blob: b2a1cbc72ec08829ea6f79ab903629e0b98340a1 [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
19import com.google.android.googleapps.IGoogleLoginService;
20import com.google.android.googlelogin.GoogleLoginServiceConstants;
21
22import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080023import android.app.AlertDialog;
24import android.app.ProgressDialog;
25import android.app.SearchManager;
26import android.content.ActivityNotFoundException;
27import android.content.BroadcastReceiver;
28import android.content.ComponentName;
29import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040030import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080031import android.content.ContentValues;
32import android.content.Context;
33import android.content.DialogInterface;
34import android.content.Intent;
35import android.content.IntentFilter;
36import android.content.ServiceConnection;
Grace Klobab4da0ad2009-05-14 14:45:40 -070037import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080038import android.content.pm.PackageManager;
39import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080040import android.content.res.Configuration;
41import android.content.res.Resources;
42import android.database.Cursor;
The Android Open Source Project0c908882009-03-03 19:32:16 -080043import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010044import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080045import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080046import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040047import android.graphics.PixelFormat;
48import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080050import android.net.ConnectivityManager;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -040051import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080052import android.net.Uri;
53import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080054import android.net.http.SslCertificate;
55import android.net.http.SslError;
56import android.os.AsyncTask;
57import android.os.Bundle;
58import android.os.Debug;
59import android.os.Environment;
60import android.os.Handler;
61import android.os.IBinder;
62import android.os.Message;
63import android.os.PowerManager;
64import android.os.Process;
65import android.os.RemoteException;
66import android.os.ServiceManager;
67import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040069import android.provider.ContactsContract;
70import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080071import android.provider.Downloads;
72import android.provider.MediaStore;
The Android Open Source Project0c908882009-03-03 19:32:16 -080073import android.text.IClipboard;
74import android.text.TextUtils;
75import android.text.format.DateFormat;
76import android.text.util.Regex;
Leon Scrogginsb94bf272009-09-25 15:22:08 -040077import android.util.AttributeSet;
The Android Open Source Project0c908882009-03-03 19:32:16 -080078import android.util.Log;
79import android.view.ContextMenu;
80import android.view.Gravity;
81import android.view.KeyEvent;
82import android.view.LayoutInflater;
83import android.view.Menu;
84import android.view.MenuInflater;
85import android.view.MenuItem;
86import android.view.View;
87import android.view.ViewGroup;
88import android.view.Window;
89import android.view.WindowManager;
90import android.view.ContextMenu.ContextMenuInfo;
91import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080092import android.webkit.CookieManager;
93import android.webkit.CookieSyncManager;
94import android.webkit.DownloadListener;
95import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070096import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080097import android.webkit.SslErrorHandler;
98import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010099import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800100import android.webkit.WebChromeClient;
101import android.webkit.WebHistoryItem;
102import android.webkit.WebIconDatabase;
103import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800104import android.widget.EditText;
105import android.widget.FrameLayout;
106import android.widget.LinearLayout;
107import android.widget.TextView;
108import android.widget.Toast;
109
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400110import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800111import java.io.File;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800112import java.net.MalformedURLException;
113import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700114import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800115import java.net.URL;
116import java.net.URLEncoder;
117import java.text.ParseException;
118import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800119import java.util.HashMap;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import java.util.regex.Matcher;
121import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800122
123public class BrowserActivity extends Activity
Grace Kloba5942df02009-09-18 11:48:29 -0700124 implements View.OnCreateContextMenuListener,
The Android Open Source Project0c908882009-03-03 19:32:16 -0800125 DownloadListener {
126
Dave Bort31a6d1c2009-04-13 15:56:49 -0700127 /* Define some aliases to make these debugging flags easier to refer to.
128 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
129 */
130 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
131 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
132 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
133
The Android Open Source Project0c908882009-03-03 19:32:16 -0800134 private IGoogleLoginService mGls = null;
135 private ServiceConnection mGlsConnection = null;
136
Satish Sampath565505b2009-05-29 15:37:27 +0100137 // These are single-character shortcuts for searching popular sources.
138 private static final int SHORTCUT_INVALID = 0;
139 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
140 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
141 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
142 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
143
The Android Open Source Project0c908882009-03-03 19:32:16 -0800144 private void setupHomePage() {
145 final Runnable getAccount = new Runnable() {
146 public void run() {
147 // Lower priority
148 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
149 // get the default home page
150 String homepage = mSettings.getHomePage();
151
152 try {
153 if (mGls == null) return;
154
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700155 if (!homepage.startsWith("http://www.google.")) return;
156 if (homepage.indexOf('?') == -1) return;
157
The Android Open Source Project0c908882009-03-03 19:32:16 -0800158 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
159 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
160
161 // three cases:
162 //
163 // hostedUser == googleUser
164 // The device has only a google account
165 //
166 // hostedUser != googleUser
167 // The device has a hosted account and a google account
168 //
169 // hostedUser != null, googleUser == null
170 // The device has only a hosted account (so far)
171
172 // developers might have no accounts at all
173 if (hostedUser == null) return;
174
175 if (googleUser == null || !hostedUser.equals(googleUser)) {
176 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700177 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800178 }
179 } catch (RemoteException ignore) {
180 // Login service died; carry on
181 } catch (RuntimeException ignore) {
182 // Login service died; carry on
183 } finally {
184 finish(homepage);
185 }
186 }
187
188 private void finish(final String homepage) {
189 mHandler.post(new Runnable() {
190 public void run() {
191 mSettings.setHomePage(BrowserActivity.this, homepage);
192 resumeAfterCredentials();
193
194 // as this is running in a separate thread,
195 // BrowserActivity's onDestroy() may have been called,
196 // which also calls unbindService().
197 if (mGlsConnection != null) {
198 // we no longer need to keep GLS open
199 unbindService(mGlsConnection);
200 mGlsConnection = null;
201 }
202 } });
203 } };
204
205 final boolean[] done = { false };
206
207 // Open a connection to the Google Login Service. The first
208 // time the connection is established, set up the homepage depending on
209 // the account in a background thread.
210 mGlsConnection = new ServiceConnection() {
211 public void onServiceConnected(ComponentName className, IBinder service) {
212 mGls = IGoogleLoginService.Stub.asInterface(service);
213 if (done[0] == false) {
214 done[0] = true;
215 Thread account = new Thread(getAccount);
216 account.setName("GLSAccount");
217 account.start();
218 }
219 }
220 public void onServiceDisconnected(ComponentName className) {
221 mGls = null;
222 }
223 };
224
225 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
226 mGlsConnection, Context.BIND_AUTO_CREATE);
227 }
228
Cary Clarka9771242009-08-11 16:42:26 -0400229 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800230 @Override
231 public Void doInBackground(File... files) {
232 if (files != null) {
233 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400234 if (!f.delete()) {
235 Log.e(LOGTAG, f.getPath() + " was not deleted");
236 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800237 }
238 }
239 return null;
240 }
241 }
242
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400243 /**
244 * This layout holds everything you see below the status bar, including the
245 * error console, the custom view container, and the webviews.
246 */
247 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400248
Grace Kloba22ac16e2009-10-07 18:00:23 -0700249 @Override
250 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700251 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800252 Log.v(LOGTAG, this + " onStart");
253 }
254 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800255 // test the browser in OpenGL
256 // requestWindowFeature(Window.FEATURE_OPENGL);
257
258 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
259
260 mResolver = getContentResolver();
261
Grace Kloba0923d692009-09-23 21:37:25 -0700262 // If this was a web search request, pass it on to the default web
263 // search provider and finish this activity.
264 if (handleWebSearchIntent(getIntent())) {
265 finish();
266 return;
267 }
268
The Android Open Source Project0c908882009-03-03 19:32:16 -0800269 mSecLockIcon = Resources.getSystem().getDrawable(
270 android.R.drawable.ic_secure);
271 mMixLockIcon = Resources.getSystem().getDrawable(
272 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800273
Leon Scroggins81db3662009-06-04 17:45:11 -0400274 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
275 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400276 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
277 .inflate(R.layout.custom_screen, null);
278 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
279 R.id.main_content);
280 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
281 .findViewById(R.id.error_console);
282 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
283 .findViewById(R.id.fullscreen_custom_content);
284 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400285 mTitleBar = new TitleBar(this);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400286 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800287
288 // Create the tab control and our initial tab
289 mTabControl = new TabControl(this);
290
291 // Open the icon database and retain all the bookmark urls for favicons
292 retainIconsOnStartup();
293
294 // Keep a settings instance handy.
295 mSettings = BrowserSettings.getInstance();
296 mSettings.setTabControl(mTabControl);
297 mSettings.loadFromDb(this);
298
299 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
300 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
301
Grace Klobaa34f6862009-07-31 16:28:17 -0700302 /* enables registration for changes in network status from
303 http stack */
304 mNetworkStateChangedFilter = new IntentFilter();
305 mNetworkStateChangedFilter.addAction(
306 ConnectivityManager.CONNECTIVITY_ACTION);
307 mNetworkStateIntentReceiver = new BroadcastReceiver() {
308 @Override
309 public void onReceive(Context context, Intent intent) {
310 if (intent.getAction().equals(
311 ConnectivityManager.CONNECTIVITY_ACTION)) {
Patrick Scotteb6ab2a2009-09-16 10:00:17 -0400312 NetworkInfo info =
313 (NetworkInfo) intent.getParcelableExtra(
314 ConnectivityManager.EXTRA_NETWORK_INFO);
315 onNetworkToggle(
316 (info != null) ? info.isConnected() : false);
Grace Klobaa34f6862009-07-31 16:28:17 -0700317 }
318 }
319 };
320
Grace Kloba615c6c92009-08-03 10:22:44 -0700321 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
322 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
323 filter.addDataScheme("package");
324 mPackageInstallationReceiver = new BroadcastReceiver() {
325 @Override
326 public void onReceive(Context context, Intent intent) {
327 final String action = intent.getAction();
328 final String packageName = intent.getData()
329 .getSchemeSpecificPart();
330 final boolean replacing = intent.getBooleanExtra(
331 Intent.EXTRA_REPLACING, false);
332 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
333 // if it is replacing, refreshPlugins() when adding
334 return;
335 }
336 PackageManager pm = BrowserActivity.this.getPackageManager();
337 PackageInfo pkgInfo = null;
338 try {
339 pkgInfo = pm.getPackageInfo(packageName,
340 PackageManager.GET_PERMISSIONS);
341 } catch (PackageManager.NameNotFoundException e) {
342 return;
343 }
344 if (pkgInfo != null) {
345 String permissions[] = pkgInfo.requestedPermissions;
346 if (permissions == null) {
347 return;
348 }
349 boolean permissionOk = false;
350 for (String permit : permissions) {
351 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
352 permissionOk = true;
353 break;
354 }
355 }
356 if (permissionOk) {
357 PluginManager.getInstance(BrowserActivity.this)
358 .refreshPlugins(
359 Intent.ACTION_PACKAGE_ADDED
360 .equals(action));
361 }
362 }
363 }
364 };
365 registerReceiver(mPackageInstallationReceiver, filter);
366
The Android Open Source Project0c908882009-03-03 19:32:16 -0800367 if (!mTabControl.restoreState(icicle)) {
368 // clear up the thumbnail directory if we can't restore the state as
369 // none of the files in the directory are referenced any more.
370 new ClearThumbnails().execute(
371 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700372 // there is no quit on Android. But if we can't restore the state,
373 // we can treat it as a new Browser, remove the old session cookies.
374 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800375 final Intent intent = getIntent();
376 final Bundle extra = intent.getExtras();
377 // Create an initial tab.
378 // If the intent is ACTION_VIEW and data is not null, the Browser is
379 // invoked to view the content by another application. In this case,
380 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700381 UrlData urlData = getUrlDataFromIntent(intent);
382
Grace Kloba22ac16e2009-10-07 18:00:23 -0700383 final Tab t = mTabControl.createNewTab(
The Android Open Source Project0c908882009-03-03 19:32:16 -0800384 Intent.ACTION_VIEW.equals(intent.getAction()) &&
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700385 intent.getData() != null,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700386 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800387 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800388 attachTabToContentView(t);
389 WebView webView = t.getWebView();
390 if (extra != null) {
391 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
392 if (scale > 0 && scale <= 1000) {
393 webView.setInitialScale(scale);
394 }
395 }
396 // If we are not restoring from an icicle, then there is a high
397 // likely hood this is the first run. So, check to see if the
398 // homepage needs to be configured and copy any plugins from our
399 // asset directory to the data partition.
400 if ((extra == null || !extra.getBoolean("testing"))
401 && !mSettings.isLoginInitialized()) {
402 setupHomePage();
403 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800404
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700405 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400406 if (mSettings.isLoginInitialized()) {
407 webView.loadUrl(mSettings.getHomePage());
408 } else {
409 waitForCredentials();
410 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800411 } else {
Grace Kloba81678d92009-06-30 07:09:56 -0700412 if (extra != null) {
413 urlData.setPostData(extra
414 .getByteArray(Browser.EXTRA_POST_DATA));
415 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700416 urlData.loadIn(webView);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800417 }
418 } else {
419 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400420 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800421 attachTabToContentView(mTabControl.getCurrentTab());
422 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700423
Feng Qianb3c02da2009-06-29 15:58:08 -0700424 // Read JavaScript flags if it exists.
425 String jsFlags = mSettings.getJsFlags();
426 if (jsFlags.trim().length() != 0) {
427 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
428 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800429 }
430
431 @Override
432 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700433 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800434 // When a tab is closed on exit, the current tab index is set to -1.
435 // Reset before proceed as Browser requires the current tab to be set.
436 if (current == null) {
437 // Try to reset the tab in case the index was incorrect.
438 current = mTabControl.getTab(0);
439 if (current == null) {
440 // No tabs at all so just ignore this intent.
441 return;
442 }
443 mTabControl.setCurrentTab(current);
444 attachTabToContentView(current);
445 resetTitleAndIcon(current.getWebView());
446 }
447 final String action = intent.getAction();
448 final int flags = intent.getFlags();
449 if (Intent.ACTION_MAIN.equals(action) ||
450 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
451 // just resume the browser
452 return;
453 }
454 if (Intent.ACTION_VIEW.equals(action)
455 || Intent.ACTION_SEARCH.equals(action)
456 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
457 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100458 // If this was a search request (e.g. search query directly typed into the address bar),
459 // pass it on to the default web search provider.
460 if (handleWebSearchIntent(intent)) {
461 return;
462 }
463
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700464 UrlData urlData = getUrlDataFromIntent(intent);
465 if (urlData.isEmpty()) {
466 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800467 }
Grace Kloba81678d92009-06-30 07:09:56 -0700468 urlData.setPostData(intent
469 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700470
Grace Klobacc634032009-07-28 15:58:19 -0700471 final String appId = intent
472 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
473 if (Intent.ACTION_VIEW.equals(action)
474 && !getPackageName().equals(appId)
475 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700476 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700477 if (appTab != null) {
478 Log.i(LOGTAG, "Reusing tab for " + appId);
479 // Dismiss the subwindow if applicable.
480 dismissSubWindow(appTab);
481 // Since we might kill the WebView, remove it from the
482 // content view first.
483 removeTabFromContentView(appTab);
484 // Recreate the main WebView after destroying the old one.
485 // If the WebView has the same original url and is on that
486 // page, it can be reused.
487 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700488 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100489
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700490 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400491 switchToTab(mTabControl.getTabIndex(appTab));
492 if (needsLoad) {
493 urlData.loadIn(appTab.getWebView());
494 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700495 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400496 // If the tab was the current tab, we have to attach
497 // it to the view system again.
498 attachTabToContentView(appTab);
499 if (needsLoad) {
500 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700501 }
502 }
503 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400504 } else {
505 // No matching application tab, try to find a regular tab
506 // with a matching url.
507 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400508 if (appTab != null) {
509 if (current != appTab) {
510 switchToTab(mTabControl.getTabIndex(appTab));
511 }
512 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400513 } else {
514 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
515 // will be opened in a new tab unless we have reached
516 // MAX_TABS. Then the url will be opened in the current
517 // tab. If a new tab is created, it will have "true" for
518 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400519 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400520 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700521 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800522 } else {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700523 if ("about:debug".equals(urlData.mUrl)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800524 mSettings.toggleDebugSettings();
525 return;
526 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400527 // Get rid of the subwindow if it exists
528 dismissSubWindow(current);
529 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800530 }
531 }
532 }
533
Satish Sampath565505b2009-05-29 15:37:27 +0100534 private int parseUrlShortcut(String url) {
535 if (url == null) return SHORTCUT_INVALID;
536
537 // FIXME: quick search, need to be customized by setting
538 if (url.length() > 2 && url.charAt(1) == ' ') {
539 switch (url.charAt(0)) {
540 case 'g': return SHORTCUT_GOOGLE_SEARCH;
541 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
542 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
543 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
544 }
545 }
546 return SHORTCUT_INVALID;
547 }
548
549 /**
550 * Launches the default web search activity with the query parameters if the given intent's data
551 * are identified as plain search terms and not URLs/shortcuts.
552 * @return true if the intent was handled and web search activity was launched, false if not.
553 */
554 private boolean handleWebSearchIntent(Intent intent) {
555 if (intent == null) return false;
556
557 String url = null;
558 final String action = intent.getAction();
559 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700560 Uri data = intent.getData();
561 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100562 } else if (Intent.ACTION_SEARCH.equals(action)
563 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
564 || Intent.ACTION_WEB_SEARCH.equals(action)) {
565 url = intent.getStringExtra(SearchManager.QUERY);
566 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100567 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
568 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100569 }
570
571 /**
572 * Launches the default web search activity with the query parameters if the given url string
573 * was identified as plain search terms and not URL/shortcut.
574 * @return true if the request was handled and web search activity was launched, false if not.
575 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100576 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100577 if (inUrl == null) return false;
578
579 // In general, we shouldn't modify URL from Intent.
580 // But currently, we get the user-typed URL from search box as well.
581 String url = fixUrl(inUrl).trim();
582
583 // URLs and site specific search shortcuts are handled by the regular flow of control, so
584 // return early.
585 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100586 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100587 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
588 return false;
589 }
590
591 Browser.updateVisitedHistory(mResolver, url, false);
592 Browser.addSearchUrl(mResolver, url);
593
594 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
595 intent.addCategory(Intent.CATEGORY_DEFAULT);
596 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100597 if (appData != null) {
598 intent.putExtra(SearchManager.APP_DATA, appData);
599 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100600 if (extraData != null) {
601 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
602 }
Grace Klobacc634032009-07-28 15:58:19 -0700603 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100604 startActivity(intent);
605
606 return true;
607 }
608
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700609 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800610 String url = null;
611 if (intent != null) {
612 final String action = intent.getAction();
613 if (Intent.ACTION_VIEW.equals(action)) {
614 url = smartUrlFilter(intent.getData());
615 if (url != null && url.startsWith("content:")) {
616 /* Append mimetype so webview knows how to display */
617 String mimeType = intent.resolveType(getContentResolver());
618 if (mimeType != null) {
619 url += "?" + mimeType;
620 }
621 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700622 if ("inline:".equals(url)) {
623 return new InlinedUrlData(
624 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
625 intent.getType(),
626 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
627 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
628 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800629 } else if (Intent.ACTION_SEARCH.equals(action)
630 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
631 || Intent.ACTION_WEB_SEARCH.equals(action)) {
632 url = intent.getStringExtra(SearchManager.QUERY);
633 if (url != null) {
634 mLastEnteredUrl = url;
635 // Don't add Urls, just search terms.
636 // Urls will get added when the page is loaded.
637 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
638 Browser.updateVisitedHistory(mResolver, url, false);
639 }
640 // In general, we shouldn't modify URL from Intent.
641 // But currently, we get the user-typed URL from search box as well.
642 url = fixUrl(url);
643 url = smartUrlFilter(url);
644 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
645 if (url.contains(searchSource)) {
646 String source = null;
647 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
648 if (appData != null) {
649 source = appData.getString(SearchManager.SOURCE);
650 }
651 if (TextUtils.isEmpty(source)) {
652 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
653 }
654 url = url.replace(searchSource, "&source=android-"+source+"&");
655 }
656 }
657 }
658 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700659 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800660 }
661
662 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400663 // FIXME: Converting the url to lower case
664 // duplicates functionality in smartUrlFilter().
665 // However, changing all current callers of fixUrl to
666 // call smartUrlFilter in addition may have unwanted
667 // consequences, and is deferred for now.
668 int colon = inUrl.indexOf(':');
669 boolean allLower = true;
670 for (int index = 0; index < colon; index++) {
671 char ch = inUrl.charAt(index);
672 if (!Character.isLetter(ch)) {
673 break;
674 }
675 allLower &= Character.isLowerCase(ch);
676 if (index == colon - 1 && !allLower) {
677 inUrl = inUrl.substring(0, colon).toLowerCase()
678 + inUrl.substring(colon);
679 }
680 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800681 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
682 return inUrl;
683 if (inUrl.startsWith("http:") ||
684 inUrl.startsWith("https:")) {
685 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
686 inUrl = inUrl.replaceFirst("/", "//");
687 } else inUrl = inUrl.replaceFirst(":", "://");
688 }
689 return inUrl;
690 }
691
Grace Kloba22ac16e2009-10-07 18:00:23 -0700692 @Override
693 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800694 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700695 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800696 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
697 }
698
699 if (!mActivityInPause) {
700 Log.e(LOGTAG, "BrowserActivity is already resumed.");
701 return;
702 }
703
Mike Reed7bfa63b2009-05-28 11:08:32 -0400704 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800705 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400706 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800707
708 if (mWakeLock.isHeld()) {
709 mHandler.removeMessages(RELEASE_WAKELOCK);
710 mWakeLock.release();
711 }
712
713 if (mCredsDlg != null) {
714 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
715 // In case credential request never comes back
716 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
717 }
718 }
719
720 registerReceiver(mNetworkStateIntentReceiver,
721 mNetworkStateChangedFilter);
722 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800723 }
724
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400725 /**
726 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400727 * would change its appearance, use a different TitleBar to show overlayed
728 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400729 */
730 private TitleBar mFakeTitleBar;
731
732 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400733 * Holder for the fake title bar. It will have a foreground shadow, as well
734 * as a white background, so the fake title bar looks like the real one.
735 */
736 private ViewGroup mFakeTitleBarHolder;
737
738 /**
739 * Layout parameters for the fake title bar within mFakeTitleBarHolder
740 */
741 private FrameLayout.LayoutParams mFakeTitleBarParams
742 = new FrameLayout.LayoutParams(
Leon Scrogginsc01e4a82009-09-16 14:41:00 -0400743 ViewGroup.LayoutParams.FILL_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400744 ViewGroup.LayoutParams.WRAP_CONTENT);
745 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400746 * Keeps track of whether the options menu is open. This is important in
747 * determining whether to show or hide the title bar overlay.
748 */
749 private boolean mOptionsMenuOpen;
750
751 /**
752 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
753 * of whether the configuration has changed. The first onMenuOpened call
754 * after a configuration change is simply a reopening of the same menu
755 * (i.e. mIconView did not change).
756 */
757 private boolean mConfigChanged;
758
759 /**
760 * Whether or not the options menu is in its smaller, icon menu form. When
761 * true, we want the title bar overlay to be up. When false, we do not.
762 * Only meaningful if mOptionsMenuOpen is true.
763 */
764 private boolean mIconView;
765
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400766 @Override
767 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400768 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
769 if (mOptionsMenuOpen) {
770 if (mConfigChanged) {
771 // We do not need to make any changes to the state of the
772 // title bar, since the only thing that happened was a
773 // change in orientation
774 mConfigChanged = false;
775 } else {
776 if (mIconView) {
777 // Switching the menu to expanded view, so hide the
778 // title bar.
779 hideFakeTitleBar();
780 mIconView = false;
781 } else {
782 // Switching the menu back to icon view, so show the
783 // title bar once again.
784 showFakeTitleBar();
785 mIconView = true;
786 }
787 }
788 } else {
789 // The options menu is closed, so open it, and show the title
790 showFakeTitleBar();
791 mOptionsMenuOpen = true;
792 mConfigChanged = false;
793 mIconView = true;
794 }
795 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400796 return true;
797 }
798
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400799 /**
800 * Special class used exclusively for the shadow drawn underneath the fake
801 * title bar. The shadow does not need to be drawn if the WebView
802 * underneath is scrolled to the top, because it will draw directly on top
803 * of the embedded shadow.
804 */
805 private static class Shadow extends View {
806 private WebView mWebView;
807
808 public Shadow(Context context, AttributeSet attrs) {
809 super(context, attrs);
810 }
811
812 public void setWebView(WebView view) {
813 mWebView = view;
814 }
815
816 @Override
817 public void draw(Canvas canvas) {
818 // In general onDraw is the method to override, but we care about
819 // whether or not the background gets drawn, which happens in draw()
820 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
821 super.draw(canvas);
822 }
823 // Need to invalidate so that if the scroll position changes, we
824 // still draw as appropriate.
825 invalidate();
826 }
827 }
828
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400829 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400830 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400831 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400832 && !mActivityInPause && decor != null
833 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400834 Rect visRect = new Rect();
835 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
836 if (LOGD_ENABLED) {
837 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
838 }
839 return;
840 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400841
842 WindowManager manager
843 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
844
845 // Add the title bar to the window manager so it can receive touches
846 // while the menu is up
847 WindowManager.LayoutParams params
848 = new WindowManager.LayoutParams(
849 ViewGroup.LayoutParams.FILL_PARENT,
850 ViewGroup.LayoutParams.WRAP_CONTENT,
851 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
852 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400853 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400854 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400855 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400856 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400857 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400858 // XXX : Without providing an offset, the fake title bar will be
859 // placed underneath the status bar. Use the global visible rect
860 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400861 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400862 // Add a holder for the title bar. It also holds a shadow to show
863 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400864 if (mFakeTitleBarHolder == null) {
865 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
866 .inflate(R.layout.title_bar_bg, null);
867 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400868 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
869 R.id.shadow);
870 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400871 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400872 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400873 }
874 }
875
876 @Override
877 public void onOptionsMenuClosed(Menu menu) {
878 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400879 if (!mInLoad) {
880 hideFakeTitleBar();
881 } else if (!mIconView) {
882 // The page is currently loading, and we are in expanded mode, so
883 // we were not showing the menu. Show it once again. It will be
884 // removed when the page finishes.
885 showFakeTitleBar();
886 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400887 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700888
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400889 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400890 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400891 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
892 mFakeTitleBarHolder.getLayoutParams();
893 WebView mainView = mTabControl.getCurrentWebView();
894 // Although we decided whether or not to animate based on the current
895 // scroll position, the scroll position may have changed since the
896 // fake title bar was displayed. Make sure it has the appropriate
897 // animation/lack thereof before removing.
898 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400899 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400900 WindowManager manager
901 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -0400902 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400903 mFakeTitleBarHolder.removeView(mFakeTitleBar);
904 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400905 }
906
The Android Open Source Project0c908882009-03-03 19:32:16 -0800907 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400908 * Special method for the fake title bar to call when displaying its context
909 * menu, since it is in its own Window, and its parent does not show a
910 * context menu.
911 */
912 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400913 if (null == mTitleBar.getParent()) {
914 return;
915 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400916 openContextMenu(mTitleBar);
917 }
918
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400919 @Override
920 public void onContextMenuClosed(Menu menu) {
921 super.onContextMenuClosed(menu);
922 if (mInLoad) {
923 showFakeTitleBar();
924 }
925 }
926
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400927 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800928 * onSaveInstanceState(Bundle map)
929 * onSaveInstanceState is called right before onStop(). The map contains
930 * the saved state.
931 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700932 @Override
933 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700934 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800935 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
936 }
937 // the default implementation requires each view to have an id. As the
938 // browser handles the state itself and it doesn't use id for the views,
939 // don't call the default implementation. Otherwise it will trigger the
940 // warning like this, "couldn't save which view has focus because the
941 // focused view XXX has no id".
942
943 // Save all the tabs
944 mTabControl.saveState(outState);
945 }
946
Grace Kloba22ac16e2009-10-07 18:00:23 -0700947 @Override
948 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800949 super.onPause();
950
951 if (mActivityInPause) {
952 Log.e(LOGTAG, "BrowserActivity is already paused.");
953 return;
954 }
955
Mike Reed7bfa63b2009-05-28 11:08:32 -0400956 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800957 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400958 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800959 mWakeLock.acquire();
960 mHandler.sendMessageDelayed(mHandler
961 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
962 }
963
964 // Clear the credentials toast if it is up
965 if (mCredsDlg != null && mCredsDlg.isShowing()) {
966 mCredsDlg.dismiss();
967 }
968 mCredsDlg = null;
969
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400970 // FIXME: This removes the active tabs page and resets the menu to
971 // MAIN_MENU. A better solution might be to do this work in onNewIntent
972 // but then we would need to save it in onSaveInstanceState and restore
973 // it in onCreate/onRestoreInstanceState
974 if (mActiveTabsPage != null) {
975 removeActiveTabPage(true);
976 }
977
The Android Open Source Project0c908882009-03-03 19:32:16 -0800978 cancelStopToast();
979
980 // unregister network state listener
981 unregisterReceiver(mNetworkStateIntentReceiver);
982 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800983 }
984
Grace Kloba22ac16e2009-10-07 18:00:23 -0700985 @Override
986 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700987 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800988 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
989 }
990 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700991
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400992 if (mUploadMessage != null) {
993 mUploadMessage.onReceiveValue(null);
994 mUploadMessage = null;
995 }
996
Grace Kloba0923d692009-09-23 21:37:25 -0700997 if (mTabControl == null) return;
998
Grace Kloba1fc98a32009-10-21 13:23:08 -0700999 // Remove the fake title bar if it is there
1000 hideFakeTitleBar();
1001
The Android Open Source Project0c908882009-03-03 19:32:16 -08001002 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001003 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001004 if (t != null) {
1005 dismissSubWindow(t);
1006 removeTabFromContentView(t);
1007 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001008 // Destroy all the tabs
1009 mTabControl.destroy();
1010 WebIconDatabase.getInstance().close();
1011 if (mGlsConnection != null) {
1012 unbindService(mGlsConnection);
1013 mGlsConnection = null;
1014 }
1015
Grace Klobab4da0ad2009-05-14 14:45:40 -07001016 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001017 }
1018
1019 @Override
1020 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001021 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001022 super.onConfigurationChanged(newConfig);
1023
1024 if (mPageInfoDialog != null) {
1025 mPageInfoDialog.dismiss();
1026 showPageInfo(
1027 mPageInfoView,
1028 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1029 }
1030 if (mSSLCertificateDialog != null) {
1031 mSSLCertificateDialog.dismiss();
1032 showSSLCertificate(
1033 mSSLCertificateView);
1034 }
1035 if (mSSLCertificateOnErrorDialog != null) {
1036 mSSLCertificateOnErrorDialog.dismiss();
1037 showSSLCertificateOnError(
1038 mSSLCertificateOnErrorView,
1039 mSSLCertificateOnErrorHandler,
1040 mSSLCertificateOnErrorError);
1041 }
1042 if (mHttpAuthenticationDialog != null) {
1043 String title = ((TextView) mHttpAuthenticationDialog
1044 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1045 .toString();
1046 String name = ((TextView) mHttpAuthenticationDialog
1047 .findViewById(R.id.username_edit)).getText().toString();
1048 String password = ((TextView) mHttpAuthenticationDialog
1049 .findViewById(R.id.password_edit)).getText().toString();
1050 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1051 .getId();
1052 mHttpAuthenticationDialog.dismiss();
1053 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1054 name, password, focusId);
1055 }
1056 if (mFindDialog != null && mFindDialog.isShowing()) {
1057 mFindDialog.onConfigurationChanged(newConfig);
1058 }
1059 }
1060
Grace Kloba22ac16e2009-10-07 18:00:23 -07001061 @Override
1062 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001063 super.onLowMemory();
1064 mTabControl.freeMemory();
1065 }
1066
Mike Reed7bfa63b2009-05-28 11:08:32 -04001067 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001068 Tab tab = mTabControl.getCurrentTab();
1069 boolean inLoad = tab.inLoad();
1070 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001071 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001072 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001073 if (w != null) {
1074 w.resumeTimers();
1075 }
1076 return true;
1077 } else {
1078 return false;
1079 }
1080 }
1081
Mike Reed7bfa63b2009-05-28 11:08:32 -04001082 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001083 Tab tab = mTabControl.getCurrentTab();
1084 boolean inLoad = tab.inLoad();
1085 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001086 CookieSyncManager.getInstance().stopSync();
1087 WebView w = mTabControl.getCurrentWebView();
1088 if (w != null) {
1089 w.pauseTimers();
1090 }
1091 return true;
1092 } else {
1093 return false;
1094 }
1095 }
1096
Leon Scroggins1f005d32009-08-10 17:36:42 -04001097 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001098 /*
1099 * This function is called when we are launching for the first time. We
1100 * are waiting for the login credentials before loading Google home
1101 * pages. This way the user will be logged in straight away.
1102 */
1103 private void waitForCredentials() {
1104 // Show a toast
1105 mCredsDlg = new ProgressDialog(this);
1106 mCredsDlg.setIndeterminate(true);
1107 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1108 // If the user cancels the operation, then cancel the Google
1109 // Credentials request.
1110 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1111 mCredsDlg.show();
1112
1113 // We set a timeout for the retrieval of credentials in onResume()
1114 // as that is when we have freed up some CPU time to get
1115 // the login credentials.
1116 }
1117
1118 /*
1119 * If we have received the credentials or we have timed out and we are
1120 * showing the credentials dialog, then it is time to move on.
1121 */
1122 private void resumeAfterCredentials() {
1123 if (mCredsDlg == null) {
1124 return;
1125 }
1126
1127 // Clear the toast
1128 if (mCredsDlg.isShowing()) {
1129 mCredsDlg.dismiss();
1130 }
1131 mCredsDlg = null;
1132
1133 // Clear any pending timeout
1134 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1135
1136 // Load the page
1137 WebView w = mTabControl.getCurrentWebView();
1138 if (w != null) {
1139 w.loadUrl(mSettings.getHomePage());
1140 }
1141
1142 // Update the settings, need to do this last as it can take a moment
1143 // to persist the settings. In the mean time we could be loading
1144 // content.
1145 mSettings.setLoginInitialized(this);
1146 }
1147
1148 // Open the icon database and retain all the icons for visited sites.
1149 private void retainIconsOnStartup() {
1150 final WebIconDatabase db = WebIconDatabase.getInstance();
1151 db.open(getDir("icons", 0).getPath());
1152 try {
1153 Cursor c = Browser.getAllBookmarks(mResolver);
1154 if (!c.moveToFirst()) {
1155 c.deactivate();
1156 return;
1157 }
1158 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1159 do {
1160 String url = c.getString(urlIndex);
1161 db.retainIconForPageUrl(url);
1162 } while (c.moveToNext());
1163 c.deactivate();
1164 } catch (IllegalStateException e) {
1165 Log.e(LOGTAG, "retainIconsOnStartup", e);
1166 }
1167 }
1168
1169 // Helper method for getting the top window.
1170 WebView getTopWindow() {
1171 return mTabControl.getCurrentTopWebView();
1172 }
1173
Grace Kloba22ac16e2009-10-07 18:00:23 -07001174 TabControl getTabControl() {
1175 return mTabControl;
1176 }
1177
The Android Open Source Project0c908882009-03-03 19:32:16 -08001178 @Override
1179 public boolean onCreateOptionsMenu(Menu menu) {
1180 super.onCreateOptionsMenu(menu);
1181
1182 MenuInflater inflater = getMenuInflater();
1183 inflater.inflate(R.menu.browser, menu);
1184 mMenu = menu;
1185 updateInLoadMenuItems();
1186 return true;
1187 }
1188
1189 /**
1190 * As the menu can be open when loading state changes
1191 * we must manually update the state of the stop/reload menu
1192 * item
1193 */
1194 private void updateInLoadMenuItems() {
1195 if (mMenu == null) {
1196 return;
1197 }
1198 MenuItem src = mInLoad ?
1199 mMenu.findItem(R.id.stop_menu_id):
1200 mMenu.findItem(R.id.reload_menu_id);
1201 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1202 dest.setIcon(src.getIcon());
1203 dest.setTitle(src.getTitle());
1204 }
1205
1206 @Override
1207 public boolean onContextItemSelected(MenuItem item) {
1208 // chording is not an issue with context menus, but we use the same
1209 // options selector, so set mCanChord to true so we can access them.
1210 mCanChord = true;
1211 int id = item.getItemId();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001212 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001213 // For the context menu from the title bar
1214 case R.id.title_bar_share_page_url:
1215 case R.id.title_bar_copy_page_url:
1216 WebView mainView = mTabControl.getCurrentWebView();
1217 if (null == mainView) {
1218 return false;
1219 }
1220 if (id == R.id.title_bar_share_page_url) {
1221 Browser.sendString(this, mainView.getUrl());
1222 } else {
1223 copy(mainView.getUrl());
1224 }
1225 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001226 // -- Browser context menu
1227 case R.id.open_context_menu_id:
1228 case R.id.open_newtab_context_menu_id:
1229 case R.id.bookmark_context_menu_id:
1230 case R.id.save_link_context_menu_id:
1231 case R.id.share_link_context_menu_id:
1232 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001233 final WebView webView = getTopWindow();
1234 if (null == webView) {
1235 return false;
1236 }
1237 final HashMap hrefMap = new HashMap();
1238 hrefMap.put("webview", webView);
1239 final Message msg = mHandler.obtainMessage(
1240 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001241 webView.requestFocusNodeHref(msg);
1242 break;
1243
1244 default:
1245 // For other context menus
1246 return onOptionsItemSelected(item);
1247 }
1248 mCanChord = false;
1249 return true;
1250 }
1251
1252 private Bundle createGoogleSearchSourceBundle(String source) {
1253 Bundle bundle = new Bundle();
1254 bundle.putString(SearchManager.SOURCE, source);
1255 return bundle;
1256 }
1257
1258 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001259 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001260 */
1261 @Override
1262 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001263 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001264 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001265 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001266 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001267 return true;
1268 }
1269
1270 @Override
1271 public void startSearch(String initialQuery, boolean selectInitialQuery,
1272 Bundle appSearchData, boolean globalSearch) {
1273 if (appSearchData == null) {
1274 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1275 }
1276 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1277 }
1278
Leon Scroggins1f005d32009-08-10 17:36:42 -04001279 /**
1280 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1281 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001282 * @param index Index of the tab to change to, as defined by
1283 * mTabControl.getTabIndex(Tab t).
1284 * @return boolean True if we successfully switched to a different tab. If
1285 * the indexth tab is null, or if that tab is the same as
1286 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001287 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001288 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001289 Tab tab = mTabControl.getTab(index);
1290 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001291 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001292 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001293 }
1294 if (currentTab != null) {
1295 // currentTab may be null if it was just removed. In that case,
1296 // we do not need to remove it
1297 removeTabFromContentView(currentTab);
1298 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001299 mTabControl.setCurrentTab(tab);
1300 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001301 resetTitleIconAndProgress();
1302 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001303 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001304 }
1305
Grace Kloba22ac16e2009-10-07 18:00:23 -07001306 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001307 return openTabAndShow(mSettings.getHomePage(), false, null);
1308 }
1309
Leon Scroggins1f005d32009-08-10 17:36:42 -04001310 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001311 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001312 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001313 // This is the last tab. Open a new one, with the home
1314 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001315 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001316 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001317 return;
1318 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001319 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001320 int indexToShow = -1;
1321 if (parent != null) {
1322 indexToShow = mTabControl.getTabIndex(parent);
1323 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001324 final int currentIndex = mTabControl.getCurrentIndex();
1325 // Try to move to the tab to the right
1326 indexToShow = currentIndex + 1;
1327 if (indexToShow > mTabControl.getTabCount() - 1) {
1328 // Try to move to the tab to the left
1329 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001330 }
1331 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001332 if (switchToTab(indexToShow)) {
1333 // Close window
1334 closeTab(current);
1335 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001336 }
1337
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001338 private ActiveTabsPage mActiveTabsPage;
1339
1340 /**
1341 * Remove the active tabs page.
1342 * @param needToAttach If true, the active tabs page did not attach a tab
1343 * to the content view, so we need to do that here.
1344 */
1345 /* package */ void removeActiveTabPage(boolean needToAttach) {
1346 mContentView.removeView(mActiveTabsPage);
1347 mActiveTabsPage = null;
1348 mMenuState = R.id.MAIN_MENU;
1349 if (needToAttach) {
1350 attachTabToContentView(mTabControl.getCurrentTab());
1351 }
1352 getTopWindow().requestFocus();
1353 }
1354
The Android Open Source Project0c908882009-03-03 19:32:16 -08001355 @Override
1356 public boolean onOptionsItemSelected(MenuItem item) {
1357 if (!mCanChord) {
1358 // The user has already fired a shortcut with this hold down of the
1359 // menu key.
1360 return false;
1361 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001362 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001363 return false;
1364 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001365 if (mMenuIsDown) {
1366 // The shortcut action consumes the MENU. Even if it is still down,
1367 // it won't trigger the next shortcut action. In the case of the
1368 // shortcut action triggering a new activity, like Bookmarks, we
1369 // won't get onKeyUp for MENU. So it is important to reset it here.
1370 mMenuIsDown = false;
1371 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001372 switch (item.getItemId()) {
1373 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001374 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001375 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001376 break;
1377
Leon Scroggins64b80f32009-08-07 12:03:34 -04001378 case R.id.goto_menu_id:
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001379 onSearchRequested();
1380 break;
1381
1382 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001383 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001384 break;
1385
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001386 case R.id.active_tabs_menu_id:
1387 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1388 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001389 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001390 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1391 mActiveTabsPage.requestFocus();
1392 mMenuState = EMPTY_MENU;
1393 break;
1394
Leon Scroggins1f005d32009-08-10 17:36:42 -04001395 case R.id.add_bookmark_menu_id:
1396 Intent i = new Intent(BrowserActivity.this,
1397 AddBookmarkPage.class);
1398 WebView w = getTopWindow();
1399 i.putExtra("url", w.getUrl());
1400 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001401 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001402 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001403 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001404 break;
1405
1406 case R.id.stop_reload_menu_id:
1407 if (mInLoad) {
1408 stopLoading();
1409 } else {
1410 getTopWindow().reload();
1411 }
1412 break;
1413
1414 case R.id.back_menu_id:
1415 getTopWindow().goBack();
1416 break;
1417
1418 case R.id.forward_menu_id:
1419 getTopWindow().goForward();
1420 break;
1421
1422 case R.id.close_menu_id:
1423 // Close the subwindow if it exists.
1424 if (mTabControl.getCurrentSubWindow() != null) {
1425 dismissSubWindow(mTabControl.getCurrentTab());
1426 break;
1427 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001428 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001429 break;
1430
1431 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001432 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001433 if (current != null) {
1434 dismissSubWindow(current);
1435 current.getWebView().loadUrl(mSettings.getHomePage());
1436 }
1437 break;
1438
1439 case R.id.preferences_menu_id:
1440 Intent intent = new Intent(this,
1441 BrowserPreferencesPage.class);
1442 startActivityForResult(intent, PREFERENCES_PAGE);
1443 break;
1444
1445 case R.id.find_menu_id:
1446 if (null == mFindDialog) {
1447 mFindDialog = new FindDialog(this);
1448 }
1449 mFindDialog.setWebView(getTopWindow());
1450 mFindDialog.show();
1451 mMenuState = EMPTY_MENU;
1452 break;
1453
1454 case R.id.select_text_id:
1455 getTopWindow().emulateShiftHeld();
1456 break;
1457 case R.id.page_info_menu_id:
1458 showPageInfo(mTabControl.getCurrentTab(), false);
1459 break;
1460
1461 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001462 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001463 break;
1464
1465 case R.id.share_page_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01001466 Browser.sendString(this, getTopWindow().getUrl(),
1467 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001468 break;
1469
1470 case R.id.dump_nav_menu_id:
1471 getTopWindow().debugDump();
1472 break;
1473
1474 case R.id.zoom_in_menu_id:
1475 getTopWindow().zoomIn();
1476 break;
1477
1478 case R.id.zoom_out_menu_id:
1479 getTopWindow().zoomOut();
1480 break;
1481
1482 case R.id.view_downloads_menu_id:
1483 viewDownloads(null);
1484 break;
1485
The Android Open Source Project0c908882009-03-03 19:32:16 -08001486 case R.id.window_one_menu_id:
1487 case R.id.window_two_menu_id:
1488 case R.id.window_three_menu_id:
1489 case R.id.window_four_menu_id:
1490 case R.id.window_five_menu_id:
1491 case R.id.window_six_menu_id:
1492 case R.id.window_seven_menu_id:
1493 case R.id.window_eight_menu_id:
1494 {
1495 int menuid = item.getItemId();
1496 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1497 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001498 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001499 if (desiredTab != null &&
1500 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001501 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001502 }
1503 break;
1504 }
1505 }
1506 }
1507 break;
1508
1509 default:
1510 if (!super.onOptionsItemSelected(item)) {
1511 return false;
1512 }
1513 // Otherwise fall through.
1514 }
1515 mCanChord = false;
1516 return true;
1517 }
1518
1519 public void closeFind() {
1520 mMenuState = R.id.MAIN_MENU;
1521 }
1522
Grace Kloba22ac16e2009-10-07 18:00:23 -07001523 @Override
1524 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001525 // This happens when the user begins to hold down the menu key, so
1526 // allow them to chord to get a shortcut.
1527 mCanChord = true;
1528 // Note: setVisible will decide whether an item is visible; while
1529 // setEnabled() will decide whether an item is enabled, which also means
1530 // whether the matching shortcut key will function.
1531 super.onPrepareOptionsMenu(menu);
1532 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001533 case EMPTY_MENU:
1534 if (mCurrentMenuState != mMenuState) {
1535 menu.setGroupVisible(R.id.MAIN_MENU, false);
1536 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1537 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001538 }
1539 break;
1540 default:
1541 if (mCurrentMenuState != mMenuState) {
1542 menu.setGroupVisible(R.id.MAIN_MENU, true);
1543 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1544 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001545 }
1546 final WebView w = getTopWindow();
1547 boolean canGoBack = false;
1548 boolean canGoForward = false;
1549 boolean isHome = false;
1550 if (w != null) {
1551 canGoBack = w.canGoBack();
1552 canGoForward = w.canGoForward();
1553 isHome = mSettings.getHomePage().equals(w.getUrl());
1554 }
1555 final MenuItem back = menu.findItem(R.id.back_menu_id);
1556 back.setEnabled(canGoBack);
1557
1558 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1559 home.setEnabled(!isHome);
1560
1561 menu.findItem(R.id.forward_menu_id)
1562 .setEnabled(canGoForward);
1563
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001564 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001565 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001566
The Android Open Source Project0c908882009-03-03 19:32:16 -08001567 // decide whether to show the share link option
1568 PackageManager pm = getPackageManager();
1569 Intent send = new Intent(Intent.ACTION_SEND);
1570 send.setType("text/plain");
1571 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1572 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1573
The Android Open Source Project0c908882009-03-03 19:32:16 -08001574 boolean isNavDump = mSettings.isNavDump();
1575 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1576 nav.setVisible(isNavDump);
1577 nav.setEnabled(isNavDump);
1578 break;
1579 }
1580 mCurrentMenuState = mMenuState;
1581 return true;
1582 }
1583
1584 @Override
1585 public void onCreateContextMenu(ContextMenu menu, View v,
1586 ContextMenuInfo menuInfo) {
1587 WebView webview = (WebView) v;
1588 WebView.HitTestResult result = webview.getHitTestResult();
1589 if (result == null) {
1590 return;
1591 }
1592
1593 int type = result.getType();
1594 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1595 Log.w(LOGTAG,
1596 "We should not show context menu when nothing is touched");
1597 return;
1598 }
1599 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1600 // let TextView handles context menu
1601 return;
1602 }
1603
1604 // Note, http://b/issue?id=1106666 is requesting that
1605 // an inflated menu can be used again. This is not available
1606 // yet, so inflate each time (yuk!)
1607 MenuInflater inflater = getMenuInflater();
1608 inflater.inflate(R.menu.browsercontext, menu);
1609
1610 // Show the correct menu group
1611 String extra = result.getExtra();
1612 menu.setGroupVisible(R.id.PHONE_MENU,
1613 type == WebView.HitTestResult.PHONE_TYPE);
1614 menu.setGroupVisible(R.id.EMAIL_MENU,
1615 type == WebView.HitTestResult.EMAIL_TYPE);
1616 menu.setGroupVisible(R.id.GEO_MENU,
1617 type == WebView.HitTestResult.GEO_TYPE);
1618 menu.setGroupVisible(R.id.IMAGE_MENU,
1619 type == WebView.HitTestResult.IMAGE_TYPE
1620 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1621 menu.setGroupVisible(R.id.ANCHOR_MENU,
1622 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1623 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1624
1625 // Setup custom handling depending on the type
1626 switch (type) {
1627 case WebView.HitTestResult.PHONE_TYPE:
1628 menu.setHeaderTitle(Uri.decode(extra));
1629 menu.findItem(R.id.dial_context_menu_id).setIntent(
1630 new Intent(Intent.ACTION_VIEW, Uri
1631 .parse(WebView.SCHEME_TEL + extra)));
1632 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1633 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001634 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001635 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1636 addIntent);
1637 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1638 new Copy(extra));
1639 break;
1640
1641 case WebView.HitTestResult.EMAIL_TYPE:
1642 menu.setHeaderTitle(extra);
1643 menu.findItem(R.id.email_context_menu_id).setIntent(
1644 new Intent(Intent.ACTION_VIEW, Uri
1645 .parse(WebView.SCHEME_MAILTO + extra)));
1646 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1647 new Copy(extra));
1648 break;
1649
1650 case WebView.HitTestResult.GEO_TYPE:
1651 menu.setHeaderTitle(extra);
1652 menu.findItem(R.id.map_context_menu_id).setIntent(
1653 new Intent(Intent.ACTION_VIEW, Uri
1654 .parse(WebView.SCHEME_GEO
1655 + URLEncoder.encode(extra))));
1656 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1657 new Copy(extra));
1658 break;
1659
1660 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1661 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1662 TextView titleView = (TextView) LayoutInflater.from(this)
1663 .inflate(android.R.layout.browser_link_context_header,
1664 null);
1665 titleView.setText(extra);
1666 menu.setHeaderView(titleView);
1667 // decide whether to show the open link in new tab option
1668 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001669 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001670 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1671 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001672 PackageManager pm = getPackageManager();
1673 Intent send = new Intent(Intent.ACTION_SEND);
1674 send.setType("text/plain");
1675 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1676 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1677 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1678 break;
1679 }
1680 // otherwise fall through to handle image part
1681 case WebView.HitTestResult.IMAGE_TYPE:
1682 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1683 menu.setHeaderTitle(extra);
1684 }
1685 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1686 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1687 menu.findItem(R.id.download_context_menu_id).
1688 setOnMenuItemClickListener(new Download(extra));
1689 break;
1690
1691 default:
1692 Log.w(LOGTAG, "We should not get here.");
1693 break;
1694 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001695 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001696 }
1697
The Android Open Source Project0c908882009-03-03 19:32:16 -08001698 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001699 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001700 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001701 // Attach the container that contains the main WebView and any other UI
1702 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001703 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001704
1705 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001706 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001707 if (errorConsole.numberOfErrors() == 0) {
1708 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1709 } else {
1710 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1711 }
1712
1713 mErrorConsoleContainer.addView(errorConsole,
1714 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1715 ViewGroup.LayoutParams.WRAP_CONTENT));
1716 }
1717
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001718 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001719 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001720 // Request focus on the top window.
1721 t.getTopWindow().requestFocus();
1722 }
1723
1724 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001725 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001726 t.attachSubWindow(mContentView);
1727 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001728 }
1729
1730 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001731 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001732 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001733 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001734
Grace Kloba22ac16e2009-10-07 18:00:23 -07001735 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1736 if (errorConsole != null) {
1737 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001738 }
1739
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001740 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001741 if (view != null) {
1742 view.setEmbeddedTitleBar(null);
1743 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001744 }
1745
1746 // Remove the sub window if it exists. Also called by TabControl when the
1747 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001748 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001749 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001750 // dismiss the subwindow. This will destroy the WebView.
1751 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001752 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001753 }
1754
Leon Scroggins1f005d32009-08-10 17:36:42 -04001755 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001756 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001757 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001758 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001759 }
1760
1761 // This method does a ton of stuff. It will attempt to create a new tab
1762 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001763 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001764 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1765 String appId) {
1766 final Tab currentTab = mTabControl.getCurrentTab();
1767 if (mTabControl.canCreateNewTab()) {
1768 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1769 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001770 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001771 // If the last tab was removed from the active tabs page, currentTab
1772 // will be null.
1773 if (currentTab != null) {
1774 removeTabFromContentView(currentTab);
1775 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001776 // We must set the new tab as the current tab to reflect the old
1777 // animation behavior.
1778 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001779 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001780 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001781 urlData.loadIn(webview);
1782 }
1783 return tab;
1784 } else {
1785 // Get rid of the subwindow if it exists
1786 dismissSubWindow(currentTab);
1787 if (!urlData.isEmpty()) {
1788 // Load the given url.
1789 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001790 }
1791 }
Grace Klobac9181842009-04-14 08:53:22 -07001792 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001793 }
1794
Grace Kloba22ac16e2009-10-07 18:00:23 -07001795 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001796 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001797 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001798 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001799 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001800 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001801 }
Grace Klobac9181842009-04-14 08:53:22 -07001802 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001803 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001804 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001805 }
1806 }
1807
1808 private class Copy implements OnMenuItemClickListener {
1809 private CharSequence mText;
1810
1811 public boolean onMenuItemClick(MenuItem item) {
1812 copy(mText);
1813 return true;
1814 }
1815
1816 public Copy(CharSequence toCopy) {
1817 mText = toCopy;
1818 }
1819 }
1820
1821 private class Download implements OnMenuItemClickListener {
1822 private String mText;
1823
1824 public boolean onMenuItemClick(MenuItem item) {
1825 onDownloadStartNoStream(mText, null, null, null, -1);
1826 return true;
1827 }
1828
1829 public Download(String toDownload) {
1830 mText = toDownload;
1831 }
1832 }
1833
1834 private void copy(CharSequence text) {
1835 try {
1836 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1837 if (clip != null) {
1838 clip.setClipboardText(text);
1839 }
1840 } catch (android.os.RemoteException e) {
1841 Log.e(LOGTAG, "Copy failed", e);
1842 }
1843 }
1844
1845 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001846 * Resets the browser title-view to whatever it must be
1847 * (for example, if we had a loading error)
1848 * When we have a new page, we call resetTitle, when we
1849 * have to reset the titlebar to whatever it used to be
1850 * (for example, if the user chose to stop loading), we
1851 * call resetTitleAndRevertLockIcon.
1852 */
1853 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001854 mTabControl.getCurrentTab().revertLockIcon();
1855 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001856 resetTitleIconAndProgress();
1857 }
1858
1859 /**
1860 * Reset the title, favicon, and progress.
1861 */
1862 private void resetTitleIconAndProgress() {
1863 WebView current = mTabControl.getCurrentWebView();
1864 if (current == null) {
1865 return;
1866 }
1867 resetTitleAndIcon(current);
1868 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001869 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001870 }
1871
1872 // Reset the title and the icon based on the given item.
1873 private void resetTitleAndIcon(WebView view) {
1874 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1875 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001876 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001877 setFavicon(item.getFavicon());
1878 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001879 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001880 setFavicon(null);
1881 }
1882 }
1883
1884 /**
1885 * Sets a title composed of the URL and the title string.
1886 * @param url The URL of the site being loaded.
1887 * @param title The title of the site being loaded.
1888 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001889 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001890 mUrl = url;
1891 mTitle = title;
1892
Leon Scroggins68579392009-09-15 15:31:54 -04001893 mTitleBar.setTitleAndUrl(title, url);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001894 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001895 }
1896
1897 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001898 * @param url The URL to build a title version of the URL from.
1899 * @return The title version of the URL or null if fails.
1900 * The title version of the URL can be either the URL hostname,
1901 * or the hostname with an "https://" prefix (for secure URLs),
1902 * or an empty string if, for example, the URL in question is a
1903 * file:// URL with no hostname.
1904 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001905 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001906 String titleUrl = null;
1907
1908 if (url != null) {
1909 try {
1910 // parse the url string
1911 URL urlObj = new URL(url);
1912 if (urlObj != null) {
1913 titleUrl = "";
1914
1915 String protocol = urlObj.getProtocol();
1916 String host = urlObj.getHost();
1917
1918 if (host != null && 0 < host.length()) {
1919 titleUrl = host;
1920 if (protocol != null) {
1921 // if a secure site, add an "https://" prefix!
1922 if (protocol.equalsIgnoreCase("https")) {
1923 titleUrl = protocol + "://" + host;
1924 }
1925 }
1926 }
1927 }
1928 } catch (MalformedURLException e) {}
1929 }
1930
1931 return titleUrl;
1932 }
1933
1934 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001935 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04001936 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001937 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001938 }
1939
1940 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001941 * Close the tab, remove its associated title bar, and adjust mTabControl's
1942 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001943 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001944 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001945 int currentIndex = mTabControl.getCurrentIndex();
1946 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001947 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001948 if (currentIndex >= removeIndex && currentIndex != 0) {
1949 currentIndex--;
1950 }
1951 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01001952 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001953 }
1954
1955 private void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001956 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001957 if (current == null) {
1958 /*
1959 * Instead of finishing the activity, simply push this to the back
1960 * of the stack and let ActivityManager to choose the foreground
1961 * activity. As BrowserActivity is singleTask, it will be always the
1962 * root of the task. So we can use either true or false for
1963 * moveTaskToBack().
1964 */
1965 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07001966 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001967 }
1968 WebView w = current.getWebView();
1969 if (w.canGoBack()) {
1970 w.goBack();
1971 } else {
1972 // Check to see if we are closing a window that was created by
1973 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001974 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001975 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001976 switchToTab(mTabControl.getTabIndex(parent));
1977 // Now we close the other tab
1978 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001979 } else {
1980 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001981 // force the tab's inLoad() to be false as we are going to
1982 // either finish the activity or remove the tab. This will
1983 // ensure pauseWebViewTimers() taking action.
1984 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001985 if (mTabControl.getTabCount() == 1) {
1986 finish();
1987 return;
1988 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04001989 // call pauseWebViewTimers() now, we won't be able to call
1990 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07001991 // Temporarily change mActivityInPause to be true as
1992 // pauseWebViewTimers() will do nothing if mActivityInPause
1993 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07001994 boolean savedState = mActivityInPause;
1995 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07001996 Log.e(LOGTAG, "BrowserActivity is already paused "
1997 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07001998 }
1999 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002000 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002001 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002002 removeTabFromContentView(current);
2003 mTabControl.removeTab(current);
2004 }
2005 /*
2006 * Instead of finishing the activity, simply push this to the back
2007 * of the stack and let ActivityManager to choose the foreground
2008 * activity. As BrowserActivity is singleTask, it will be always the
2009 * root of the task. So we can use either true or false for
2010 * moveTaskToBack().
2011 */
2012 moveTaskToBack(true);
2013 }
2014 }
2015 }
2016
Grace Kloba22ac16e2009-10-07 18:00:23 -07002017 boolean isMenuDown() {
2018 return mMenuIsDown;
2019 }
2020
Grace Kloba5942df02009-09-18 11:48:29 -07002021 @Override
2022 public boolean onKeyDown(int keyCode, KeyEvent event) {
2023 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2024 // still down, we don't want to trigger the search. Pretend to consume
2025 // the key and do nothing.
2026 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002027
Grace Kloba5942df02009-09-18 11:48:29 -07002028 switch(keyCode) {
2029 case KeyEvent.KEYCODE_MENU:
2030 mMenuIsDown = true;
2031 break;
2032 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002033 // WebView/WebTextView handle the keys in the KeyDown. As
2034 // the Activity's shortcut keys are only handled when WebView
2035 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2036 if (event.isShiftPressed()) {
2037 getTopWindow().pageUp(false);
2038 } else {
2039 getTopWindow().pageDown(false);
2040 }
Grace Kloba5942df02009-09-18 11:48:29 -07002041 return true;
2042 case KeyEvent.KEYCODE_BACK:
2043 if (event.getRepeatCount() == 0) {
2044 event.startTracking();
2045 return true;
2046 } else if (mCustomView == null && mActiveTabsPage == null
2047 && event.isLongPress()) {
2048 bookmarksOrHistoryPicker(true);
2049 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002050 }
Grace Kloba5942df02009-09-18 11:48:29 -07002051 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002052 }
Grace Kloba5942df02009-09-18 11:48:29 -07002053 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002054 }
2055
Grace Kloba5942df02009-09-18 11:48:29 -07002056 @Override
2057 public boolean onKeyUp(int keyCode, KeyEvent event) {
2058 switch(keyCode) {
2059 case KeyEvent.KEYCODE_MENU:
2060 mMenuIsDown = false;
2061 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002062 case KeyEvent.KEYCODE_BACK:
2063 if (event.isTracking() && !event.isCanceled()) {
2064 if (mCustomView != null) {
2065 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002066 mTabControl.getCurrentWebView().getWebChromeClient()
2067 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002068 } else if (mActiveTabsPage != null) {
2069 // if tab page is showing, hide it
2070 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002071 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002072 WebView subwindow = mTabControl.getCurrentSubWindow();
2073 if (subwindow != null) {
2074 if (subwindow.canGoBack()) {
2075 subwindow.goBack();
2076 } else {
2077 dismissSubWindow(mTabControl.getCurrentTab());
2078 }
2079 } else {
2080 goBackOnePageOrQuit();
2081 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002082 }
Grace Kloba5942df02009-09-18 11:48:29 -07002083 return true;
2084 }
2085 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002086 }
Grace Kloba5942df02009-09-18 11:48:29 -07002087 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002088 }
2089
Leon Scroggins68579392009-09-15 15:31:54 -04002090 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002091 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002092 resetTitleAndRevertLockIcon();
2093 WebView w = getTopWindow();
2094 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002095 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2096 // same logic here. But for subwindow case, should we call into the main
2097 // WebView's onPageFinished as we never call its onPageStarted and if
2098 // the page finishes itself, we don't call onPageFinished.
2099 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2100 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002101
2102 cancelStopToast();
2103 mStopToast = Toast
2104 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2105 mStopToast.show();
2106 }
2107
Grace Kloba22ac16e2009-10-07 18:00:23 -07002108 boolean didUserStopLoading() {
2109 return mDidStopLoad;
2110 }
2111
The Android Open Source Project0c908882009-03-03 19:32:16 -08002112 private void cancelStopToast() {
2113 if (mStopToast != null) {
2114 mStopToast.cancel();
2115 mStopToast = null;
2116 }
2117 }
2118
Grace Kloba22ac16e2009-10-07 18:00:23 -07002119 // called by a UI or non-UI thread to post the message
2120 public void postMessage(int what, int arg1, int arg2, Object obj,
2121 long delayMillis) {
2122 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2123 obj), delayMillis);
2124 }
2125
2126 // called by a UI or non-UI thread to remove the message
2127 void removeMessages(int what, Object object) {
2128 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002129 }
2130
2131 // public message ids
2132 public final static int LOAD_URL = 1001;
2133 public final static int STOP_LOAD = 1002;
2134
2135 // Message Ids
2136 private static final int FOCUS_NODE_HREF = 102;
2137 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002138 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002139
Grace Kloba22ac16e2009-10-07 18:00:23 -07002140 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002141
The Android Open Source Project0c908882009-03-03 19:32:16 -08002142 // Private handler for handling javascript and saving passwords
2143 private Handler mHandler = new Handler() {
2144
2145 public void handleMessage(Message msg) {
2146 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002147 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002148 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002149 String url = (String) msg.getData().get("url");
2150 if (url == null || url.length() == 0) {
2151 break;
2152 }
2153 HashMap focusNodeMap = (HashMap) msg.obj;
2154 WebView view = (WebView) focusNodeMap.get("webview");
2155 // Only apply the action if the top window did not change.
2156 if (getTopWindow() != view) {
2157 break;
2158 }
2159 switch (msg.arg1) {
2160 case R.id.open_context_menu_id:
2161 case R.id.view_image_context_menu_id:
2162 loadURL(getTopWindow(), url);
2163 break;
2164 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002165 final Tab parent = mTabControl.getCurrentTab();
2166 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002167 if (newTab != parent) {
2168 parent.addChildTab(newTab);
2169 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002170 break;
2171 case R.id.bookmark_context_menu_id:
2172 Intent intent = new Intent(BrowserActivity.this,
2173 AddBookmarkPage.class);
2174 intent.putExtra("url", url);
2175 startActivity(intent);
2176 break;
2177 case R.id.share_link_context_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01002178 Browser.sendString(BrowserActivity.this, url,
2179 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002180 break;
2181 case R.id.copy_link_context_menu_id:
2182 copy(url);
2183 break;
2184 case R.id.save_link_context_menu_id:
2185 case R.id.download_context_menu_id:
2186 onDownloadStartNoStream(url, null, null, null, -1);
2187 break;
2188 }
2189 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002190 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002191
2192 case LOAD_URL:
2193 loadURL(getTopWindow(), (String) msg.obj);
2194 break;
2195
2196 case STOP_LOAD:
2197 stopLoading();
2198 break;
2199
2200 case CANCEL_CREDS_REQUEST:
2201 resumeAfterCredentials();
2202 break;
2203
The Android Open Source Project0c908882009-03-03 19:32:16 -08002204 case RELEASE_WAKELOCK:
2205 if (mWakeLock.isHeld()) {
2206 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002207 // if we reach here, Browser should be still in the
2208 // background loading after WAKELOCK_TIMEOUT (5-min).
2209 // To avoid burning the battery, stop loading.
2210 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002211 }
2212 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002213
2214 case UPDATE_BOOKMARK_THUMBNAIL:
2215 WebView view = (WebView) msg.obj;
2216 if (view != null) {
2217 updateScreenshot(view);
2218 }
2219 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002220 }
2221 }
2222 };
2223
Leon Scroggins89c6d362009-07-15 16:54:37 -04002224 private void updateScreenshot(WebView view) {
2225 // If this is a bookmarked site, add a screenshot to the database.
2226 // FIXME: When should we update? Every time?
2227 // FIXME: Would like to make sure there is actually something to
2228 // draw, but the API for that (WebViewCore.pictureReady()) is not
2229 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002230
Patrick Scott3918d442009-08-04 13:22:29 -04002231 ContentResolver cr = getContentResolver();
2232 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002233 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002234 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002235 boolean succeed = c.moveToFirst();
2236 ContentValues values = null;
2237 while (succeed) {
2238 if (values == null) {
2239 final ByteArrayOutputStream os
2240 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002241 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002242 if (bm == null) {
2243 c.close();
2244 return;
2245 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002246 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2247 values = new ContentValues();
2248 values.put(Browser.BookmarkColumns.THUMBNAIL,
2249 os.toByteArray());
2250 }
2251 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2252 c.getInt(0)), values, null, null);
2253 succeed = c.moveToNext();
2254 }
2255 c.close();
2256 }
2257 }
2258
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002259 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002260 * Values for the size of the thumbnail created when taking a screenshot.
2261 * Lazily initialized. Instead of using these directly, use
2262 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002263 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002264 private static int THUMBNAIL_WIDTH = 0;
2265 private static int THUMBNAIL_HEIGHT = 0;
2266
2267 /**
2268 * Return the desired width for thumbnail screenshots, which are stored in
2269 * the database, and used on the bookmarks screen.
2270 * @param context Context for finding out the density of the screen.
2271 * @return int desired width for thumbnail screenshot.
2272 */
2273 /* package */ static int getDesiredThumbnailWidth(Context context) {
2274 if (THUMBNAIL_WIDTH == 0) {
2275 float density = context.getResources().getDisplayMetrics().density;
2276 THUMBNAIL_WIDTH = (int) (90 * density);
2277 THUMBNAIL_HEIGHT = (int) (80 * density);
2278 }
2279 return THUMBNAIL_WIDTH;
2280 }
2281
2282 /**
2283 * Return the desired height for thumbnail screenshots, which are stored in
2284 * the database, and used on the bookmarks screen.
2285 * @param context Context for finding out the density of the screen.
2286 * @return int desired height for thumbnail screenshot.
2287 */
2288 /* package */ static int getDesiredThumbnailHeight(Context context) {
2289 // To ensure that they are both initialized.
2290 getDesiredThumbnailWidth(context);
2291 return THUMBNAIL_HEIGHT;
2292 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002293
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002294 private Bitmap createScreenshot(WebView view) {
2295 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002296 if (thumbnail == null) {
2297 return null;
2298 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002299 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2300 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002301 Canvas canvas = new Canvas(bm);
2302 // May need to tweak these values to determine what is the
2303 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002304 int thumbnailWidth = thumbnail.getWidth();
2305 if (thumbnailWidth > 0) {
2306 float scaleFactor = (float) getDesiredThumbnailWidth(this) /
2307 (float)thumbnailWidth;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002308 canvas.scale(scaleFactor, scaleFactor);
2309 }
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002310 thumbnail.draw(canvas);
2311 return bm;
2312 }
2313
The Android Open Source Project0c908882009-03-03 19:32:16 -08002314 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002315 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002316 //-------------------------------------------------------------------------
2317
2318 // Use in overrideUrlLoading
2319 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2320 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2321 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2322 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2323
Grace Kloba22ac16e2009-10-07 18:00:23 -07002324 void onPageStarted(WebView view, String url, Bitmap favicon) {
2325 // when BrowserActivity just starts, onPageStarted may be called before
2326 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2327 // to start the timer. As we won't switch tabs while an activity is in
2328 // pause state, we can ensure calling resume and pause in pair.
2329 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002330
Grace Kloba22ac16e2009-10-07 18:00:23 -07002331 resetLockIcon(url);
2332 setUrlTitle(url, null);
2333 setFavicon(favicon);
2334 mInLoad = true;
2335 mDidStopLoad = false;
2336 showFakeTitleBar();
2337 updateInLoadMenuItems();
2338 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002339
Grace Kloba22ac16e2009-10-07 18:00:23 -07002340 if (mSettings.isTracing()) {
2341 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002342 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002343 WebAddress uri = new WebAddress(url);
2344 host = uri.mHost;
2345 } catch (android.net.ParseException ex) {
2346 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002347 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002348 host = host.replace('.', '_');
2349 host += ".trace";
2350 mInTrace = true;
2351 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2352 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002353
Grace Kloba22ac16e2009-10-07 18:00:23 -07002354 // Performance probe
2355 if (false) {
2356 mStart = SystemClock.uptimeMillis();
2357 mProcessStart = Process.getElapsedCpuTime();
2358 long[] sysCpu = new long[7];
2359 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2360 sysCpu, null)) {
2361 mUserStart = sysCpu[0] + sysCpu[1];
2362 mSystemStart = sysCpu[2];
2363 mIdleStart = sysCpu[3];
2364 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2365 }
2366 mUiStart = SystemClock.currentThreadTimeMillis();
2367 }
2368 }
2369
2370 void onPageFinished(WebView view, String url) {
2371 // Reset the title and icon in case we stopped a provisional load.
2372 resetTitleAndIcon(view);
2373 // Update the lock icon image only once we are done loading
2374 updateLockIconToLatest();
2375 // pause the WebView timer and release the wake lock if it is finished
2376 // while BrowserActivity is in pause state.
2377 if (mActivityInPause && pauseWebViewTimers()) {
2378 if (mWakeLock.isHeld()) {
2379 mHandler.removeMessages(RELEASE_WAKELOCK);
2380 mWakeLock.release();
2381 }
2382 }
2383
2384 // Performance probe
2385 if (false) {
2386 long[] sysCpu = new long[7];
2387 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2388 sysCpu, null)) {
2389 String uiInfo = "UI thread used "
2390 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2391 + " ms";
2392 if (LOGD_ENABLED) {
2393 Log.d(LOGTAG, uiInfo);
2394 }
2395 //The string that gets written to the log
2396 String performanceString = "It took total "
2397 + (SystemClock.uptimeMillis() - mStart)
2398 + " ms clock time to load the page."
2399 + "\nbrowser process used "
2400 + (Process.getElapsedCpuTime() - mProcessStart)
2401 + " ms, user processes used "
2402 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2403 + " ms, kernel used "
2404 + (sysCpu[2] - mSystemStart) * 10
2405 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2406 + " ms and irq took "
2407 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2408 * 10 + " ms, " + uiInfo;
2409 if (LOGD_ENABLED) {
2410 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2411 }
2412 if (url != null) {
2413 // strip the url to maintain consistency
2414 String newUrl = new String(url);
2415 if (newUrl.startsWith("http://www.")) {
2416 newUrl = newUrl.substring(11);
2417 } else if (newUrl.startsWith("http://")) {
2418 newUrl = newUrl.substring(7);
2419 } else if (newUrl.startsWith("https://www.")) {
2420 newUrl = newUrl.substring(12);
2421 } else if (newUrl.startsWith("https://")) {
2422 newUrl = newUrl.substring(8);
2423 }
2424 if (LOGD_ENABLED) {
2425 Log.d(LOGTAG, newUrl + " loaded");
2426 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002427 }
2428 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002429 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002430
Grace Kloba22ac16e2009-10-07 18:00:23 -07002431 if (mInTrace) {
2432 mInTrace = false;
2433 Debug.stopMethodTracing();
2434 }
2435 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002436
Grace Kloba22ac16e2009-10-07 18:00:23 -07002437 boolean shouldOverrideUrlLoading(WebView view, String url) {
2438 if (url.startsWith(SCHEME_WTAI)) {
2439 // wtai://wp/mc;number
2440 // number=string(phone-number)
2441 if (url.startsWith(SCHEME_WTAI_MC)) {
2442 Intent intent = new Intent(Intent.ACTION_VIEW,
2443 Uri.parse(WebView.SCHEME_TEL +
2444 url.substring(SCHEME_WTAI_MC.length())));
2445 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002446 return true;
2447 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002448 // wtai://wp/sd;dtmf
2449 // dtmf=string(dialstring)
2450 if (url.startsWith(SCHEME_WTAI_SD)) {
2451 // TODO: only send when there is active voice connection
2452 return false;
2453 }
2454 // wtai://wp/ap;number;name
2455 // number=string(phone-number)
2456 // name=string
2457 if (url.startsWith(SCHEME_WTAI_AP)) {
2458 // TODO
2459 return false;
2460 }
2461 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002462
Grace Kloba22ac16e2009-10-07 18:00:23 -07002463 // The "about:" schemes are internal to the browser; don't want these to
2464 // be dispatched to other apps.
2465 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002466 return false;
2467 }
2468
Grace Kloba22ac16e2009-10-07 18:00:23 -07002469 Intent intent;
2470 // perform generic parsing of the URI to turn it into an Intent.
2471 try {
2472 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2473 } catch (URISyntaxException ex) {
2474 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2475 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002476 }
2477
Grace Kloba22ac16e2009-10-07 18:00:23 -07002478 // check whether the intent can be resolved. If not, we will see
2479 // whether we can download it from the Market.
2480 if (getPackageManager().resolveActivity(intent, 0) == null) {
2481 String packagename = intent.getPackage();
2482 if (packagename != null) {
2483 intent = new Intent(Intent.ACTION_VIEW, Uri
2484 .parse("market://search?q=pname:" + packagename));
2485 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2486 startActivity(intent);
2487 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002488 } else {
2489 return false;
2490 }
2491 }
2492
Grace Kloba22ac16e2009-10-07 18:00:23 -07002493 // sanitize the Intent, ensuring web pages can not bypass browser
2494 // security (only access to BROWSABLE activities).
2495 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2496 intent.setComponent(null);
2497 try {
2498 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002499 return true;
2500 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002501 } catch (ActivityNotFoundException ex) {
2502 // ignore the error. If no application can handle the URL,
2503 // eg about:blank, assume the browser can handle it.
2504 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002505
Grace Kloba22ac16e2009-10-07 18:00:23 -07002506 if (mMenuIsDown) {
2507 openTab(url);
2508 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002509 return true;
2510 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002511 return false;
2512 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002513
Grace Kloba22ac16e2009-10-07 18:00:23 -07002514 // -------------------------------------------------------------------------
2515 // Helper function for WebChromeClient
2516 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002517
Grace Kloba22ac16e2009-10-07 18:00:23 -07002518 void onProgressChanged(WebView view, int newProgress) {
2519 mTitleBar.setProgress(newProgress);
2520 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002521
Grace Kloba22ac16e2009-10-07 18:00:23 -07002522 if (newProgress == 100) {
2523 // onProgressChanged() may continue to be called after the main
2524 // frame has finished loading, as any remaining sub frames continue
2525 // to load. We'll only get called once though with newProgress as
2526 // 100 when everything is loaded. (onPageFinished is called once
2527 // when the main frame completes loading regardless of the state of
2528 // any sub frames so calls to onProgressChanges may continue after
2529 // onPageFinished has executed)
2530 if (mInLoad) {
2531 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002532 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002533 // If the options menu is open, leave the title bar
2534 if (!mOptionsMenuOpen || !mIconView) {
2535 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002536 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002537 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002538 } else if (!mInLoad) {
2539 // onPageFinished may have already been called but a subframe is
2540 // still loading and updating the progress. Reset mInLoad and update
2541 // the menu items.
2542 mInLoad = true;
2543 updateInLoadMenuItems();
2544 if (!mOptionsMenuOpen || mIconView) {
2545 // This page has begun to load, so show the title bar
2546 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002547 }
2548 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002549 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002550
Grace Kloba22ac16e2009-10-07 18:00:23 -07002551 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2552 if (mCustomView != null)
2553 return;
2554
2555 // Add the custom view to its container.
2556 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2557 mCustomView = view;
2558 mCustomViewCallback = callback;
2559 // Save the menu state and set it to empty while the custom
2560 // view is showing.
2561 mOldMenuState = mMenuState;
2562 mMenuState = EMPTY_MENU;
2563 // Hide the content view.
2564 mContentView.setVisibility(View.GONE);
2565 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002566 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002567 mCustomViewContainer.setVisibility(View.VISIBLE);
2568 mCustomViewContainer.bringToFront();
2569 }
2570
2571 void onHideCustomView() {
2572 if (mCustomView == null)
2573 return;
2574
2575 // Hide the custom view.
2576 mCustomView.setVisibility(View.GONE);
2577 // Remove the custom view from its container.
2578 mCustomViewContainer.removeView(mCustomView);
2579 mCustomView = null;
2580 // Reset the old menu state.
2581 mMenuState = mOldMenuState;
2582 mOldMenuState = EMPTY_MENU;
2583 mCustomViewContainer.setVisibility(View.GONE);
2584 mCustomViewCallback.onCustomViewHidden();
2585 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002586 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002587 mContentView.setVisibility(View.VISIBLE);
2588 }
2589
2590 Bitmap getDefaultVideoPoster() {
2591 if (mDefaultVideoPoster == null) {
2592 mDefaultVideoPoster = BitmapFactory.decodeResource(
2593 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002594 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002595 return mDefaultVideoPoster;
2596 }
Patrick Scott3918d442009-08-04 13:22:29 -04002597
Grace Kloba22ac16e2009-10-07 18:00:23 -07002598 View getVideoLoadingProgressView() {
2599 if (mVideoProgressView == null) {
2600 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2601 mVideoProgressView = inflater.inflate(
2602 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002603 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002604 return mVideoProgressView;
2605 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002606
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002607 /*
2608 * The Object used to inform the WebView of the file to upload.
2609 */
2610 private ValueCallback<Uri> mUploadMessage;
2611
Grace Kloba22ac16e2009-10-07 18:00:23 -07002612 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2613 if (mUploadMessage != null) return;
2614 mUploadMessage = uploadMsg;
2615 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2616 i.addCategory(Intent.CATEGORY_OPENABLE);
2617 i.setType("*/*");
2618 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2619 getString(R.string.choose_upload)), FILE_SELECTED);
2620 }
2621
2622 // -------------------------------------------------------------------------
2623 // Implement functions for DownloadListener
2624 // -------------------------------------------------------------------------
2625
The Android Open Source Project0c908882009-03-03 19:32:16 -08002626 /**
2627 * Notify the host application a download should be done, or that
2628 * the data should be streamed if a streaming viewer is available.
2629 * @param url The full url to the content that should be downloaded
2630 * @param contentDisposition Content-disposition http header, if
2631 * present.
2632 * @param mimetype The mimetype of the content reported by the server
2633 * @param contentLength The file size reported by the server
2634 */
2635 public void onDownloadStart(String url, String userAgent,
2636 String contentDisposition, String mimetype, long contentLength) {
2637 // if we're dealing wih A/V content that's not explicitly marked
2638 // for download, check if it's streamable.
2639 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002640 || !contentDisposition.regionMatches(
2641 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002642 // query the package manager to see if there's a registered handler
2643 // that matches.
2644 Intent intent = new Intent(Intent.ACTION_VIEW);
2645 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002646 ResolveInfo info = getPackageManager().resolveActivity(intent,
2647 PackageManager.MATCH_DEFAULT_ONLY);
2648 if (info != null) {
2649 ComponentName myName = getComponentName();
2650 // If we resolved to ourselves, we don't want to attempt to
2651 // load the url only to try and download it again.
2652 if (!myName.getPackageName().equals(
2653 info.activityInfo.packageName)
2654 || !myName.getClassName().equals(
2655 info.activityInfo.name)) {
2656 // someone (other than us) knows how to handle this mime
2657 // type with this scheme, don't download.
2658 try {
2659 startActivity(intent);
2660 return;
2661 } catch (ActivityNotFoundException ex) {
2662 if (LOGD_ENABLED) {
2663 Log.d(LOGTAG, "activity not found for " + mimetype
2664 + " over " + Uri.parse(url).getScheme(),
2665 ex);
2666 }
2667 // Best behavior is to fall back to a download in this
2668 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002669 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002670 }
2671 }
2672 }
2673 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2674 }
2675
2676 /**
2677 * Notify the host application a download should be done, even if there
2678 * is a streaming viewer available for thise type.
2679 * @param url The full url to the content that should be downloaded
2680 * @param contentDisposition Content-disposition http header, if
2681 * present.
2682 * @param mimetype The mimetype of the content reported by the server
2683 * @param contentLength The file size reported by the server
2684 */
2685 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2686 String contentDisposition, String mimetype, long contentLength) {
2687
2688 String filename = URLUtil.guessFileName(url,
2689 contentDisposition, mimetype);
2690
2691 // Check to see if we have an SDCard
2692 String status = Environment.getExternalStorageState();
2693 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2694 int title;
2695 String msg;
2696
2697 // Check to see if the SDCard is busy, same as the music app
2698 if (status.equals(Environment.MEDIA_SHARED)) {
2699 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2700 title = R.string.download_sdcard_busy_dlg_title;
2701 } else {
2702 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2703 title = R.string.download_no_sdcard_dlg_title;
2704 }
2705
2706 new AlertDialog.Builder(this)
2707 .setTitle(title)
2708 .setIcon(android.R.drawable.ic_dialog_alert)
2709 .setMessage(msg)
2710 .setPositiveButton(R.string.ok, null)
2711 .show();
2712 return;
2713 }
2714
2715 // java.net.URI is a lot stricter than KURL so we have to undo
2716 // KURL's percent-encoding and redo the encoding using java.net.URI.
2717 URI uri = null;
2718 try {
2719 // Undo the percent-encoding that KURL may have done.
2720 String newUrl = new String(URLUtil.decode(url.getBytes()));
2721 // Parse the url into pieces
2722 WebAddress w = new WebAddress(newUrl);
2723 String frag = null;
2724 String query = null;
2725 String path = w.mPath;
2726 // Break the path into path, query, and fragment
2727 if (path.length() > 0) {
2728 // Strip the fragment
2729 int idx = path.lastIndexOf('#');
2730 if (idx != -1) {
2731 frag = path.substring(idx + 1);
2732 path = path.substring(0, idx);
2733 }
2734 idx = path.lastIndexOf('?');
2735 if (idx != -1) {
2736 query = path.substring(idx + 1);
2737 path = path.substring(0, idx);
2738 }
2739 }
2740 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2741 query, frag);
2742 } catch (Exception e) {
2743 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2744 return;
2745 }
2746
2747 // XXX: Have to use the old url since the cookies were stored using the
2748 // old percent-encoded url.
2749 String cookies = CookieManager.getInstance().getCookie(url);
2750
2751 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002752 values.put(Downloads.COLUMN_URI, uri.toString());
2753 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
2754 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
2755 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002756 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002757 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002758 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002759 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2760 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
2761 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
2762 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002763 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002764 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002765 }
2766 if (mimetype == null) {
2767 // We must have long pressed on a link or image to download it. We
2768 // are not sure of the mimetype in this case, so do a head request
2769 new FetchUrlMimeType(this).execute(values);
2770 } else {
2771 final Uri contentUri =
2772 getContentResolver().insert(Downloads.CONTENT_URI, values);
2773 viewDownloads(contentUri);
2774 }
2775
2776 }
2777
Grace Kloba22ac16e2009-10-07 18:00:23 -07002778 // -------------------------------------------------------------------------
2779
The Android Open Source Project0c908882009-03-03 19:32:16 -08002780 /**
2781 * Resets the lock icon. This method is called when we start a new load and
2782 * know the url to be loaded.
2783 */
2784 private void resetLockIcon(String url) {
2785 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002786 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002787 updateLockIconImage(LOCK_ICON_UNSECURE);
2788 }
2789
The Android Open Source Project0c908882009-03-03 19:32:16 -08002790 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002791 * Update the lock icon to correspond to our latest state.
2792 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002793 private void updateLockIconToLatest() {
2794 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002795 }
2796
2797 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002798 * Updates the lock-icon image in the title-bar.
2799 */
2800 private void updateLockIconImage(int lockIconType) {
2801 Drawable d = null;
2802 if (lockIconType == LOCK_ICON_SECURE) {
2803 d = mSecLockIcon;
2804 } else if (lockIconType == LOCK_ICON_MIXED) {
2805 d = mMixLockIcon;
2806 }
Leon Scroggins68579392009-09-15 15:31:54 -04002807 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002808 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002809 }
2810
2811 /**
2812 * Displays a page-info dialog.
2813 * @param tab The tab to show info about
2814 * @param fromShowSSLCertificateOnError The flag that indicates whether
2815 * this dialog was opened from the SSL-certificate-on-error dialog or
2816 * not. This is important, since we need to know whether to return to
2817 * the parent dialog or simply dismiss.
2818 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002819 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002820 final boolean fromShowSSLCertificateOnError) {
2821 final LayoutInflater factory = LayoutInflater
2822 .from(this);
2823
2824 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2825
2826 final WebView view = tab.getWebView();
2827
2828 String url = null;
2829 String title = null;
2830
2831 if (view == null) {
2832 url = tab.getUrl();
2833 title = tab.getTitle();
2834 } else if (view == mTabControl.getCurrentWebView()) {
2835 // Use the cached title and url if this is the current WebView
2836 url = mUrl;
2837 title = mTitle;
2838 } else {
2839 url = view.getUrl();
2840 title = view.getTitle();
2841 }
2842
2843 if (url == null) {
2844 url = "";
2845 }
2846 if (title == null) {
2847 title = "";
2848 }
2849
2850 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
2851 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
2852
2853 mPageInfoView = tab;
2854 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
2855
2856 AlertDialog.Builder alertDialogBuilder =
2857 new AlertDialog.Builder(this)
2858 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
2859 .setView(pageInfoView)
2860 .setPositiveButton(
2861 R.string.ok,
2862 new DialogInterface.OnClickListener() {
2863 public void onClick(DialogInterface dialog,
2864 int whichButton) {
2865 mPageInfoDialog = null;
2866 mPageInfoView = null;
2867 mPageInfoFromShowSSLCertificateOnError = null;
2868
2869 // if we came here from the SSL error dialog
2870 if (fromShowSSLCertificateOnError) {
2871 // go back to the SSL error dialog
2872 showSSLCertificateOnError(
2873 mSSLCertificateOnErrorView,
2874 mSSLCertificateOnErrorHandler,
2875 mSSLCertificateOnErrorError);
2876 }
2877 }
2878 })
2879 .setOnCancelListener(
2880 new DialogInterface.OnCancelListener() {
2881 public void onCancel(DialogInterface dialog) {
2882 mPageInfoDialog = null;
2883 mPageInfoView = null;
2884 mPageInfoFromShowSSLCertificateOnError = null;
2885
2886 // if we came here from the SSL error dialog
2887 if (fromShowSSLCertificateOnError) {
2888 // go back to the SSL error dialog
2889 showSSLCertificateOnError(
2890 mSSLCertificateOnErrorView,
2891 mSSLCertificateOnErrorHandler,
2892 mSSLCertificateOnErrorError);
2893 }
2894 }
2895 });
2896
2897 // if we have a main top-level page SSL certificate set or a certificate
2898 // error
2899 if (fromShowSSLCertificateOnError ||
2900 (view != null && view.getCertificate() != null)) {
2901 // add a 'View Certificate' button
2902 alertDialogBuilder.setNeutralButton(
2903 R.string.view_certificate,
2904 new DialogInterface.OnClickListener() {
2905 public void onClick(DialogInterface dialog,
2906 int whichButton) {
2907 mPageInfoDialog = null;
2908 mPageInfoView = null;
2909 mPageInfoFromShowSSLCertificateOnError = null;
2910
2911 // if we came here from the SSL error dialog
2912 if (fromShowSSLCertificateOnError) {
2913 // go back to the SSL error dialog
2914 showSSLCertificateOnError(
2915 mSSLCertificateOnErrorView,
2916 mSSLCertificateOnErrorHandler,
2917 mSSLCertificateOnErrorError);
2918 } else {
2919 // otherwise, display the top-most certificate from
2920 // the chain
2921 if (view.getCertificate() != null) {
2922 showSSLCertificate(tab);
2923 }
2924 }
2925 }
2926 });
2927 }
2928
2929 mPageInfoDialog = alertDialogBuilder.show();
2930 }
2931
2932 /**
2933 * Displays the main top-level page SSL certificate dialog
2934 * (accessible from the Page-Info dialog).
2935 * @param tab The tab to show certificate for.
2936 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002937 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002938 final View certificateView =
2939 inflateCertificateView(tab.getWebView().getCertificate());
2940 if (certificateView == null) {
2941 return;
2942 }
2943
2944 LayoutInflater factory = LayoutInflater.from(this);
2945
2946 final LinearLayout placeholder =
2947 (LinearLayout)certificateView.findViewById(R.id.placeholder);
2948
2949 LinearLayout ll = (LinearLayout) factory.inflate(
2950 R.layout.ssl_success, placeholder);
2951 ((TextView)ll.findViewById(R.id.success))
2952 .setText(R.string.ssl_certificate_is_valid);
2953
2954 mSSLCertificateView = tab;
2955 mSSLCertificateDialog =
2956 new AlertDialog.Builder(this)
2957 .setTitle(R.string.ssl_certificate).setIcon(
2958 R.drawable.ic_dialog_browser_certificate_secure)
2959 .setView(certificateView)
2960 .setPositiveButton(R.string.ok,
2961 new DialogInterface.OnClickListener() {
2962 public void onClick(DialogInterface dialog,
2963 int whichButton) {
2964 mSSLCertificateDialog = null;
2965 mSSLCertificateView = null;
2966
2967 showPageInfo(tab, false);
2968 }
2969 })
2970 .setOnCancelListener(
2971 new DialogInterface.OnCancelListener() {
2972 public void onCancel(DialogInterface dialog) {
2973 mSSLCertificateDialog = null;
2974 mSSLCertificateView = null;
2975
2976 showPageInfo(tab, false);
2977 }
2978 })
2979 .show();
2980 }
2981
2982 /**
2983 * Displays the SSL error certificate dialog.
2984 * @param view The target web-view.
2985 * @param handler The SSL error handler responsible for cancelling the
2986 * connection that resulted in an SSL error or proceeding per user request.
2987 * @param error The SSL error object.
2988 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002989 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08002990 final WebView view, final SslErrorHandler handler, final SslError error) {
2991
2992 final View certificateView =
2993 inflateCertificateView(error.getCertificate());
2994 if (certificateView == null) {
2995 return;
2996 }
2997
2998 LayoutInflater factory = LayoutInflater.from(this);
2999
3000 final LinearLayout placeholder =
3001 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3002
3003 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3004 LinearLayout ll = (LinearLayout)factory
3005 .inflate(R.layout.ssl_warning, placeholder);
3006 ((TextView)ll.findViewById(R.id.warning))
3007 .setText(R.string.ssl_untrusted);
3008 }
3009
3010 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3011 LinearLayout ll = (LinearLayout)factory
3012 .inflate(R.layout.ssl_warning, placeholder);
3013 ((TextView)ll.findViewById(R.id.warning))
3014 .setText(R.string.ssl_mismatch);
3015 }
3016
3017 if (error.hasError(SslError.SSL_EXPIRED)) {
3018 LinearLayout ll = (LinearLayout)factory
3019 .inflate(R.layout.ssl_warning, placeholder);
3020 ((TextView)ll.findViewById(R.id.warning))
3021 .setText(R.string.ssl_expired);
3022 }
3023
3024 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3025 LinearLayout ll = (LinearLayout)factory
3026 .inflate(R.layout.ssl_warning, placeholder);
3027 ((TextView)ll.findViewById(R.id.warning))
3028 .setText(R.string.ssl_not_yet_valid);
3029 }
3030
3031 mSSLCertificateOnErrorHandler = handler;
3032 mSSLCertificateOnErrorView = view;
3033 mSSLCertificateOnErrorError = error;
3034 mSSLCertificateOnErrorDialog =
3035 new AlertDialog.Builder(this)
3036 .setTitle(R.string.ssl_certificate).setIcon(
3037 R.drawable.ic_dialog_browser_certificate_partially_secure)
3038 .setView(certificateView)
3039 .setPositiveButton(R.string.ok,
3040 new DialogInterface.OnClickListener() {
3041 public void onClick(DialogInterface dialog,
3042 int whichButton) {
3043 mSSLCertificateOnErrorDialog = null;
3044 mSSLCertificateOnErrorView = null;
3045 mSSLCertificateOnErrorHandler = null;
3046 mSSLCertificateOnErrorError = null;
3047
Grace Kloba22ac16e2009-10-07 18:00:23 -07003048 view.getWebViewClient().onReceivedSslError(
3049 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003050 }
3051 })
3052 .setNeutralButton(R.string.page_info_view,
3053 new DialogInterface.OnClickListener() {
3054 public void onClick(DialogInterface dialog,
3055 int whichButton) {
3056 mSSLCertificateOnErrorDialog = null;
3057
3058 // do not clear the dialog state: we will
3059 // need to show the dialog again once the
3060 // user is done exploring the page-info details
3061
3062 showPageInfo(mTabControl.getTabFromView(view),
3063 true);
3064 }
3065 })
3066 .setOnCancelListener(
3067 new DialogInterface.OnCancelListener() {
3068 public void onCancel(DialogInterface dialog) {
3069 mSSLCertificateOnErrorDialog = null;
3070 mSSLCertificateOnErrorView = null;
3071 mSSLCertificateOnErrorHandler = null;
3072 mSSLCertificateOnErrorError = null;
3073
Grace Kloba22ac16e2009-10-07 18:00:23 -07003074 view.getWebViewClient().onReceivedSslError(
3075 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003076 }
3077 })
3078 .show();
3079 }
3080
3081 /**
3082 * Inflates the SSL certificate view (helper method).
3083 * @param certificate The SSL certificate.
3084 * @return The resultant certificate view with issued-to, issued-by,
3085 * issued-on, expires-on, and possibly other fields set.
3086 * If the input certificate is null, returns null.
3087 */
3088 private View inflateCertificateView(SslCertificate certificate) {
3089 if (certificate == null) {
3090 return null;
3091 }
3092
3093 LayoutInflater factory = LayoutInflater.from(this);
3094
3095 View certificateView = factory.inflate(
3096 R.layout.ssl_certificate, null);
3097
3098 // issued to:
3099 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3100 if (issuedTo != null) {
3101 ((TextView) certificateView.findViewById(R.id.to_common))
3102 .setText(issuedTo.getCName());
3103 ((TextView) certificateView.findViewById(R.id.to_org))
3104 .setText(issuedTo.getOName());
3105 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3106 .setText(issuedTo.getUName());
3107 }
3108
3109 // issued by:
3110 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3111 if (issuedBy != null) {
3112 ((TextView) certificateView.findViewById(R.id.by_common))
3113 .setText(issuedBy.getCName());
3114 ((TextView) certificateView.findViewById(R.id.by_org))
3115 .setText(issuedBy.getOName());
3116 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3117 .setText(issuedBy.getUName());
3118 }
3119
3120 // issued on:
3121 String issuedOn = reformatCertificateDate(
3122 certificate.getValidNotBefore());
3123 ((TextView) certificateView.findViewById(R.id.issued_on))
3124 .setText(issuedOn);
3125
3126 // expires on:
3127 String expiresOn = reformatCertificateDate(
3128 certificate.getValidNotAfter());
3129 ((TextView) certificateView.findViewById(R.id.expires_on))
3130 .setText(expiresOn);
3131
3132 return certificateView;
3133 }
3134
3135 /**
3136 * Re-formats the certificate date (Date.toString()) string to
3137 * a properly localized date string.
3138 * @return Properly localized version of the certificate date string and
3139 * the original certificate date string if fails to localize.
3140 * If the original string is null, returns an empty string "".
3141 */
3142 private String reformatCertificateDate(String certificateDate) {
3143 String reformattedDate = null;
3144
3145 if (certificateDate != null) {
3146 Date date = null;
3147 try {
3148 date = java.text.DateFormat.getInstance().parse(certificateDate);
3149 } catch (ParseException e) {
3150 date = null;
3151 }
3152
3153 if (date != null) {
3154 reformattedDate =
3155 DateFormat.getDateFormat(this).format(date);
3156 }
3157 }
3158
3159 return reformattedDate != null ? reformattedDate :
3160 (certificateDate != null ? certificateDate : "");
3161 }
3162
3163 /**
3164 * Displays an http-authentication dialog.
3165 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003166 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003167 final String host, final String realm, final String title,
3168 final String name, final String password, int focusId) {
3169 LayoutInflater factory = LayoutInflater.from(this);
3170 final View v = factory
3171 .inflate(R.layout.http_authentication, null);
3172 if (name != null) {
3173 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3174 }
3175 if (password != null) {
3176 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3177 }
3178
3179 String titleText = title;
3180 if (titleText == null) {
3181 titleText = getText(R.string.sign_in_to).toString().replace(
3182 "%s1", host).replace("%s2", realm);
3183 }
3184
3185 mHttpAuthHandler = handler;
3186 AlertDialog dialog = new AlertDialog.Builder(this)
3187 .setTitle(titleText)
3188 .setIcon(android.R.drawable.ic_dialog_alert)
3189 .setView(v)
3190 .setPositiveButton(R.string.action,
3191 new DialogInterface.OnClickListener() {
3192 public void onClick(DialogInterface dialog,
3193 int whichButton) {
3194 String nm = ((EditText) v
3195 .findViewById(R.id.username_edit))
3196 .getText().toString();
3197 String pw = ((EditText) v
3198 .findViewById(R.id.password_edit))
3199 .getText().toString();
3200 BrowserActivity.this.setHttpAuthUsernamePassword
3201 (host, realm, nm, pw);
3202 handler.proceed(nm, pw);
3203 mHttpAuthenticationDialog = null;
3204 mHttpAuthHandler = null;
3205 }})
3206 .setNegativeButton(R.string.cancel,
3207 new DialogInterface.OnClickListener() {
3208 public void onClick(DialogInterface dialog,
3209 int whichButton) {
3210 handler.cancel();
3211 BrowserActivity.this.resetTitleAndRevertLockIcon();
3212 mHttpAuthenticationDialog = null;
3213 mHttpAuthHandler = null;
3214 }})
3215 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3216 public void onCancel(DialogInterface dialog) {
3217 handler.cancel();
3218 BrowserActivity.this.resetTitleAndRevertLockIcon();
3219 mHttpAuthenticationDialog = null;
3220 mHttpAuthHandler = null;
3221 }})
3222 .create();
3223 // Make the IME appear when the dialog is displayed if applicable.
3224 dialog.getWindow().setSoftInputMode(
3225 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3226 dialog.show();
3227 if (focusId != 0) {
3228 dialog.findViewById(focusId).requestFocus();
3229 } else {
3230 v.findViewById(R.id.username_edit).requestFocus();
3231 }
3232 mHttpAuthenticationDialog = dialog;
3233 }
3234
3235 public int getProgress() {
3236 WebView w = mTabControl.getCurrentWebView();
3237 if (w != null) {
3238 return w.getProgress();
3239 } else {
3240 return 100;
3241 }
3242 }
3243
3244 /**
3245 * Set HTTP authentication password.
3246 *
3247 * @param host The host for the password
3248 * @param realm The realm for the password
3249 * @param username The username for the password. If it is null, it means
3250 * password can't be saved.
3251 * @param password The password
3252 */
3253 public void setHttpAuthUsernamePassword(String host, String realm,
3254 String username,
3255 String password) {
3256 WebView w = mTabControl.getCurrentWebView();
3257 if (w != null) {
3258 w.setHttpAuthUsernamePassword(host, realm, username, password);
3259 }
3260 }
3261
3262 /**
3263 * connectivity manager says net has come or gone... inform the user
3264 * @param up true if net has come up, false if net has gone down
3265 */
3266 public void onNetworkToggle(boolean up) {
3267 if (up == mIsNetworkUp) {
3268 return;
3269 } else if (up) {
3270 mIsNetworkUp = true;
3271 if (mAlertDialog != null) {
3272 mAlertDialog.cancel();
3273 mAlertDialog = null;
3274 }
3275 } else {
3276 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003277 if (mInLoad) {
3278 createAndShowNetworkDialog();
3279 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003280 }
3281 WebView w = mTabControl.getCurrentWebView();
3282 if (w != null) {
3283 w.setNetworkAvailable(up);
3284 }
3285 }
3286
Grace Kloba22ac16e2009-10-07 18:00:23 -07003287 boolean isNetworkUp() {
3288 return mIsNetworkUp;
3289 }
3290
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003291 // This method shows the network dialog alerting the user that the net is
3292 // down. It will only show the dialog if mAlertDialog is null.
3293 private void createAndShowNetworkDialog() {
3294 if (mAlertDialog == null) {
3295 mAlertDialog = new AlertDialog.Builder(this)
3296 .setTitle(R.string.loadSuspendedTitle)
3297 .setMessage(R.string.loadSuspended)
3298 .setPositiveButton(R.string.ok, null)
3299 .show();
3300 }
3301 }
3302
The Android Open Source Project0c908882009-03-03 19:32:16 -08003303 @Override
3304 protected void onActivityResult(int requestCode, int resultCode,
3305 Intent intent) {
3306 switch (requestCode) {
3307 case COMBO_PAGE:
3308 if (resultCode == RESULT_OK && intent != null) {
3309 String data = intent.getAction();
3310 Bundle extras = intent.getExtras();
3311 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003312 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003313 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003314 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003315 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003316 dismissSubWindow(currentTab);
3317 if (data != null && data.length() != 0) {
3318 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003319 }
3320 }
3321 }
3322 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003323 // Choose a file from the file picker.
3324 case FILE_SELECTED:
3325 if (null == mUploadMessage) break;
3326 Uri result = intent == null || resultCode != RESULT_OK ? null
3327 : intent.getData();
3328 mUploadMessage.onReceiveValue(result);
3329 mUploadMessage = null;
3330 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003331 default:
3332 break;
3333 }
Leon Scroggins30444232009-09-04 18:36:20 -04003334 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003335 }
3336
3337 /*
3338 * This method is called as a result of the user selecting the options
3339 * menu to see the download window, or when a download changes state. It
3340 * shows the download window ontop of the current window.
3341 */
3342 /* package */ void viewDownloads(Uri downloadRecord) {
3343 Intent intent = new Intent(this,
3344 BrowserDownloadPage.class);
3345 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003346 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003347
3348 }
3349
Leon Scroggins160a7e72009-08-14 18:28:01 -04003350 /**
3351 * Open the Go page.
3352 * @param startWithHistory If true, open starting on the history tab.
3353 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003354 */
Leon Scroggins30444232009-09-04 18:36:20 -04003355 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003356 WebView current = mTabControl.getCurrentWebView();
3357 if (current == null) {
3358 return;
3359 }
3360 Intent intent = new Intent(this,
3361 CombinedBookmarkHistoryActivity.class);
3362 String title = current.getTitle();
3363 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003364 Bitmap thumbnail = createScreenshot(current);
3365
The Android Open Source Project0c908882009-03-03 19:32:16 -08003366 // Just in case the user opens bookmarks before a page finishes loading
3367 // so the current history item, and therefore the page, is null.
3368 if (null == url) {
3369 url = mLastEnteredUrl;
3370 // This can happen.
3371 if (null == url) {
3372 url = mSettings.getHomePage();
3373 }
3374 }
3375 // In case the web page has not yet received its associated title.
3376 if (title == null) {
3377 title = url;
3378 }
3379 intent.putExtra("title", title);
3380 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003381 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003382 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003383 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003384 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003385 if (startWithHistory) {
3386 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3387 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3388 }
3389 startActivityForResult(intent, COMBO_PAGE);
3390 }
3391
3392 // Called when loading from context menu or LOAD_URL message
3393 private void loadURL(WebView view, String url) {
3394 // In case the user enters nothing.
3395 if (url != null && url.length() != 0 && view != null) {
3396 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003397 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003398 view.loadUrl(url);
3399 }
3400 }
3401 }
3402
The Android Open Source Project0c908882009-03-03 19:32:16 -08003403 private String smartUrlFilter(Uri inUri) {
3404 if (inUri != null) {
3405 return smartUrlFilter(inUri.toString());
3406 }
3407 return null;
3408 }
3409
Feng Qianb34f87a2009-03-24 21:27:26 -07003410 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003411 "(?i)" + // switch on case insensitive matching
3412 "(" + // begin group for schema
3413 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003414 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003415 ")" +
3416 "(.*)" );
3417
3418 /**
3419 * Attempts to determine whether user input is a URL or search
3420 * terms. Anything with a space is passed to search.
3421 *
3422 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3423 * "Http://" converts to "http://"
3424 *
3425 * @return Original or modified URL
3426 *
3427 */
3428 String smartUrlFilter(String url) {
3429
3430 String inUrl = url.trim();
3431 boolean hasSpace = inUrl.indexOf(' ') != -1;
3432
3433 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3434 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003435 // force scheme to lowercase
3436 String scheme = matcher.group(1);
3437 String lcScheme = scheme.toLowerCase();
3438 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003439 inUrl = lcScheme + matcher.group(2);
3440 }
3441 if (hasSpace) {
3442 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003443 }
3444 return inUrl;
3445 }
3446 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003447 // FIXME: Is this the correct place to add to searches?
3448 // what if someone else calls this function?
3449 int shortcut = parseUrlShortcut(inUrl);
3450 if (shortcut != SHORTCUT_INVALID) {
3451 Browser.addSearchUrl(mResolver, inUrl);
3452 String query = inUrl.substring(2);
3453 switch (shortcut) {
3454 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003455 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003456 case SHORTCUT_WIKIPEDIA_SEARCH:
3457 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3458 case SHORTCUT_DICTIONARY_SEARCH:
3459 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3460 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003461 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003462 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003463 }
3464 }
3465 } else {
3466 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
3467 return URLUtil.guessUrl(inUrl);
3468 }
3469 }
3470
3471 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003472 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003473 }
3474
Ben Murdochbff2d602009-07-01 20:19:05 +01003475 /* package */ void setShouldShowErrorConsole(boolean flag) {
3476 if (flag == mShouldShowErrorConsole) {
3477 // Nothing to do.
3478 return;
3479 }
3480
3481 mShouldShowErrorConsole = flag;
3482
Grace Kloba22ac16e2009-10-07 18:00:23 -07003483 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3484 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003485
3486 if (flag) {
3487 // Setting the show state of the console will cause it's the layout to be inflated.
3488 if (errorConsole.numberOfErrors() > 0) {
3489 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3490 } else {
3491 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3492 }
3493
3494 // Now we can add it to the main view.
3495 mErrorConsoleContainer.addView(errorConsole,
3496 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
3497 ViewGroup.LayoutParams.WRAP_CONTENT));
3498 } else {
3499 mErrorConsoleContainer.removeView(errorConsole);
3500 }
3501
3502 }
3503
Grace Kloba22ac16e2009-10-07 18:00:23 -07003504 boolean shouldShowErrorConsole() {
3505 return mShouldShowErrorConsole;
3506 }
3507
Andrei Popescu163ab742009-10-20 17:58:23 +01003508 private void setStatusBarVisibility(boolean visible) {
3509 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3510 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3511 }
3512
Grace Klobaeb6eef42009-09-15 17:56:32 -07003513 final static int LOCK_ICON_UNSECURE = 0;
3514 final static int LOCK_ICON_SECURE = 1;
3515 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003516
The Android Open Source Project0c908882009-03-03 19:32:16 -08003517 private BrowserSettings mSettings;
3518 private TabControl mTabControl;
3519 private ContentResolver mResolver;
3520 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003521 private View mCustomView;
3522 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003523 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003524
3525 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3526 // view, we should rewrite this.
3527 private int mCurrentMenuState = 0;
3528 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003529 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003530 private static final int EMPTY_MENU = -1;
3531 private Menu mMenu;
3532
3533 private FindDialog mFindDialog;
3534 // Used to prevent chording to result in firing two shortcuts immediately
3535 // one after another. Fixes bug 1211714.
3536 boolean mCanChord;
3537
3538 private boolean mInLoad;
3539 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003540 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003541
The Android Open Source Project0c908882009-03-03 19:32:16 -08003542 private boolean mActivityInPause = true;
3543
3544 private boolean mMenuIsDown;
3545
The Android Open Source Project0c908882009-03-03 19:32:16 -08003546 private static boolean mInTrace;
3547
3548 // Performance probe
3549 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3550 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3551 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3552 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3553 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3554 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3555 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3556 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3557 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3558 };
3559
3560 private long mStart;
3561 private long mProcessStart;
3562 private long mUserStart;
3563 private long mSystemStart;
3564 private long mIdleStart;
3565 private long mIrqStart;
3566
3567 private long mUiStart;
3568
3569 private Drawable mMixLockIcon;
3570 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003571
3572 /* hold a ref so we can auto-cancel if necessary */
3573 private AlertDialog mAlertDialog;
3574
3575 // Wait for credentials before loading google.com
3576 private ProgressDialog mCredsDlg;
3577
3578 // The up-to-date URL and title (these can be different from those stored
3579 // in WebView, since it takes some time for the information in WebView to
3580 // get updated)
3581 private String mUrl;
3582 private String mTitle;
3583
3584 // As PageInfo has different style for landscape / portrait, we have
3585 // to re-open it when configuration changed
3586 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003587 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003588 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3589 // dialog, we should not just dismiss it, but should get back to the
3590 // SSL-certificate-on-error dialog. This flag is used to store this state
3591 private Boolean mPageInfoFromShowSSLCertificateOnError;
3592
3593 // as SSLCertificateOnError has different style for landscape / portrait,
3594 // we have to re-open it when configuration changed
3595 private AlertDialog mSSLCertificateOnErrorDialog;
3596 private WebView mSSLCertificateOnErrorView;
3597 private SslErrorHandler mSSLCertificateOnErrorHandler;
3598 private SslError mSSLCertificateOnErrorError;
3599
3600 // as SSLCertificate has different style for landscape / portrait, we
3601 // have to re-open it when configuration changed
3602 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003603 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003604
3605 // as HttpAuthentication has different style for landscape / portrait, we
3606 // have to re-open it when configuration changed
3607 private AlertDialog mHttpAuthenticationDialog;
3608 private HttpAuthHandler mHttpAuthHandler;
3609
3610 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3611 new FrameLayout.LayoutParams(
3612 ViewGroup.LayoutParams.FILL_PARENT,
3613 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003614 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3615 new FrameLayout.LayoutParams(
3616 ViewGroup.LayoutParams.FILL_PARENT,
3617 ViewGroup.LayoutParams.FILL_PARENT,
3618 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003619 // Google search
3620 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003621 // Wikipedia search
3622 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3623 // Dictionary search
3624 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3625 // Google Mobile Local search
3626 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3627
3628 final static String QUERY_PLACE_HOLDER = "%s";
3629
3630 // "source" parameter for Google search through search key
3631 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3632 // "source" parameter for Google search through goto menu
3633 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3634 // "source" parameter for Google search through simplily type
3635 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3636 // "source" parameter for Google search suggested by the browser
3637 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3638 // "source" parameter for Google search from unknown source
3639 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3640
3641 private final static String LOGTAG = "browser";
3642
The Android Open Source Project0c908882009-03-03 19:32:16 -08003643 private String mLastEnteredUrl;
3644
3645 private PowerManager.WakeLock mWakeLock;
3646 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3647
3648 private Toast mStopToast;
3649
Leon Scroggins68579392009-09-15 15:31:54 -04003650 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003651
Ben Murdochbff2d602009-07-01 20:19:05 +01003652 private LinearLayout mErrorConsoleContainer = null;
3653 private boolean mShouldShowErrorConsole = false;
3654
The Android Open Source Project0c908882009-03-03 19:32:16 -08003655 // As the ids are dynamically created, we can't guarantee that they will
3656 // be in sequence, so this static array maps ids to a window number.
3657 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3658 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3659 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3660 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3661
3662 // monitor platform changes
3663 private IntentFilter mNetworkStateChangedFilter;
3664 private BroadcastReceiver mNetworkStateIntentReceiver;
3665
Grace Klobab4da0ad2009-05-14 14:45:40 -07003666 private BroadcastReceiver mPackageInstallationReceiver;
3667
The Android Open Source Project0c908882009-03-03 19:32:16 -08003668 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003669 final static int COMBO_PAGE = 1;
3670 final static int DOWNLOAD_PAGE = 2;
3671 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003672 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003673
Andrei Popescu540035d2009-09-18 18:59:20 +01003674 // the default <video> poster
3675 private Bitmap mDefaultVideoPoster;
3676 // the video progress view
3677 private View mVideoProgressView;
3678
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003679 /**
3680 * A UrlData class to abstract how the content will be set to WebView.
3681 * This base class uses loadUrl to show the content.
3682 */
3683 private static class UrlData {
3684 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07003685 byte[] mPostData;
3686
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003687 UrlData(String url) {
3688 this.mUrl = url;
3689 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003690
3691 void setPostData(byte[] postData) {
3692 mPostData = postData;
3693 }
3694
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003695 boolean isEmpty() {
3696 return mUrl == null || mUrl.length() == 0;
3697 }
3698
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003699 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07003700 if (mPostData != null) {
3701 webView.postUrl(mUrl, mPostData);
3702 } else {
3703 webView.loadUrl(mUrl);
3704 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003705 }
3706 };
3707
3708 /**
3709 * A subclass of UrlData class that can display inlined content using
3710 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
3711 */
3712 private static class InlinedUrlData extends UrlData {
3713 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
3714 super(failUrl);
3715 mInlined = inlined;
3716 mMimeType = mimeType;
3717 mEncoding = encoding;
3718 }
3719 String mMimeType;
3720 String mInlined;
3721 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003722 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003723 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01003724 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003725 }
3726
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003727 @Override
3728 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003729 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
3730 }
3731 }
3732
Leon Scroggins1f005d32009-08-10 17:36:42 -04003733 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003734}