blob: 7b1452820d285553c64f932d4b156e1504d2b296 [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;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000112import java.io.IOException;
113import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800114import java.net.MalformedURLException;
115import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700116import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800117import java.net.URL;
118import java.net.URLEncoder;
119import java.text.ParseException;
120import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800121import java.util.HashMap;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800122import java.util.regex.Matcher;
123import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800124
125public class BrowserActivity extends Activity
Grace Kloba5942df02009-09-18 11:48:29 -0700126 implements View.OnCreateContextMenuListener,
The Android Open Source Project0c908882009-03-03 19:32:16 -0800127 DownloadListener {
128
Dave Bort31a6d1c2009-04-13 15:56:49 -0700129 /* Define some aliases to make these debugging flags easier to refer to.
130 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
131 */
132 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
133 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
134 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
135
The Android Open Source Project0c908882009-03-03 19:32:16 -0800136 private IGoogleLoginService mGls = null;
137 private ServiceConnection mGlsConnection = null;
138
Satish Sampath565505b2009-05-29 15:37:27 +0100139 // These are single-character shortcuts for searching popular sources.
140 private static final int SHORTCUT_INVALID = 0;
141 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
142 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
143 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
144 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
145
The Android Open Source Project0c908882009-03-03 19:32:16 -0800146 private void setupHomePage() {
147 final Runnable getAccount = new Runnable() {
148 public void run() {
149 // Lower priority
150 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
151 // get the default home page
152 String homepage = mSettings.getHomePage();
153
154 try {
155 if (mGls == null) return;
156
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700157 if (!homepage.startsWith("http://www.google.")) return;
158 if (homepage.indexOf('?') == -1) return;
159
The Android Open Source Project0c908882009-03-03 19:32:16 -0800160 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
161 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
162
163 // three cases:
164 //
165 // hostedUser == googleUser
166 // The device has only a google account
167 //
168 // hostedUser != googleUser
169 // The device has a hosted account and a google account
170 //
171 // hostedUser != null, googleUser == null
172 // The device has only a hosted account (so far)
173
174 // developers might have no accounts at all
175 if (hostedUser == null) return;
176
177 if (googleUser == null || !hostedUser.equals(googleUser)) {
178 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700179 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800180 }
181 } catch (RemoteException ignore) {
182 // Login service died; carry on
183 } catch (RuntimeException ignore) {
184 // Login service died; carry on
185 } finally {
186 finish(homepage);
187 }
188 }
189
190 private void finish(final String homepage) {
191 mHandler.post(new Runnable() {
192 public void run() {
193 mSettings.setHomePage(BrowserActivity.this, homepage);
194 resumeAfterCredentials();
195
196 // as this is running in a separate thread,
197 // BrowserActivity's onDestroy() may have been called,
198 // which also calls unbindService().
199 if (mGlsConnection != null) {
200 // we no longer need to keep GLS open
201 unbindService(mGlsConnection);
202 mGlsConnection = null;
203 }
204 } });
205 } };
206
207 final boolean[] done = { false };
208
209 // Open a connection to the Google Login Service. The first
210 // time the connection is established, set up the homepage depending on
211 // the account in a background thread.
212 mGlsConnection = new ServiceConnection() {
213 public void onServiceConnected(ComponentName className, IBinder service) {
214 mGls = IGoogleLoginService.Stub.asInterface(service);
215 if (done[0] == false) {
216 done[0] = true;
217 Thread account = new Thread(getAccount);
218 account.setName("GLSAccount");
219 account.start();
220 }
221 }
222 public void onServiceDisconnected(ComponentName className) {
223 mGls = null;
224 }
225 };
226
227 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
228 mGlsConnection, Context.BIND_AUTO_CREATE);
229 }
230
Cary Clarka9771242009-08-11 16:42:26 -0400231 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800232 @Override
233 public Void doInBackground(File... files) {
234 if (files != null) {
235 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400236 if (!f.delete()) {
237 Log.e(LOGTAG, f.getPath() + " was not deleted");
238 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800239 }
240 }
241 return null;
242 }
243 }
244
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400245 /**
246 * This layout holds everything you see below the status bar, including the
247 * error console, the custom view container, and the webviews.
248 */
249 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400250
Grace Kloba22ac16e2009-10-07 18:00:23 -0700251 @Override
252 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700253 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800254 Log.v(LOGTAG, this + " onStart");
255 }
256 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800257 // test the browser in OpenGL
258 // requestWindowFeature(Window.FEATURE_OPENGL);
259
260 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
261
262 mResolver = getContentResolver();
263
Grace Kloba0923d692009-09-23 21:37:25 -0700264 // If this was a web search request, pass it on to the default web
265 // search provider and finish this activity.
266 if (handleWebSearchIntent(getIntent())) {
267 finish();
268 return;
269 }
270
The Android Open Source Project0c908882009-03-03 19:32:16 -0800271 mSecLockIcon = Resources.getSystem().getDrawable(
272 android.R.drawable.ic_secure);
273 mMixLockIcon = Resources.getSystem().getDrawable(
274 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800275
Leon Scroggins81db3662009-06-04 17:45:11 -0400276 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
277 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400278 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
279 .inflate(R.layout.custom_screen, null);
280 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
281 R.id.main_content);
282 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
283 .findViewById(R.id.error_console);
284 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
285 .findViewById(R.id.fullscreen_custom_content);
286 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400287 mTitleBar = new TitleBar(this);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400288 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800289
290 // Create the tab control and our initial tab
291 mTabControl = new TabControl(this);
292
293 // Open the icon database and retain all the bookmark urls for favicons
294 retainIconsOnStartup();
295
296 // Keep a settings instance handy.
297 mSettings = BrowserSettings.getInstance();
298 mSettings.setTabControl(mTabControl);
299 mSettings.loadFromDb(this);
300
301 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
302 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
303
Grace Klobaa34f6862009-07-31 16:28:17 -0700304 /* enables registration for changes in network status from
305 http stack */
306 mNetworkStateChangedFilter = new IntentFilter();
307 mNetworkStateChangedFilter.addAction(
308 ConnectivityManager.CONNECTIVITY_ACTION);
309 mNetworkStateIntentReceiver = new BroadcastReceiver() {
310 @Override
311 public void onReceive(Context context, Intent intent) {
312 if (intent.getAction().equals(
313 ConnectivityManager.CONNECTIVITY_ACTION)) {
Robert Greenwalt7d899d62009-10-23 10:33:48 -0700314 boolean noConnectivity = intent.getBooleanExtra(
315 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
316 onNetworkToggle(!noConnectivity);
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 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001056 }
1057
Grace Kloba22ac16e2009-10-07 18:00:23 -07001058 @Override
1059 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001060 super.onLowMemory();
1061 mTabControl.freeMemory();
1062 }
1063
Mike Reed7bfa63b2009-05-28 11:08:32 -04001064 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001065 Tab tab = mTabControl.getCurrentTab();
1066 boolean inLoad = tab.inLoad();
1067 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001068 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001069 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001070 if (w != null) {
1071 w.resumeTimers();
1072 }
1073 return true;
1074 } else {
1075 return false;
1076 }
1077 }
1078
Mike Reed7bfa63b2009-05-28 11:08:32 -04001079 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001080 Tab tab = mTabControl.getCurrentTab();
1081 boolean inLoad = tab.inLoad();
1082 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001083 CookieSyncManager.getInstance().stopSync();
1084 WebView w = mTabControl.getCurrentWebView();
1085 if (w != null) {
1086 w.pauseTimers();
1087 }
1088 return true;
1089 } else {
1090 return false;
1091 }
1092 }
1093
Leon Scroggins1f005d32009-08-10 17:36:42 -04001094 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001095 /*
1096 * This function is called when we are launching for the first time. We
1097 * are waiting for the login credentials before loading Google home
1098 * pages. This way the user will be logged in straight away.
1099 */
1100 private void waitForCredentials() {
1101 // Show a toast
1102 mCredsDlg = new ProgressDialog(this);
1103 mCredsDlg.setIndeterminate(true);
1104 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1105 // If the user cancels the operation, then cancel the Google
1106 // Credentials request.
1107 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1108 mCredsDlg.show();
1109
1110 // We set a timeout for the retrieval of credentials in onResume()
1111 // as that is when we have freed up some CPU time to get
1112 // the login credentials.
1113 }
1114
1115 /*
1116 * If we have received the credentials or we have timed out and we are
1117 * showing the credentials dialog, then it is time to move on.
1118 */
1119 private void resumeAfterCredentials() {
1120 if (mCredsDlg == null) {
1121 return;
1122 }
1123
1124 // Clear the toast
1125 if (mCredsDlg.isShowing()) {
1126 mCredsDlg.dismiss();
1127 }
1128 mCredsDlg = null;
1129
1130 // Clear any pending timeout
1131 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1132
1133 // Load the page
1134 WebView w = mTabControl.getCurrentWebView();
1135 if (w != null) {
1136 w.loadUrl(mSettings.getHomePage());
1137 }
1138
1139 // Update the settings, need to do this last as it can take a moment
1140 // to persist the settings. In the mean time we could be loading
1141 // content.
1142 mSettings.setLoginInitialized(this);
1143 }
1144
1145 // Open the icon database and retain all the icons for visited sites.
1146 private void retainIconsOnStartup() {
1147 final WebIconDatabase db = WebIconDatabase.getInstance();
1148 db.open(getDir("icons", 0).getPath());
1149 try {
1150 Cursor c = Browser.getAllBookmarks(mResolver);
1151 if (!c.moveToFirst()) {
1152 c.deactivate();
1153 return;
1154 }
1155 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1156 do {
1157 String url = c.getString(urlIndex);
1158 db.retainIconForPageUrl(url);
1159 } while (c.moveToNext());
1160 c.deactivate();
1161 } catch (IllegalStateException e) {
1162 Log.e(LOGTAG, "retainIconsOnStartup", e);
1163 }
1164 }
1165
1166 // Helper method for getting the top window.
1167 WebView getTopWindow() {
1168 return mTabControl.getCurrentTopWebView();
1169 }
1170
Grace Kloba22ac16e2009-10-07 18:00:23 -07001171 TabControl getTabControl() {
1172 return mTabControl;
1173 }
1174
The Android Open Source Project0c908882009-03-03 19:32:16 -08001175 @Override
1176 public boolean onCreateOptionsMenu(Menu menu) {
1177 super.onCreateOptionsMenu(menu);
1178
1179 MenuInflater inflater = getMenuInflater();
1180 inflater.inflate(R.menu.browser, menu);
1181 mMenu = menu;
1182 updateInLoadMenuItems();
1183 return true;
1184 }
1185
1186 /**
1187 * As the menu can be open when loading state changes
1188 * we must manually update the state of the stop/reload menu
1189 * item
1190 */
1191 private void updateInLoadMenuItems() {
1192 if (mMenu == null) {
1193 return;
1194 }
1195 MenuItem src = mInLoad ?
1196 mMenu.findItem(R.id.stop_menu_id):
1197 mMenu.findItem(R.id.reload_menu_id);
1198 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1199 dest.setIcon(src.getIcon());
1200 dest.setTitle(src.getTitle());
1201 }
1202
1203 @Override
1204 public boolean onContextItemSelected(MenuItem item) {
1205 // chording is not an issue with context menus, but we use the same
1206 // options selector, so set mCanChord to true so we can access them.
1207 mCanChord = true;
1208 int id = item.getItemId();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001209 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001210 // For the context menu from the title bar
1211 case R.id.title_bar_share_page_url:
1212 case R.id.title_bar_copy_page_url:
1213 WebView mainView = mTabControl.getCurrentWebView();
1214 if (null == mainView) {
1215 return false;
1216 }
1217 if (id == R.id.title_bar_share_page_url) {
1218 Browser.sendString(this, mainView.getUrl());
1219 } else {
1220 copy(mainView.getUrl());
1221 }
1222 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001223 // -- Browser context menu
1224 case R.id.open_context_menu_id:
1225 case R.id.open_newtab_context_menu_id:
1226 case R.id.bookmark_context_menu_id:
1227 case R.id.save_link_context_menu_id:
1228 case R.id.share_link_context_menu_id:
1229 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001230 final WebView webView = getTopWindow();
1231 if (null == webView) {
1232 return false;
1233 }
1234 final HashMap hrefMap = new HashMap();
1235 hrefMap.put("webview", webView);
1236 final Message msg = mHandler.obtainMessage(
1237 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001238 webView.requestFocusNodeHref(msg);
1239 break;
1240
1241 default:
1242 // For other context menus
1243 return onOptionsItemSelected(item);
1244 }
1245 mCanChord = false;
1246 return true;
1247 }
1248
1249 private Bundle createGoogleSearchSourceBundle(String source) {
1250 Bundle bundle = new Bundle();
1251 bundle.putString(SearchManager.SOURCE, source);
1252 return bundle;
1253 }
1254
1255 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001256 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001257 */
1258 @Override
1259 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001260 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001261 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001262 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001263 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001264 return true;
1265 }
1266
1267 @Override
1268 public void startSearch(String initialQuery, boolean selectInitialQuery,
1269 Bundle appSearchData, boolean globalSearch) {
1270 if (appSearchData == null) {
1271 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1272 }
1273 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1274 }
1275
Leon Scroggins1f005d32009-08-10 17:36:42 -04001276 /**
1277 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1278 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001279 * @param index Index of the tab to change to, as defined by
1280 * mTabControl.getTabIndex(Tab t).
1281 * @return boolean True if we successfully switched to a different tab. If
1282 * the indexth tab is null, or if that tab is the same as
1283 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001284 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001285 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001286 Tab tab = mTabControl.getTab(index);
1287 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001288 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001289 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001290 }
1291 if (currentTab != null) {
1292 // currentTab may be null if it was just removed. In that case,
1293 // we do not need to remove it
1294 removeTabFromContentView(currentTab);
1295 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001296 mTabControl.setCurrentTab(tab);
1297 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001298 resetTitleIconAndProgress();
1299 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001300 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001301 }
1302
Grace Kloba22ac16e2009-10-07 18:00:23 -07001303 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001304 return openTabAndShow(mSettings.getHomePage(), false, null);
1305 }
1306
Leon Scroggins1f005d32009-08-10 17:36:42 -04001307 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001308 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001309 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001310 // This is the last tab. Open a new one, with the home
1311 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001312 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001313 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001314 return;
1315 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001316 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001317 int indexToShow = -1;
1318 if (parent != null) {
1319 indexToShow = mTabControl.getTabIndex(parent);
1320 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001321 final int currentIndex = mTabControl.getCurrentIndex();
1322 // Try to move to the tab to the right
1323 indexToShow = currentIndex + 1;
1324 if (indexToShow > mTabControl.getTabCount() - 1) {
1325 // Try to move to the tab to the left
1326 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001327 }
1328 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001329 if (switchToTab(indexToShow)) {
1330 // Close window
1331 closeTab(current);
1332 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001333 }
1334
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001335 private ActiveTabsPage mActiveTabsPage;
1336
1337 /**
1338 * Remove the active tabs page.
1339 * @param needToAttach If true, the active tabs page did not attach a tab
1340 * to the content view, so we need to do that here.
1341 */
1342 /* package */ void removeActiveTabPage(boolean needToAttach) {
1343 mContentView.removeView(mActiveTabsPage);
1344 mActiveTabsPage = null;
1345 mMenuState = R.id.MAIN_MENU;
1346 if (needToAttach) {
1347 attachTabToContentView(mTabControl.getCurrentTab());
1348 }
1349 getTopWindow().requestFocus();
1350 }
1351
The Android Open Source Project0c908882009-03-03 19:32:16 -08001352 @Override
1353 public boolean onOptionsItemSelected(MenuItem item) {
1354 if (!mCanChord) {
1355 // The user has already fired a shortcut with this hold down of the
1356 // menu key.
1357 return false;
1358 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001359 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001360 return false;
1361 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001362 if (mMenuIsDown) {
1363 // The shortcut action consumes the MENU. Even if it is still down,
1364 // it won't trigger the next shortcut action. In the case of the
1365 // shortcut action triggering a new activity, like Bookmarks, we
1366 // won't get onKeyUp for MENU. So it is important to reset it here.
1367 mMenuIsDown = false;
1368 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001369 switch (item.getItemId()) {
1370 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001371 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001372 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001373 break;
1374
Leon Scroggins64b80f32009-08-07 12:03:34 -04001375 case R.id.goto_menu_id:
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001376 onSearchRequested();
1377 break;
1378
1379 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001380 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001381 break;
1382
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001383 case R.id.active_tabs_menu_id:
1384 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1385 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001386 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001387 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1388 mActiveTabsPage.requestFocus();
1389 mMenuState = EMPTY_MENU;
1390 break;
1391
Leon Scroggins1f005d32009-08-10 17:36:42 -04001392 case R.id.add_bookmark_menu_id:
1393 Intent i = new Intent(BrowserActivity.this,
1394 AddBookmarkPage.class);
1395 WebView w = getTopWindow();
1396 i.putExtra("url", w.getUrl());
1397 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001398 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001399 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001400 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001401 break;
1402
1403 case R.id.stop_reload_menu_id:
1404 if (mInLoad) {
1405 stopLoading();
1406 } else {
1407 getTopWindow().reload();
1408 }
1409 break;
1410
1411 case R.id.back_menu_id:
1412 getTopWindow().goBack();
1413 break;
1414
1415 case R.id.forward_menu_id:
1416 getTopWindow().goForward();
1417 break;
1418
1419 case R.id.close_menu_id:
1420 // Close the subwindow if it exists.
1421 if (mTabControl.getCurrentSubWindow() != null) {
1422 dismissSubWindow(mTabControl.getCurrentTab());
1423 break;
1424 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001425 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001426 break;
1427
1428 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001429 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001430 if (current != null) {
1431 dismissSubWindow(current);
1432 current.getWebView().loadUrl(mSettings.getHomePage());
1433 }
1434 break;
1435
1436 case R.id.preferences_menu_id:
1437 Intent intent = new Intent(this,
1438 BrowserPreferencesPage.class);
1439 startActivityForResult(intent, PREFERENCES_PAGE);
1440 break;
1441
1442 case R.id.find_menu_id:
1443 if (null == mFindDialog) {
1444 mFindDialog = new FindDialog(this);
1445 }
1446 mFindDialog.setWebView(getTopWindow());
1447 mFindDialog.show();
1448 mMenuState = EMPTY_MENU;
1449 break;
1450
1451 case R.id.select_text_id:
1452 getTopWindow().emulateShiftHeld();
1453 break;
1454 case R.id.page_info_menu_id:
1455 showPageInfo(mTabControl.getCurrentTab(), false);
1456 break;
1457
1458 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001459 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001460 break;
1461
1462 case R.id.share_page_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01001463 Browser.sendString(this, getTopWindow().getUrl(),
1464 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001465 break;
1466
1467 case R.id.dump_nav_menu_id:
1468 getTopWindow().debugDump();
1469 break;
1470
1471 case R.id.zoom_in_menu_id:
1472 getTopWindow().zoomIn();
1473 break;
1474
1475 case R.id.zoom_out_menu_id:
1476 getTopWindow().zoomOut();
1477 break;
1478
1479 case R.id.view_downloads_menu_id:
1480 viewDownloads(null);
1481 break;
1482
The Android Open Source Project0c908882009-03-03 19:32:16 -08001483 case R.id.window_one_menu_id:
1484 case R.id.window_two_menu_id:
1485 case R.id.window_three_menu_id:
1486 case R.id.window_four_menu_id:
1487 case R.id.window_five_menu_id:
1488 case R.id.window_six_menu_id:
1489 case R.id.window_seven_menu_id:
1490 case R.id.window_eight_menu_id:
1491 {
1492 int menuid = item.getItemId();
1493 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1494 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001495 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001496 if (desiredTab != null &&
1497 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001498 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001499 }
1500 break;
1501 }
1502 }
1503 }
1504 break;
1505
1506 default:
1507 if (!super.onOptionsItemSelected(item)) {
1508 return false;
1509 }
1510 // Otherwise fall through.
1511 }
1512 mCanChord = false;
1513 return true;
1514 }
1515
1516 public void closeFind() {
1517 mMenuState = R.id.MAIN_MENU;
1518 }
1519
Grace Kloba22ac16e2009-10-07 18:00:23 -07001520 @Override
1521 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001522 // This happens when the user begins to hold down the menu key, so
1523 // allow them to chord to get a shortcut.
1524 mCanChord = true;
1525 // Note: setVisible will decide whether an item is visible; while
1526 // setEnabled() will decide whether an item is enabled, which also means
1527 // whether the matching shortcut key will function.
1528 super.onPrepareOptionsMenu(menu);
1529 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001530 case EMPTY_MENU:
1531 if (mCurrentMenuState != mMenuState) {
1532 menu.setGroupVisible(R.id.MAIN_MENU, false);
1533 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1534 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001535 }
1536 break;
1537 default:
1538 if (mCurrentMenuState != mMenuState) {
1539 menu.setGroupVisible(R.id.MAIN_MENU, true);
1540 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1541 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001542 }
1543 final WebView w = getTopWindow();
1544 boolean canGoBack = false;
1545 boolean canGoForward = false;
1546 boolean isHome = false;
1547 if (w != null) {
1548 canGoBack = w.canGoBack();
1549 canGoForward = w.canGoForward();
1550 isHome = mSettings.getHomePage().equals(w.getUrl());
1551 }
1552 final MenuItem back = menu.findItem(R.id.back_menu_id);
1553 back.setEnabled(canGoBack);
1554
1555 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1556 home.setEnabled(!isHome);
1557
1558 menu.findItem(R.id.forward_menu_id)
1559 .setEnabled(canGoForward);
1560
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001561 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001562 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001563
The Android Open Source Project0c908882009-03-03 19:32:16 -08001564 // decide whether to show the share link option
1565 PackageManager pm = getPackageManager();
1566 Intent send = new Intent(Intent.ACTION_SEND);
1567 send.setType("text/plain");
1568 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1569 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1570
The Android Open Source Project0c908882009-03-03 19:32:16 -08001571 boolean isNavDump = mSettings.isNavDump();
1572 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1573 nav.setVisible(isNavDump);
1574 nav.setEnabled(isNavDump);
1575 break;
1576 }
1577 mCurrentMenuState = mMenuState;
1578 return true;
1579 }
1580
1581 @Override
1582 public void onCreateContextMenu(ContextMenu menu, View v,
1583 ContextMenuInfo menuInfo) {
1584 WebView webview = (WebView) v;
1585 WebView.HitTestResult result = webview.getHitTestResult();
1586 if (result == null) {
1587 return;
1588 }
1589
1590 int type = result.getType();
1591 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1592 Log.w(LOGTAG,
1593 "We should not show context menu when nothing is touched");
1594 return;
1595 }
1596 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1597 // let TextView handles context menu
1598 return;
1599 }
1600
1601 // Note, http://b/issue?id=1106666 is requesting that
1602 // an inflated menu can be used again. This is not available
1603 // yet, so inflate each time (yuk!)
1604 MenuInflater inflater = getMenuInflater();
1605 inflater.inflate(R.menu.browsercontext, menu);
1606
1607 // Show the correct menu group
1608 String extra = result.getExtra();
1609 menu.setGroupVisible(R.id.PHONE_MENU,
1610 type == WebView.HitTestResult.PHONE_TYPE);
1611 menu.setGroupVisible(R.id.EMAIL_MENU,
1612 type == WebView.HitTestResult.EMAIL_TYPE);
1613 menu.setGroupVisible(R.id.GEO_MENU,
1614 type == WebView.HitTestResult.GEO_TYPE);
1615 menu.setGroupVisible(R.id.IMAGE_MENU,
1616 type == WebView.HitTestResult.IMAGE_TYPE
1617 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1618 menu.setGroupVisible(R.id.ANCHOR_MENU,
1619 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1620 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1621
1622 // Setup custom handling depending on the type
1623 switch (type) {
1624 case WebView.HitTestResult.PHONE_TYPE:
1625 menu.setHeaderTitle(Uri.decode(extra));
1626 menu.findItem(R.id.dial_context_menu_id).setIntent(
1627 new Intent(Intent.ACTION_VIEW, Uri
1628 .parse(WebView.SCHEME_TEL + extra)));
1629 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1630 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001631 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001632 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1633 addIntent);
1634 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1635 new Copy(extra));
1636 break;
1637
1638 case WebView.HitTestResult.EMAIL_TYPE:
1639 menu.setHeaderTitle(extra);
1640 menu.findItem(R.id.email_context_menu_id).setIntent(
1641 new Intent(Intent.ACTION_VIEW, Uri
1642 .parse(WebView.SCHEME_MAILTO + extra)));
1643 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1644 new Copy(extra));
1645 break;
1646
1647 case WebView.HitTestResult.GEO_TYPE:
1648 menu.setHeaderTitle(extra);
1649 menu.findItem(R.id.map_context_menu_id).setIntent(
1650 new Intent(Intent.ACTION_VIEW, Uri
1651 .parse(WebView.SCHEME_GEO
1652 + URLEncoder.encode(extra))));
1653 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1654 new Copy(extra));
1655 break;
1656
1657 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1658 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1659 TextView titleView = (TextView) LayoutInflater.from(this)
1660 .inflate(android.R.layout.browser_link_context_header,
1661 null);
1662 titleView.setText(extra);
1663 menu.setHeaderView(titleView);
1664 // decide whether to show the open link in new tab option
1665 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001666 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001667 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1668 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001669 PackageManager pm = getPackageManager();
1670 Intent send = new Intent(Intent.ACTION_SEND);
1671 send.setType("text/plain");
1672 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1673 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1674 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1675 break;
1676 }
1677 // otherwise fall through to handle image part
1678 case WebView.HitTestResult.IMAGE_TYPE:
1679 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1680 menu.setHeaderTitle(extra);
1681 }
1682 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1683 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1684 menu.findItem(R.id.download_context_menu_id).
1685 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001686 menu.findItem(R.id.set_wallpaper_context_menu_id).
1687 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001688 break;
1689
1690 default:
1691 Log.w(LOGTAG, "We should not get here.");
1692 break;
1693 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001694 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001695 }
1696
The Android Open Source Project0c908882009-03-03 19:32:16 -08001697 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001698 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001699 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001700 // Attach the container that contains the main WebView and any other UI
1701 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001702 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001703
1704 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001705 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001706 if (errorConsole.numberOfErrors() == 0) {
1707 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1708 } else {
1709 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1710 }
1711
1712 mErrorConsoleContainer.addView(errorConsole,
1713 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1714 ViewGroup.LayoutParams.WRAP_CONTENT));
1715 }
1716
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001717 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001718 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001719 // Request focus on the top window.
1720 t.getTopWindow().requestFocus();
1721 }
1722
1723 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001724 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001725 t.attachSubWindow(mContentView);
1726 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001727 }
1728
1729 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001730 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001731 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001732 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001733
Grace Kloba22ac16e2009-10-07 18:00:23 -07001734 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1735 if (errorConsole != null) {
1736 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001737 }
1738
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001739 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001740 if (view != null) {
1741 view.setEmbeddedTitleBar(null);
1742 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001743 }
1744
1745 // Remove the sub window if it exists. Also called by TabControl when the
1746 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001747 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001748 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001749 // dismiss the subwindow. This will destroy the WebView.
1750 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001751 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001752 }
1753
Leon Scroggins1f005d32009-08-10 17:36:42 -04001754 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001755 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001756 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001757 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001758 }
1759
1760 // This method does a ton of stuff. It will attempt to create a new tab
1761 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001762 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001763 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1764 String appId) {
1765 final Tab currentTab = mTabControl.getCurrentTab();
1766 if (mTabControl.canCreateNewTab()) {
1767 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1768 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001769 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001770 // If the last tab was removed from the active tabs page, currentTab
1771 // will be null.
1772 if (currentTab != null) {
1773 removeTabFromContentView(currentTab);
1774 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001775 // We must set the new tab as the current tab to reflect the old
1776 // animation behavior.
1777 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001778 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001779 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001780 urlData.loadIn(webview);
1781 }
1782 return tab;
1783 } else {
1784 // Get rid of the subwindow if it exists
1785 dismissSubWindow(currentTab);
1786 if (!urlData.isEmpty()) {
1787 // Load the given url.
1788 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001789 }
1790 }
Grace Klobac9181842009-04-14 08:53:22 -07001791 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001792 }
1793
Grace Kloba22ac16e2009-10-07 18:00:23 -07001794 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001795 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001796 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001797 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001798 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001799 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001800 }
Grace Klobac9181842009-04-14 08:53:22 -07001801 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001802 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001803 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001804 }
1805 }
1806
1807 private class Copy implements OnMenuItemClickListener {
1808 private CharSequence mText;
1809
1810 public boolean onMenuItemClick(MenuItem item) {
1811 copy(mText);
1812 return true;
1813 }
1814
1815 public Copy(CharSequence toCopy) {
1816 mText = toCopy;
1817 }
1818 }
1819
1820 private class Download implements OnMenuItemClickListener {
1821 private String mText;
1822
1823 public boolean onMenuItemClick(MenuItem item) {
1824 onDownloadStartNoStream(mText, null, null, null, -1);
1825 return true;
1826 }
1827
1828 public Download(String toDownload) {
1829 mText = toDownload;
1830 }
1831 }
1832
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001833 private class SetAsWallpaper extends Thread implements
1834 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1835 private URL mUrl;
1836 private ProgressDialog mWallpaperProgress;
1837 private boolean mCanceled = false;
1838
1839 public SetAsWallpaper(String url) {
1840 try {
1841 mUrl = new URL(url);
1842 } catch (MalformedURLException e) {
1843 mUrl = null;
1844 }
1845 }
1846
1847 public void onCancel(DialogInterface dialog) {
1848 mCanceled = true;
1849 }
1850
1851 public boolean onMenuItemClick(MenuItem item) {
1852 if (mUrl != null) {
1853 // The user may have tried to set a image with a large file size as their
1854 // background so it may take a few moments to perform the operation. Display
1855 // a progress spinner while it is working.
1856 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1857 mWallpaperProgress.setIndeterminate(true);
1858 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1859 mWallpaperProgress.setCancelable(true);
1860 mWallpaperProgress.setOnCancelListener(this);
1861 mWallpaperProgress.show();
1862 start();
1863 }
1864 return true;
1865 }
1866
1867 public void run() {
1868 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1869 try {
1870 // TODO: This will cause the resource to be downloaded again, when we
1871 // should in most cases be able to grab it from the cache. To fix this
1872 // we should query WebCore to see if we can access a cached version and
1873 // instead open an input stream on that. This pattern could also be used
1874 // in the download manager where the same problem exists.
1875 InputStream inputstream = mUrl.openStream();
1876 if (inputstream != null) {
1877 setWallpaper(inputstream);
1878 }
1879 } catch (IOException e) {
1880 Log.e(LOGTAG, "Unable to set new wallpaper");
1881 // Act as though the user canceled the operation so we try to
1882 // restore the old wallpaper.
1883 mCanceled = true;
1884 }
1885
1886 if (mCanceled) {
1887 // Restore the old wallpaper if the user cancelled whilst we were setting
1888 // the new wallpaper.
1889 int width = oldWallpaper.getIntrinsicWidth();
1890 int height = oldWallpaper.getIntrinsicHeight();
1891 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1892 Canvas canvas = new Canvas(bm);
1893 oldWallpaper.setBounds(0, 0, width, height);
1894 oldWallpaper.draw(canvas);
1895 try {
1896 setWallpaper(bm);
1897 } catch (IOException e) {
1898 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1899 }
1900 mCanceled = false;
1901 }
1902
1903 if (mWallpaperProgress.isShowing()) {
1904 mWallpaperProgress.dismiss();
1905 }
1906 }
1907 }
1908
The Android Open Source Project0c908882009-03-03 19:32:16 -08001909 private void copy(CharSequence text) {
1910 try {
1911 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1912 if (clip != null) {
1913 clip.setClipboardText(text);
1914 }
1915 } catch (android.os.RemoteException e) {
1916 Log.e(LOGTAG, "Copy failed", e);
1917 }
1918 }
1919
1920 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001921 * Resets the browser title-view to whatever it must be
1922 * (for example, if we had a loading error)
1923 * When we have a new page, we call resetTitle, when we
1924 * have to reset the titlebar to whatever it used to be
1925 * (for example, if the user chose to stop loading), we
1926 * call resetTitleAndRevertLockIcon.
1927 */
1928 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001929 mTabControl.getCurrentTab().revertLockIcon();
1930 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001931 resetTitleIconAndProgress();
1932 }
1933
1934 /**
1935 * Reset the title, favicon, and progress.
1936 */
1937 private void resetTitleIconAndProgress() {
1938 WebView current = mTabControl.getCurrentWebView();
1939 if (current == null) {
1940 return;
1941 }
1942 resetTitleAndIcon(current);
1943 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001944 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001945 }
1946
1947 // Reset the title and the icon based on the given item.
1948 private void resetTitleAndIcon(WebView view) {
1949 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1950 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001951 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001952 setFavicon(item.getFavicon());
1953 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001954 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001955 setFavicon(null);
1956 }
1957 }
1958
1959 /**
1960 * Sets a title composed of the URL and the title string.
1961 * @param url The URL of the site being loaded.
1962 * @param title The title of the site being loaded.
1963 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001964 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001965 mUrl = url;
1966 mTitle = title;
1967
Leon Scroggins68579392009-09-15 15:31:54 -04001968 mTitleBar.setTitleAndUrl(title, url);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001969 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001970 }
1971
1972 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001973 * @param url The URL to build a title version of the URL from.
1974 * @return The title version of the URL or null if fails.
1975 * The title version of the URL can be either the URL hostname,
1976 * or the hostname with an "https://" prefix (for secure URLs),
1977 * or an empty string if, for example, the URL in question is a
1978 * file:// URL with no hostname.
1979 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001980 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001981 String titleUrl = null;
1982
1983 if (url != null) {
1984 try {
1985 // parse the url string
1986 URL urlObj = new URL(url);
1987 if (urlObj != null) {
1988 titleUrl = "";
1989
1990 String protocol = urlObj.getProtocol();
1991 String host = urlObj.getHost();
1992
1993 if (host != null && 0 < host.length()) {
1994 titleUrl = host;
1995 if (protocol != null) {
1996 // if a secure site, add an "https://" prefix!
1997 if (protocol.equalsIgnoreCase("https")) {
1998 titleUrl = protocol + "://" + host;
1999 }
2000 }
2001 }
2002 }
2003 } catch (MalformedURLException e) {}
2004 }
2005
2006 return titleUrl;
2007 }
2008
2009 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002010 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002011 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002012 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002013 }
2014
2015 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002016 * Close the tab, remove its associated title bar, and adjust mTabControl's
2017 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002018 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002019 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002020 int currentIndex = mTabControl.getCurrentIndex();
2021 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002022 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002023 if (currentIndex >= removeIndex && currentIndex != 0) {
2024 currentIndex--;
2025 }
2026 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002027 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002028 }
2029
2030 private void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002031 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002032 if (current == null) {
2033 /*
2034 * Instead of finishing the activity, simply push this to the back
2035 * of the stack and let ActivityManager to choose the foreground
2036 * activity. As BrowserActivity is singleTask, it will be always the
2037 * root of the task. So we can use either true or false for
2038 * moveTaskToBack().
2039 */
2040 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002041 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002042 }
2043 WebView w = current.getWebView();
2044 if (w.canGoBack()) {
2045 w.goBack();
2046 } else {
2047 // Check to see if we are closing a window that was created by
2048 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002049 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002050 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002051 switchToTab(mTabControl.getTabIndex(parent));
2052 // Now we close the other tab
2053 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002054 } else {
2055 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002056 // force the tab's inLoad() to be false as we are going to
2057 // either finish the activity or remove the tab. This will
2058 // ensure pauseWebViewTimers() taking action.
2059 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002060 if (mTabControl.getTabCount() == 1) {
2061 finish();
2062 return;
2063 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002064 // call pauseWebViewTimers() now, we won't be able to call
2065 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002066 // Temporarily change mActivityInPause to be true as
2067 // pauseWebViewTimers() will do nothing if mActivityInPause
2068 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002069 boolean savedState = mActivityInPause;
2070 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002071 Log.e(LOGTAG, "BrowserActivity is already paused "
2072 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002073 }
2074 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002075 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002076 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002077 removeTabFromContentView(current);
2078 mTabControl.removeTab(current);
2079 }
2080 /*
2081 * Instead of finishing the activity, simply push this to the back
2082 * of the stack and let ActivityManager to choose the foreground
2083 * activity. As BrowserActivity is singleTask, it will be always the
2084 * root of the task. So we can use either true or false for
2085 * moveTaskToBack().
2086 */
2087 moveTaskToBack(true);
2088 }
2089 }
2090 }
2091
Grace Kloba22ac16e2009-10-07 18:00:23 -07002092 boolean isMenuDown() {
2093 return mMenuIsDown;
2094 }
2095
Grace Kloba5942df02009-09-18 11:48:29 -07002096 @Override
2097 public boolean onKeyDown(int keyCode, KeyEvent event) {
2098 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2099 // still down, we don't want to trigger the search. Pretend to consume
2100 // the key and do nothing.
2101 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002102
Grace Kloba5942df02009-09-18 11:48:29 -07002103 switch(keyCode) {
2104 case KeyEvent.KEYCODE_MENU:
2105 mMenuIsDown = true;
2106 break;
2107 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002108 // WebView/WebTextView handle the keys in the KeyDown. As
2109 // the Activity's shortcut keys are only handled when WebView
2110 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2111 if (event.isShiftPressed()) {
2112 getTopWindow().pageUp(false);
2113 } else {
2114 getTopWindow().pageDown(false);
2115 }
Grace Kloba5942df02009-09-18 11:48:29 -07002116 return true;
2117 case KeyEvent.KEYCODE_BACK:
2118 if (event.getRepeatCount() == 0) {
2119 event.startTracking();
2120 return true;
2121 } else if (mCustomView == null && mActiveTabsPage == null
2122 && event.isLongPress()) {
2123 bookmarksOrHistoryPicker(true);
2124 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002125 }
Grace Kloba5942df02009-09-18 11:48:29 -07002126 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002127 }
Grace Kloba5942df02009-09-18 11:48:29 -07002128 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002129 }
2130
Grace Kloba5942df02009-09-18 11:48:29 -07002131 @Override
2132 public boolean onKeyUp(int keyCode, KeyEvent event) {
2133 switch(keyCode) {
2134 case KeyEvent.KEYCODE_MENU:
2135 mMenuIsDown = false;
2136 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002137 case KeyEvent.KEYCODE_BACK:
2138 if (event.isTracking() && !event.isCanceled()) {
2139 if (mCustomView != null) {
2140 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002141 mTabControl.getCurrentWebView().getWebChromeClient()
2142 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002143 } else if (mActiveTabsPage != null) {
2144 // if tab page is showing, hide it
2145 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002146 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002147 WebView subwindow = mTabControl.getCurrentSubWindow();
2148 if (subwindow != null) {
2149 if (subwindow.canGoBack()) {
2150 subwindow.goBack();
2151 } else {
2152 dismissSubWindow(mTabControl.getCurrentTab());
2153 }
2154 } else {
2155 goBackOnePageOrQuit();
2156 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002157 }
Grace Kloba5942df02009-09-18 11:48:29 -07002158 return true;
2159 }
2160 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002161 }
Grace Kloba5942df02009-09-18 11:48:29 -07002162 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002163 }
2164
Leon Scroggins68579392009-09-15 15:31:54 -04002165 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002166 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002167 resetTitleAndRevertLockIcon();
2168 WebView w = getTopWindow();
2169 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002170 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2171 // same logic here. But for subwindow case, should we call into the main
2172 // WebView's onPageFinished as we never call its onPageStarted and if
2173 // the page finishes itself, we don't call onPageFinished.
2174 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2175 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002176
2177 cancelStopToast();
2178 mStopToast = Toast
2179 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2180 mStopToast.show();
2181 }
2182
Grace Kloba22ac16e2009-10-07 18:00:23 -07002183 boolean didUserStopLoading() {
2184 return mDidStopLoad;
2185 }
2186
The Android Open Source Project0c908882009-03-03 19:32:16 -08002187 private void cancelStopToast() {
2188 if (mStopToast != null) {
2189 mStopToast.cancel();
2190 mStopToast = null;
2191 }
2192 }
2193
Grace Kloba22ac16e2009-10-07 18:00:23 -07002194 // called by a UI or non-UI thread to post the message
2195 public void postMessage(int what, int arg1, int arg2, Object obj,
2196 long delayMillis) {
2197 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2198 obj), delayMillis);
2199 }
2200
2201 // called by a UI or non-UI thread to remove the message
2202 void removeMessages(int what, Object object) {
2203 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002204 }
2205
2206 // public message ids
2207 public final static int LOAD_URL = 1001;
2208 public final static int STOP_LOAD = 1002;
2209
2210 // Message Ids
2211 private static final int FOCUS_NODE_HREF = 102;
2212 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002213 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002214
Grace Kloba22ac16e2009-10-07 18:00:23 -07002215 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002216
The Android Open Source Project0c908882009-03-03 19:32:16 -08002217 // Private handler for handling javascript and saving passwords
2218 private Handler mHandler = new Handler() {
2219
2220 public void handleMessage(Message msg) {
2221 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002222 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002223 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002224 String url = (String) msg.getData().get("url");
2225 if (url == null || url.length() == 0) {
2226 break;
2227 }
2228 HashMap focusNodeMap = (HashMap) msg.obj;
2229 WebView view = (WebView) focusNodeMap.get("webview");
2230 // Only apply the action if the top window did not change.
2231 if (getTopWindow() != view) {
2232 break;
2233 }
2234 switch (msg.arg1) {
2235 case R.id.open_context_menu_id:
2236 case R.id.view_image_context_menu_id:
2237 loadURL(getTopWindow(), url);
2238 break;
2239 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002240 final Tab parent = mTabControl.getCurrentTab();
2241 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002242 if (newTab != parent) {
2243 parent.addChildTab(newTab);
2244 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002245 break;
2246 case R.id.bookmark_context_menu_id:
2247 Intent intent = new Intent(BrowserActivity.this,
2248 AddBookmarkPage.class);
2249 intent.putExtra("url", url);
2250 startActivity(intent);
2251 break;
2252 case R.id.share_link_context_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01002253 Browser.sendString(BrowserActivity.this, url,
2254 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002255 break;
2256 case R.id.copy_link_context_menu_id:
2257 copy(url);
2258 break;
2259 case R.id.save_link_context_menu_id:
2260 case R.id.download_context_menu_id:
2261 onDownloadStartNoStream(url, null, null, null, -1);
2262 break;
2263 }
2264 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002265 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002266
2267 case LOAD_URL:
2268 loadURL(getTopWindow(), (String) msg.obj);
2269 break;
2270
2271 case STOP_LOAD:
2272 stopLoading();
2273 break;
2274
2275 case CANCEL_CREDS_REQUEST:
2276 resumeAfterCredentials();
2277 break;
2278
The Android Open Source Project0c908882009-03-03 19:32:16 -08002279 case RELEASE_WAKELOCK:
2280 if (mWakeLock.isHeld()) {
2281 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002282 // if we reach here, Browser should be still in the
2283 // background loading after WAKELOCK_TIMEOUT (5-min).
2284 // To avoid burning the battery, stop loading.
2285 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002286 }
2287 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002288
2289 case UPDATE_BOOKMARK_THUMBNAIL:
2290 WebView view = (WebView) msg.obj;
2291 if (view != null) {
2292 updateScreenshot(view);
2293 }
2294 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002295 }
2296 }
2297 };
2298
Leon Scroggins89c6d362009-07-15 16:54:37 -04002299 private void updateScreenshot(WebView view) {
2300 // If this is a bookmarked site, add a screenshot to the database.
2301 // FIXME: When should we update? Every time?
2302 // FIXME: Would like to make sure there is actually something to
2303 // draw, but the API for that (WebViewCore.pictureReady()) is not
2304 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002305
Patrick Scott3918d442009-08-04 13:22:29 -04002306 ContentResolver cr = getContentResolver();
2307 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002308 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002309 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002310 boolean succeed = c.moveToFirst();
2311 ContentValues values = null;
2312 while (succeed) {
2313 if (values == null) {
2314 final ByteArrayOutputStream os
2315 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002316 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002317 if (bm == null) {
2318 c.close();
2319 return;
2320 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002321 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2322 values = new ContentValues();
2323 values.put(Browser.BookmarkColumns.THUMBNAIL,
2324 os.toByteArray());
2325 }
2326 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2327 c.getInt(0)), values, null, null);
2328 succeed = c.moveToNext();
2329 }
2330 c.close();
2331 }
2332 }
2333
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002334 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002335 * Values for the size of the thumbnail created when taking a screenshot.
2336 * Lazily initialized. Instead of using these directly, use
2337 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002338 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002339 private static int THUMBNAIL_WIDTH = 0;
2340 private static int THUMBNAIL_HEIGHT = 0;
2341
2342 /**
2343 * Return the desired width for thumbnail screenshots, which are stored in
2344 * the database, and used on the bookmarks screen.
2345 * @param context Context for finding out the density of the screen.
2346 * @return int desired width for thumbnail screenshot.
2347 */
2348 /* package */ static int getDesiredThumbnailWidth(Context context) {
2349 if (THUMBNAIL_WIDTH == 0) {
2350 float density = context.getResources().getDisplayMetrics().density;
2351 THUMBNAIL_WIDTH = (int) (90 * density);
2352 THUMBNAIL_HEIGHT = (int) (80 * density);
2353 }
2354 return THUMBNAIL_WIDTH;
2355 }
2356
2357 /**
2358 * Return the desired height for thumbnail screenshots, which are stored in
2359 * the database, and used on the bookmarks screen.
2360 * @param context Context for finding out the density of the screen.
2361 * @return int desired height for thumbnail screenshot.
2362 */
2363 /* package */ static int getDesiredThumbnailHeight(Context context) {
2364 // To ensure that they are both initialized.
2365 getDesiredThumbnailWidth(context);
2366 return THUMBNAIL_HEIGHT;
2367 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002368
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002369 private Bitmap createScreenshot(WebView view) {
2370 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002371 if (thumbnail == null) {
2372 return null;
2373 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002374 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2375 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002376 Canvas canvas = new Canvas(bm);
2377 // May need to tweak these values to determine what is the
2378 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002379 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002380 int thumbnailHeight = thumbnail.getHeight();
2381 float scaleFactorX = 1.0f;
2382 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002383 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002384 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002385 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002386 } else {
2387 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002388 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002389
2390 if (view.getWidth() > view.getHeight() &&
2391 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2392 // If the device is in landscape and the page is shorter
2393 // than the height of the view, stretch the thumbnail to fill the
2394 // space.
2395 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2396 (float)thumbnailHeight;
2397 } else {
2398 // In the portrait case, this looks nice.
2399 scaleFactorY = scaleFactorX;
2400 }
2401
2402 canvas.scale(scaleFactorX, scaleFactorY);
2403
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002404 thumbnail.draw(canvas);
2405 return bm;
2406 }
2407
The Android Open Source Project0c908882009-03-03 19:32:16 -08002408 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002409 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002410 //-------------------------------------------------------------------------
2411
2412 // Use in overrideUrlLoading
2413 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2414 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2415 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2416 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2417
Grace Kloba22ac16e2009-10-07 18:00:23 -07002418 void onPageStarted(WebView view, String url, Bitmap favicon) {
2419 // when BrowserActivity just starts, onPageStarted may be called before
2420 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2421 // to start the timer. As we won't switch tabs while an activity is in
2422 // pause state, we can ensure calling resume and pause in pair.
2423 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002424
Grace Kloba22ac16e2009-10-07 18:00:23 -07002425 resetLockIcon(url);
2426 setUrlTitle(url, null);
2427 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002428 // Keep this initial progress in sync with initialProgressValue (* 100)
2429 // in ProgressTracker.cpp
2430 // Show some progress so that the user knows the page is beginning to
2431 // load
2432 onProgressChanged(view, 10);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002433 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002434 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002435
Grace Kloba22ac16e2009-10-07 18:00:23 -07002436 if (mSettings.isTracing()) {
2437 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002438 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002439 WebAddress uri = new WebAddress(url);
2440 host = uri.mHost;
2441 } catch (android.net.ParseException ex) {
2442 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002443 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002444 host = host.replace('.', '_');
2445 host += ".trace";
2446 mInTrace = true;
2447 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2448 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002449
Grace Kloba22ac16e2009-10-07 18:00:23 -07002450 // Performance probe
2451 if (false) {
2452 mStart = SystemClock.uptimeMillis();
2453 mProcessStart = Process.getElapsedCpuTime();
2454 long[] sysCpu = new long[7];
2455 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2456 sysCpu, null)) {
2457 mUserStart = sysCpu[0] + sysCpu[1];
2458 mSystemStart = sysCpu[2];
2459 mIdleStart = sysCpu[3];
2460 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2461 }
2462 mUiStart = SystemClock.currentThreadTimeMillis();
2463 }
2464 }
2465
2466 void onPageFinished(WebView view, String url) {
2467 // Reset the title and icon in case we stopped a provisional load.
2468 resetTitleAndIcon(view);
2469 // Update the lock icon image only once we are done loading
2470 updateLockIconToLatest();
2471 // pause the WebView timer and release the wake lock if it is finished
2472 // while BrowserActivity is in pause state.
2473 if (mActivityInPause && pauseWebViewTimers()) {
2474 if (mWakeLock.isHeld()) {
2475 mHandler.removeMessages(RELEASE_WAKELOCK);
2476 mWakeLock.release();
2477 }
2478 }
2479
2480 // Performance probe
2481 if (false) {
2482 long[] sysCpu = new long[7];
2483 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2484 sysCpu, null)) {
2485 String uiInfo = "UI thread used "
2486 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2487 + " ms";
2488 if (LOGD_ENABLED) {
2489 Log.d(LOGTAG, uiInfo);
2490 }
2491 //The string that gets written to the log
2492 String performanceString = "It took total "
2493 + (SystemClock.uptimeMillis() - mStart)
2494 + " ms clock time to load the page."
2495 + "\nbrowser process used "
2496 + (Process.getElapsedCpuTime() - mProcessStart)
2497 + " ms, user processes used "
2498 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2499 + " ms, kernel used "
2500 + (sysCpu[2] - mSystemStart) * 10
2501 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2502 + " ms and irq took "
2503 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2504 * 10 + " ms, " + uiInfo;
2505 if (LOGD_ENABLED) {
2506 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2507 }
2508 if (url != null) {
2509 // strip the url to maintain consistency
2510 String newUrl = new String(url);
2511 if (newUrl.startsWith("http://www.")) {
2512 newUrl = newUrl.substring(11);
2513 } else if (newUrl.startsWith("http://")) {
2514 newUrl = newUrl.substring(7);
2515 } else if (newUrl.startsWith("https://www.")) {
2516 newUrl = newUrl.substring(12);
2517 } else if (newUrl.startsWith("https://")) {
2518 newUrl = newUrl.substring(8);
2519 }
2520 if (LOGD_ENABLED) {
2521 Log.d(LOGTAG, newUrl + " loaded");
2522 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002523 }
2524 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002525 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002526
Grace Kloba22ac16e2009-10-07 18:00:23 -07002527 if (mInTrace) {
2528 mInTrace = false;
2529 Debug.stopMethodTracing();
2530 }
2531 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002532
Grace Kloba22ac16e2009-10-07 18:00:23 -07002533 boolean shouldOverrideUrlLoading(WebView view, String url) {
2534 if (url.startsWith(SCHEME_WTAI)) {
2535 // wtai://wp/mc;number
2536 // number=string(phone-number)
2537 if (url.startsWith(SCHEME_WTAI_MC)) {
2538 Intent intent = new Intent(Intent.ACTION_VIEW,
2539 Uri.parse(WebView.SCHEME_TEL +
2540 url.substring(SCHEME_WTAI_MC.length())));
2541 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002542 return true;
2543 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002544 // wtai://wp/sd;dtmf
2545 // dtmf=string(dialstring)
2546 if (url.startsWith(SCHEME_WTAI_SD)) {
2547 // TODO: only send when there is active voice connection
2548 return false;
2549 }
2550 // wtai://wp/ap;number;name
2551 // number=string(phone-number)
2552 // name=string
2553 if (url.startsWith(SCHEME_WTAI_AP)) {
2554 // TODO
2555 return false;
2556 }
2557 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002558
Grace Kloba22ac16e2009-10-07 18:00:23 -07002559 // The "about:" schemes are internal to the browser; don't want these to
2560 // be dispatched to other apps.
2561 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002562 return false;
2563 }
2564
Grace Kloba22ac16e2009-10-07 18:00:23 -07002565 Intent intent;
2566 // perform generic parsing of the URI to turn it into an Intent.
2567 try {
2568 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2569 } catch (URISyntaxException ex) {
2570 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2571 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002572 }
2573
Grace Kloba22ac16e2009-10-07 18:00:23 -07002574 // check whether the intent can be resolved. If not, we will see
2575 // whether we can download it from the Market.
2576 if (getPackageManager().resolveActivity(intent, 0) == null) {
2577 String packagename = intent.getPackage();
2578 if (packagename != null) {
2579 intent = new Intent(Intent.ACTION_VIEW, Uri
2580 .parse("market://search?q=pname:" + packagename));
2581 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2582 startActivity(intent);
2583 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002584 } else {
2585 return false;
2586 }
2587 }
2588
Grace Kloba22ac16e2009-10-07 18:00:23 -07002589 // sanitize the Intent, ensuring web pages can not bypass browser
2590 // security (only access to BROWSABLE activities).
2591 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2592 intent.setComponent(null);
2593 try {
2594 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002595 return true;
2596 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002597 } catch (ActivityNotFoundException ex) {
2598 // ignore the error. If no application can handle the URL,
2599 // eg about:blank, assume the browser can handle it.
2600 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002601
Grace Kloba22ac16e2009-10-07 18:00:23 -07002602 if (mMenuIsDown) {
2603 openTab(url);
2604 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002605 return true;
2606 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002607 return false;
2608 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002609
Grace Kloba22ac16e2009-10-07 18:00:23 -07002610 // -------------------------------------------------------------------------
2611 // Helper function for WebChromeClient
2612 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002613
Grace Kloba22ac16e2009-10-07 18:00:23 -07002614 void onProgressChanged(WebView view, int newProgress) {
2615 mTitleBar.setProgress(newProgress);
2616 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002617
Grace Kloba22ac16e2009-10-07 18:00:23 -07002618 if (newProgress == 100) {
2619 // onProgressChanged() may continue to be called after the main
2620 // frame has finished loading, as any remaining sub frames continue
2621 // to load. We'll only get called once though with newProgress as
2622 // 100 when everything is loaded. (onPageFinished is called once
2623 // when the main frame completes loading regardless of the state of
2624 // any sub frames so calls to onProgressChanges may continue after
2625 // onPageFinished has executed)
2626 if (mInLoad) {
2627 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002628 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002629 // If the options menu is open, leave the title bar
2630 if (!mOptionsMenuOpen || !mIconView) {
2631 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002632 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002633 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002634 } else if (!mInLoad) {
2635 // onPageFinished may have already been called but a subframe is
2636 // still loading and updating the progress. Reset mInLoad and update
2637 // the menu items.
2638 mInLoad = true;
2639 updateInLoadMenuItems();
2640 if (!mOptionsMenuOpen || mIconView) {
2641 // This page has begun to load, so show the title bar
2642 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002643 }
2644 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002645 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002646
Grace Kloba22ac16e2009-10-07 18:00:23 -07002647 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2648 if (mCustomView != null)
2649 return;
2650
2651 // Add the custom view to its container.
2652 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2653 mCustomView = view;
2654 mCustomViewCallback = callback;
2655 // Save the menu state and set it to empty while the custom
2656 // view is showing.
2657 mOldMenuState = mMenuState;
2658 mMenuState = EMPTY_MENU;
2659 // Hide the content view.
2660 mContentView.setVisibility(View.GONE);
2661 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002662 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002663 mCustomViewContainer.setVisibility(View.VISIBLE);
2664 mCustomViewContainer.bringToFront();
2665 }
2666
2667 void onHideCustomView() {
2668 if (mCustomView == null)
2669 return;
2670
2671 // Hide the custom view.
2672 mCustomView.setVisibility(View.GONE);
2673 // Remove the custom view from its container.
2674 mCustomViewContainer.removeView(mCustomView);
2675 mCustomView = null;
2676 // Reset the old menu state.
2677 mMenuState = mOldMenuState;
2678 mOldMenuState = EMPTY_MENU;
2679 mCustomViewContainer.setVisibility(View.GONE);
2680 mCustomViewCallback.onCustomViewHidden();
2681 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002682 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002683 mContentView.setVisibility(View.VISIBLE);
2684 }
2685
2686 Bitmap getDefaultVideoPoster() {
2687 if (mDefaultVideoPoster == null) {
2688 mDefaultVideoPoster = BitmapFactory.decodeResource(
2689 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002690 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002691 return mDefaultVideoPoster;
2692 }
Patrick Scott3918d442009-08-04 13:22:29 -04002693
Grace Kloba22ac16e2009-10-07 18:00:23 -07002694 View getVideoLoadingProgressView() {
2695 if (mVideoProgressView == null) {
2696 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2697 mVideoProgressView = inflater.inflate(
2698 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002699 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002700 return mVideoProgressView;
2701 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002702
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002703 /*
2704 * The Object used to inform the WebView of the file to upload.
2705 */
2706 private ValueCallback<Uri> mUploadMessage;
2707
Grace Kloba22ac16e2009-10-07 18:00:23 -07002708 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2709 if (mUploadMessage != null) return;
2710 mUploadMessage = uploadMsg;
2711 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2712 i.addCategory(Intent.CATEGORY_OPENABLE);
2713 i.setType("*/*");
2714 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2715 getString(R.string.choose_upload)), FILE_SELECTED);
2716 }
2717
2718 // -------------------------------------------------------------------------
2719 // Implement functions for DownloadListener
2720 // -------------------------------------------------------------------------
2721
The Android Open Source Project0c908882009-03-03 19:32:16 -08002722 /**
2723 * Notify the host application a download should be done, or that
2724 * the data should be streamed if a streaming viewer is available.
2725 * @param url The full url to the content that should be downloaded
2726 * @param contentDisposition Content-disposition http header, if
2727 * present.
2728 * @param mimetype The mimetype of the content reported by the server
2729 * @param contentLength The file size reported by the server
2730 */
2731 public void onDownloadStart(String url, String userAgent,
2732 String contentDisposition, String mimetype, long contentLength) {
2733 // if we're dealing wih A/V content that's not explicitly marked
2734 // for download, check if it's streamable.
2735 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002736 || !contentDisposition.regionMatches(
2737 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002738 // query the package manager to see if there's a registered handler
2739 // that matches.
2740 Intent intent = new Intent(Intent.ACTION_VIEW);
2741 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002742 ResolveInfo info = getPackageManager().resolveActivity(intent,
2743 PackageManager.MATCH_DEFAULT_ONLY);
2744 if (info != null) {
2745 ComponentName myName = getComponentName();
2746 // If we resolved to ourselves, we don't want to attempt to
2747 // load the url only to try and download it again.
2748 if (!myName.getPackageName().equals(
2749 info.activityInfo.packageName)
2750 || !myName.getClassName().equals(
2751 info.activityInfo.name)) {
2752 // someone (other than us) knows how to handle this mime
2753 // type with this scheme, don't download.
2754 try {
2755 startActivity(intent);
2756 return;
2757 } catch (ActivityNotFoundException ex) {
2758 if (LOGD_ENABLED) {
2759 Log.d(LOGTAG, "activity not found for " + mimetype
2760 + " over " + Uri.parse(url).getScheme(),
2761 ex);
2762 }
2763 // Best behavior is to fall back to a download in this
2764 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002765 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002766 }
2767 }
2768 }
2769 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2770 }
2771
2772 /**
2773 * Notify the host application a download should be done, even if there
2774 * is a streaming viewer available for thise type.
2775 * @param url The full url to the content that should be downloaded
2776 * @param contentDisposition Content-disposition http header, if
2777 * present.
2778 * @param mimetype The mimetype of the content reported by the server
2779 * @param contentLength The file size reported by the server
2780 */
2781 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2782 String contentDisposition, String mimetype, long contentLength) {
2783
2784 String filename = URLUtil.guessFileName(url,
2785 contentDisposition, mimetype);
2786
2787 // Check to see if we have an SDCard
2788 String status = Environment.getExternalStorageState();
2789 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2790 int title;
2791 String msg;
2792
2793 // Check to see if the SDCard is busy, same as the music app
2794 if (status.equals(Environment.MEDIA_SHARED)) {
2795 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2796 title = R.string.download_sdcard_busy_dlg_title;
2797 } else {
2798 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2799 title = R.string.download_no_sdcard_dlg_title;
2800 }
2801
2802 new AlertDialog.Builder(this)
2803 .setTitle(title)
2804 .setIcon(android.R.drawable.ic_dialog_alert)
2805 .setMessage(msg)
2806 .setPositiveButton(R.string.ok, null)
2807 .show();
2808 return;
2809 }
2810
2811 // java.net.URI is a lot stricter than KURL so we have to undo
2812 // KURL's percent-encoding and redo the encoding using java.net.URI.
2813 URI uri = null;
2814 try {
2815 // Undo the percent-encoding that KURL may have done.
2816 String newUrl = new String(URLUtil.decode(url.getBytes()));
2817 // Parse the url into pieces
2818 WebAddress w = new WebAddress(newUrl);
2819 String frag = null;
2820 String query = null;
2821 String path = w.mPath;
2822 // Break the path into path, query, and fragment
2823 if (path.length() > 0) {
2824 // Strip the fragment
2825 int idx = path.lastIndexOf('#');
2826 if (idx != -1) {
2827 frag = path.substring(idx + 1);
2828 path = path.substring(0, idx);
2829 }
2830 idx = path.lastIndexOf('?');
2831 if (idx != -1) {
2832 query = path.substring(idx + 1);
2833 path = path.substring(0, idx);
2834 }
2835 }
2836 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2837 query, frag);
2838 } catch (Exception e) {
2839 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2840 return;
2841 }
2842
2843 // XXX: Have to use the old url since the cookies were stored using the
2844 // old percent-encoded url.
2845 String cookies = CookieManager.getInstance().getCookie(url);
2846
2847 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002848 values.put(Downloads.COLUMN_URI, uri.toString());
2849 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
2850 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
2851 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002852 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002853 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002854 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002855 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2856 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
2857 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
2858 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002859 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002860 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002861 }
2862 if (mimetype == null) {
2863 // We must have long pressed on a link or image to download it. We
2864 // are not sure of the mimetype in this case, so do a head request
2865 new FetchUrlMimeType(this).execute(values);
2866 } else {
2867 final Uri contentUri =
2868 getContentResolver().insert(Downloads.CONTENT_URI, values);
2869 viewDownloads(contentUri);
2870 }
2871
2872 }
2873
Grace Kloba22ac16e2009-10-07 18:00:23 -07002874 // -------------------------------------------------------------------------
2875
The Android Open Source Project0c908882009-03-03 19:32:16 -08002876 /**
2877 * Resets the lock icon. This method is called when we start a new load and
2878 * know the url to be loaded.
2879 */
2880 private void resetLockIcon(String url) {
2881 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002882 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002883 updateLockIconImage(LOCK_ICON_UNSECURE);
2884 }
2885
The Android Open Source Project0c908882009-03-03 19:32:16 -08002886 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002887 * Update the lock icon to correspond to our latest state.
2888 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002889 private void updateLockIconToLatest() {
2890 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002891 }
2892
2893 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002894 * Updates the lock-icon image in the title-bar.
2895 */
2896 private void updateLockIconImage(int lockIconType) {
2897 Drawable d = null;
2898 if (lockIconType == LOCK_ICON_SECURE) {
2899 d = mSecLockIcon;
2900 } else if (lockIconType == LOCK_ICON_MIXED) {
2901 d = mMixLockIcon;
2902 }
Leon Scroggins68579392009-09-15 15:31:54 -04002903 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002904 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002905 }
2906
2907 /**
2908 * Displays a page-info dialog.
2909 * @param tab The tab to show info about
2910 * @param fromShowSSLCertificateOnError The flag that indicates whether
2911 * this dialog was opened from the SSL-certificate-on-error dialog or
2912 * not. This is important, since we need to know whether to return to
2913 * the parent dialog or simply dismiss.
2914 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002915 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002916 final boolean fromShowSSLCertificateOnError) {
2917 final LayoutInflater factory = LayoutInflater
2918 .from(this);
2919
2920 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2921
2922 final WebView view = tab.getWebView();
2923
2924 String url = null;
2925 String title = null;
2926
2927 if (view == null) {
2928 url = tab.getUrl();
2929 title = tab.getTitle();
2930 } else if (view == mTabControl.getCurrentWebView()) {
2931 // Use the cached title and url if this is the current WebView
2932 url = mUrl;
2933 title = mTitle;
2934 } else {
2935 url = view.getUrl();
2936 title = view.getTitle();
2937 }
2938
2939 if (url == null) {
2940 url = "";
2941 }
2942 if (title == null) {
2943 title = "";
2944 }
2945
2946 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
2947 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
2948
2949 mPageInfoView = tab;
2950 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
2951
2952 AlertDialog.Builder alertDialogBuilder =
2953 new AlertDialog.Builder(this)
2954 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
2955 .setView(pageInfoView)
2956 .setPositiveButton(
2957 R.string.ok,
2958 new DialogInterface.OnClickListener() {
2959 public void onClick(DialogInterface dialog,
2960 int whichButton) {
2961 mPageInfoDialog = null;
2962 mPageInfoView = null;
2963 mPageInfoFromShowSSLCertificateOnError = null;
2964
2965 // if we came here from the SSL error dialog
2966 if (fromShowSSLCertificateOnError) {
2967 // go back to the SSL error dialog
2968 showSSLCertificateOnError(
2969 mSSLCertificateOnErrorView,
2970 mSSLCertificateOnErrorHandler,
2971 mSSLCertificateOnErrorError);
2972 }
2973 }
2974 })
2975 .setOnCancelListener(
2976 new DialogInterface.OnCancelListener() {
2977 public void onCancel(DialogInterface dialog) {
2978 mPageInfoDialog = null;
2979 mPageInfoView = null;
2980 mPageInfoFromShowSSLCertificateOnError = null;
2981
2982 // if we came here from the SSL error dialog
2983 if (fromShowSSLCertificateOnError) {
2984 // go back to the SSL error dialog
2985 showSSLCertificateOnError(
2986 mSSLCertificateOnErrorView,
2987 mSSLCertificateOnErrorHandler,
2988 mSSLCertificateOnErrorError);
2989 }
2990 }
2991 });
2992
2993 // if we have a main top-level page SSL certificate set or a certificate
2994 // error
2995 if (fromShowSSLCertificateOnError ||
2996 (view != null && view.getCertificate() != null)) {
2997 // add a 'View Certificate' button
2998 alertDialogBuilder.setNeutralButton(
2999 R.string.view_certificate,
3000 new DialogInterface.OnClickListener() {
3001 public void onClick(DialogInterface dialog,
3002 int whichButton) {
3003 mPageInfoDialog = null;
3004 mPageInfoView = null;
3005 mPageInfoFromShowSSLCertificateOnError = null;
3006
3007 // if we came here from the SSL error dialog
3008 if (fromShowSSLCertificateOnError) {
3009 // go back to the SSL error dialog
3010 showSSLCertificateOnError(
3011 mSSLCertificateOnErrorView,
3012 mSSLCertificateOnErrorHandler,
3013 mSSLCertificateOnErrorError);
3014 } else {
3015 // otherwise, display the top-most certificate from
3016 // the chain
3017 if (view.getCertificate() != null) {
3018 showSSLCertificate(tab);
3019 }
3020 }
3021 }
3022 });
3023 }
3024
3025 mPageInfoDialog = alertDialogBuilder.show();
3026 }
3027
3028 /**
3029 * Displays the main top-level page SSL certificate dialog
3030 * (accessible from the Page-Info dialog).
3031 * @param tab The tab to show certificate for.
3032 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003033 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003034 final View certificateView =
3035 inflateCertificateView(tab.getWebView().getCertificate());
3036 if (certificateView == null) {
3037 return;
3038 }
3039
3040 LayoutInflater factory = LayoutInflater.from(this);
3041
3042 final LinearLayout placeholder =
3043 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3044
3045 LinearLayout ll = (LinearLayout) factory.inflate(
3046 R.layout.ssl_success, placeholder);
3047 ((TextView)ll.findViewById(R.id.success))
3048 .setText(R.string.ssl_certificate_is_valid);
3049
3050 mSSLCertificateView = tab;
3051 mSSLCertificateDialog =
3052 new AlertDialog.Builder(this)
3053 .setTitle(R.string.ssl_certificate).setIcon(
3054 R.drawable.ic_dialog_browser_certificate_secure)
3055 .setView(certificateView)
3056 .setPositiveButton(R.string.ok,
3057 new DialogInterface.OnClickListener() {
3058 public void onClick(DialogInterface dialog,
3059 int whichButton) {
3060 mSSLCertificateDialog = null;
3061 mSSLCertificateView = null;
3062
3063 showPageInfo(tab, false);
3064 }
3065 })
3066 .setOnCancelListener(
3067 new DialogInterface.OnCancelListener() {
3068 public void onCancel(DialogInterface dialog) {
3069 mSSLCertificateDialog = null;
3070 mSSLCertificateView = null;
3071
3072 showPageInfo(tab, false);
3073 }
3074 })
3075 .show();
3076 }
3077
3078 /**
3079 * Displays the SSL error certificate dialog.
3080 * @param view The target web-view.
3081 * @param handler The SSL error handler responsible for cancelling the
3082 * connection that resulted in an SSL error or proceeding per user request.
3083 * @param error The SSL error object.
3084 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003085 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003086 final WebView view, final SslErrorHandler handler, final SslError error) {
3087
3088 final View certificateView =
3089 inflateCertificateView(error.getCertificate());
3090 if (certificateView == null) {
3091 return;
3092 }
3093
3094 LayoutInflater factory = LayoutInflater.from(this);
3095
3096 final LinearLayout placeholder =
3097 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3098
3099 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3100 LinearLayout ll = (LinearLayout)factory
3101 .inflate(R.layout.ssl_warning, placeholder);
3102 ((TextView)ll.findViewById(R.id.warning))
3103 .setText(R.string.ssl_untrusted);
3104 }
3105
3106 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3107 LinearLayout ll = (LinearLayout)factory
3108 .inflate(R.layout.ssl_warning, placeholder);
3109 ((TextView)ll.findViewById(R.id.warning))
3110 .setText(R.string.ssl_mismatch);
3111 }
3112
3113 if (error.hasError(SslError.SSL_EXPIRED)) {
3114 LinearLayout ll = (LinearLayout)factory
3115 .inflate(R.layout.ssl_warning, placeholder);
3116 ((TextView)ll.findViewById(R.id.warning))
3117 .setText(R.string.ssl_expired);
3118 }
3119
3120 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3121 LinearLayout ll = (LinearLayout)factory
3122 .inflate(R.layout.ssl_warning, placeholder);
3123 ((TextView)ll.findViewById(R.id.warning))
3124 .setText(R.string.ssl_not_yet_valid);
3125 }
3126
3127 mSSLCertificateOnErrorHandler = handler;
3128 mSSLCertificateOnErrorView = view;
3129 mSSLCertificateOnErrorError = error;
3130 mSSLCertificateOnErrorDialog =
3131 new AlertDialog.Builder(this)
3132 .setTitle(R.string.ssl_certificate).setIcon(
3133 R.drawable.ic_dialog_browser_certificate_partially_secure)
3134 .setView(certificateView)
3135 .setPositiveButton(R.string.ok,
3136 new DialogInterface.OnClickListener() {
3137 public void onClick(DialogInterface dialog,
3138 int whichButton) {
3139 mSSLCertificateOnErrorDialog = null;
3140 mSSLCertificateOnErrorView = null;
3141 mSSLCertificateOnErrorHandler = null;
3142 mSSLCertificateOnErrorError = null;
3143
Grace Kloba22ac16e2009-10-07 18:00:23 -07003144 view.getWebViewClient().onReceivedSslError(
3145 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003146 }
3147 })
3148 .setNeutralButton(R.string.page_info_view,
3149 new DialogInterface.OnClickListener() {
3150 public void onClick(DialogInterface dialog,
3151 int whichButton) {
3152 mSSLCertificateOnErrorDialog = null;
3153
3154 // do not clear the dialog state: we will
3155 // need to show the dialog again once the
3156 // user is done exploring the page-info details
3157
3158 showPageInfo(mTabControl.getTabFromView(view),
3159 true);
3160 }
3161 })
3162 .setOnCancelListener(
3163 new DialogInterface.OnCancelListener() {
3164 public void onCancel(DialogInterface dialog) {
3165 mSSLCertificateOnErrorDialog = null;
3166 mSSLCertificateOnErrorView = null;
3167 mSSLCertificateOnErrorHandler = null;
3168 mSSLCertificateOnErrorError = null;
3169
Grace Kloba22ac16e2009-10-07 18:00:23 -07003170 view.getWebViewClient().onReceivedSslError(
3171 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003172 }
3173 })
3174 .show();
3175 }
3176
3177 /**
3178 * Inflates the SSL certificate view (helper method).
3179 * @param certificate The SSL certificate.
3180 * @return The resultant certificate view with issued-to, issued-by,
3181 * issued-on, expires-on, and possibly other fields set.
3182 * If the input certificate is null, returns null.
3183 */
3184 private View inflateCertificateView(SslCertificate certificate) {
3185 if (certificate == null) {
3186 return null;
3187 }
3188
3189 LayoutInflater factory = LayoutInflater.from(this);
3190
3191 View certificateView = factory.inflate(
3192 R.layout.ssl_certificate, null);
3193
3194 // issued to:
3195 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3196 if (issuedTo != null) {
3197 ((TextView) certificateView.findViewById(R.id.to_common))
3198 .setText(issuedTo.getCName());
3199 ((TextView) certificateView.findViewById(R.id.to_org))
3200 .setText(issuedTo.getOName());
3201 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3202 .setText(issuedTo.getUName());
3203 }
3204
3205 // issued by:
3206 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3207 if (issuedBy != null) {
3208 ((TextView) certificateView.findViewById(R.id.by_common))
3209 .setText(issuedBy.getCName());
3210 ((TextView) certificateView.findViewById(R.id.by_org))
3211 .setText(issuedBy.getOName());
3212 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3213 .setText(issuedBy.getUName());
3214 }
3215
3216 // issued on:
3217 String issuedOn = reformatCertificateDate(
3218 certificate.getValidNotBefore());
3219 ((TextView) certificateView.findViewById(R.id.issued_on))
3220 .setText(issuedOn);
3221
3222 // expires on:
3223 String expiresOn = reformatCertificateDate(
3224 certificate.getValidNotAfter());
3225 ((TextView) certificateView.findViewById(R.id.expires_on))
3226 .setText(expiresOn);
3227
3228 return certificateView;
3229 }
3230
3231 /**
3232 * Re-formats the certificate date (Date.toString()) string to
3233 * a properly localized date string.
3234 * @return Properly localized version of the certificate date string and
3235 * the original certificate date string if fails to localize.
3236 * If the original string is null, returns an empty string "".
3237 */
3238 private String reformatCertificateDate(String certificateDate) {
3239 String reformattedDate = null;
3240
3241 if (certificateDate != null) {
3242 Date date = null;
3243 try {
3244 date = java.text.DateFormat.getInstance().parse(certificateDate);
3245 } catch (ParseException e) {
3246 date = null;
3247 }
3248
3249 if (date != null) {
3250 reformattedDate =
3251 DateFormat.getDateFormat(this).format(date);
3252 }
3253 }
3254
3255 return reformattedDate != null ? reformattedDate :
3256 (certificateDate != null ? certificateDate : "");
3257 }
3258
3259 /**
3260 * Displays an http-authentication dialog.
3261 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003262 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003263 final String host, final String realm, final String title,
3264 final String name, final String password, int focusId) {
3265 LayoutInflater factory = LayoutInflater.from(this);
3266 final View v = factory
3267 .inflate(R.layout.http_authentication, null);
3268 if (name != null) {
3269 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3270 }
3271 if (password != null) {
3272 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3273 }
3274
3275 String titleText = title;
3276 if (titleText == null) {
3277 titleText = getText(R.string.sign_in_to).toString().replace(
3278 "%s1", host).replace("%s2", realm);
3279 }
3280
3281 mHttpAuthHandler = handler;
3282 AlertDialog dialog = new AlertDialog.Builder(this)
3283 .setTitle(titleText)
3284 .setIcon(android.R.drawable.ic_dialog_alert)
3285 .setView(v)
3286 .setPositiveButton(R.string.action,
3287 new DialogInterface.OnClickListener() {
3288 public void onClick(DialogInterface dialog,
3289 int whichButton) {
3290 String nm = ((EditText) v
3291 .findViewById(R.id.username_edit))
3292 .getText().toString();
3293 String pw = ((EditText) v
3294 .findViewById(R.id.password_edit))
3295 .getText().toString();
3296 BrowserActivity.this.setHttpAuthUsernamePassword
3297 (host, realm, nm, pw);
3298 handler.proceed(nm, pw);
3299 mHttpAuthenticationDialog = null;
3300 mHttpAuthHandler = null;
3301 }})
3302 .setNegativeButton(R.string.cancel,
3303 new DialogInterface.OnClickListener() {
3304 public void onClick(DialogInterface dialog,
3305 int whichButton) {
3306 handler.cancel();
3307 BrowserActivity.this.resetTitleAndRevertLockIcon();
3308 mHttpAuthenticationDialog = null;
3309 mHttpAuthHandler = null;
3310 }})
3311 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3312 public void onCancel(DialogInterface dialog) {
3313 handler.cancel();
3314 BrowserActivity.this.resetTitleAndRevertLockIcon();
3315 mHttpAuthenticationDialog = null;
3316 mHttpAuthHandler = null;
3317 }})
3318 .create();
3319 // Make the IME appear when the dialog is displayed if applicable.
3320 dialog.getWindow().setSoftInputMode(
3321 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3322 dialog.show();
3323 if (focusId != 0) {
3324 dialog.findViewById(focusId).requestFocus();
3325 } else {
3326 v.findViewById(R.id.username_edit).requestFocus();
3327 }
3328 mHttpAuthenticationDialog = dialog;
3329 }
3330
3331 public int getProgress() {
3332 WebView w = mTabControl.getCurrentWebView();
3333 if (w != null) {
3334 return w.getProgress();
3335 } else {
3336 return 100;
3337 }
3338 }
3339
3340 /**
3341 * Set HTTP authentication password.
3342 *
3343 * @param host The host for the password
3344 * @param realm The realm for the password
3345 * @param username The username for the password. If it is null, it means
3346 * password can't be saved.
3347 * @param password The password
3348 */
3349 public void setHttpAuthUsernamePassword(String host, String realm,
3350 String username,
3351 String password) {
3352 WebView w = mTabControl.getCurrentWebView();
3353 if (w != null) {
3354 w.setHttpAuthUsernamePassword(host, realm, username, password);
3355 }
3356 }
3357
3358 /**
3359 * connectivity manager says net has come or gone... inform the user
3360 * @param up true if net has come up, false if net has gone down
3361 */
3362 public void onNetworkToggle(boolean up) {
3363 if (up == mIsNetworkUp) {
3364 return;
3365 } else if (up) {
3366 mIsNetworkUp = true;
3367 if (mAlertDialog != null) {
3368 mAlertDialog.cancel();
3369 mAlertDialog = null;
3370 }
3371 } else {
3372 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003373 if (mInLoad) {
3374 createAndShowNetworkDialog();
3375 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003376 }
3377 WebView w = mTabControl.getCurrentWebView();
3378 if (w != null) {
3379 w.setNetworkAvailable(up);
3380 }
3381 }
3382
Grace Kloba22ac16e2009-10-07 18:00:23 -07003383 boolean isNetworkUp() {
3384 return mIsNetworkUp;
3385 }
3386
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003387 // This method shows the network dialog alerting the user that the net is
3388 // down. It will only show the dialog if mAlertDialog is null.
3389 private void createAndShowNetworkDialog() {
3390 if (mAlertDialog == null) {
3391 mAlertDialog = new AlertDialog.Builder(this)
3392 .setTitle(R.string.loadSuspendedTitle)
3393 .setMessage(R.string.loadSuspended)
3394 .setPositiveButton(R.string.ok, null)
3395 .show();
3396 }
3397 }
3398
The Android Open Source Project0c908882009-03-03 19:32:16 -08003399 @Override
3400 protected void onActivityResult(int requestCode, int resultCode,
3401 Intent intent) {
3402 switch (requestCode) {
3403 case COMBO_PAGE:
3404 if (resultCode == RESULT_OK && intent != null) {
3405 String data = intent.getAction();
3406 Bundle extras = intent.getExtras();
3407 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003408 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003409 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003410 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003411 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003412 dismissSubWindow(currentTab);
3413 if (data != null && data.length() != 0) {
3414 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003415 }
3416 }
3417 }
3418 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003419 // Choose a file from the file picker.
3420 case FILE_SELECTED:
3421 if (null == mUploadMessage) break;
3422 Uri result = intent == null || resultCode != RESULT_OK ? null
3423 : intent.getData();
3424 mUploadMessage.onReceiveValue(result);
3425 mUploadMessage = null;
3426 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003427 default:
3428 break;
3429 }
Leon Scroggins30444232009-09-04 18:36:20 -04003430 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003431 }
3432
3433 /*
3434 * This method is called as a result of the user selecting the options
3435 * menu to see the download window, or when a download changes state. It
3436 * shows the download window ontop of the current window.
3437 */
3438 /* package */ void viewDownloads(Uri downloadRecord) {
3439 Intent intent = new Intent(this,
3440 BrowserDownloadPage.class);
3441 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003442 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003443
3444 }
3445
Leon Scroggins160a7e72009-08-14 18:28:01 -04003446 /**
3447 * Open the Go page.
3448 * @param startWithHistory If true, open starting on the history tab.
3449 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003450 */
Leon Scroggins30444232009-09-04 18:36:20 -04003451 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003452 WebView current = mTabControl.getCurrentWebView();
3453 if (current == null) {
3454 return;
3455 }
3456 Intent intent = new Intent(this,
3457 CombinedBookmarkHistoryActivity.class);
3458 String title = current.getTitle();
3459 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003460 Bitmap thumbnail = createScreenshot(current);
3461
The Android Open Source Project0c908882009-03-03 19:32:16 -08003462 // Just in case the user opens bookmarks before a page finishes loading
3463 // so the current history item, and therefore the page, is null.
3464 if (null == url) {
3465 url = mLastEnteredUrl;
3466 // This can happen.
3467 if (null == url) {
3468 url = mSettings.getHomePage();
3469 }
3470 }
3471 // In case the web page has not yet received its associated title.
3472 if (title == null) {
3473 title = url;
3474 }
3475 intent.putExtra("title", title);
3476 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003477 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003478 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003479 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003480 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003481 if (startWithHistory) {
3482 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3483 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3484 }
3485 startActivityForResult(intent, COMBO_PAGE);
3486 }
3487
3488 // Called when loading from context menu or LOAD_URL message
3489 private void loadURL(WebView view, String url) {
3490 // In case the user enters nothing.
3491 if (url != null && url.length() != 0 && view != null) {
3492 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003493 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003494 view.loadUrl(url);
3495 }
3496 }
3497 }
3498
The Android Open Source Project0c908882009-03-03 19:32:16 -08003499 private String smartUrlFilter(Uri inUri) {
3500 if (inUri != null) {
3501 return smartUrlFilter(inUri.toString());
3502 }
3503 return null;
3504 }
3505
Feng Qianb34f87a2009-03-24 21:27:26 -07003506 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003507 "(?i)" + // switch on case insensitive matching
3508 "(" + // begin group for schema
3509 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003510 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003511 ")" +
3512 "(.*)" );
3513
3514 /**
3515 * Attempts to determine whether user input is a URL or search
3516 * terms. Anything with a space is passed to search.
3517 *
3518 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3519 * "Http://" converts to "http://"
3520 *
3521 * @return Original or modified URL
3522 *
3523 */
3524 String smartUrlFilter(String url) {
3525
3526 String inUrl = url.trim();
3527 boolean hasSpace = inUrl.indexOf(' ') != -1;
3528
3529 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3530 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003531 // force scheme to lowercase
3532 String scheme = matcher.group(1);
3533 String lcScheme = scheme.toLowerCase();
3534 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003535 inUrl = lcScheme + matcher.group(2);
3536 }
3537 if (hasSpace) {
3538 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003539 }
3540 return inUrl;
3541 }
3542 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003543 // FIXME: Is this the correct place to add to searches?
3544 // what if someone else calls this function?
3545 int shortcut = parseUrlShortcut(inUrl);
3546 if (shortcut != SHORTCUT_INVALID) {
3547 Browser.addSearchUrl(mResolver, inUrl);
3548 String query = inUrl.substring(2);
3549 switch (shortcut) {
3550 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003551 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003552 case SHORTCUT_WIKIPEDIA_SEARCH:
3553 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3554 case SHORTCUT_DICTIONARY_SEARCH:
3555 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3556 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003557 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003558 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003559 }
3560 }
3561 } else {
3562 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
3563 return URLUtil.guessUrl(inUrl);
3564 }
3565 }
3566
3567 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003568 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003569 }
3570
Ben Murdochbff2d602009-07-01 20:19:05 +01003571 /* package */ void setShouldShowErrorConsole(boolean flag) {
3572 if (flag == mShouldShowErrorConsole) {
3573 // Nothing to do.
3574 return;
3575 }
3576
3577 mShouldShowErrorConsole = flag;
3578
Grace Kloba22ac16e2009-10-07 18:00:23 -07003579 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3580 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003581
3582 if (flag) {
3583 // Setting the show state of the console will cause it's the layout to be inflated.
3584 if (errorConsole.numberOfErrors() > 0) {
3585 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3586 } else {
3587 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3588 }
3589
3590 // Now we can add it to the main view.
3591 mErrorConsoleContainer.addView(errorConsole,
3592 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
3593 ViewGroup.LayoutParams.WRAP_CONTENT));
3594 } else {
3595 mErrorConsoleContainer.removeView(errorConsole);
3596 }
3597
3598 }
3599
Grace Kloba22ac16e2009-10-07 18:00:23 -07003600 boolean shouldShowErrorConsole() {
3601 return mShouldShowErrorConsole;
3602 }
3603
Andrei Popescu163ab742009-10-20 17:58:23 +01003604 private void setStatusBarVisibility(boolean visible) {
3605 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3606 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3607 }
3608
Grace Klobaeb6eef42009-09-15 17:56:32 -07003609 final static int LOCK_ICON_UNSECURE = 0;
3610 final static int LOCK_ICON_SECURE = 1;
3611 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003612
The Android Open Source Project0c908882009-03-03 19:32:16 -08003613 private BrowserSettings mSettings;
3614 private TabControl mTabControl;
3615 private ContentResolver mResolver;
3616 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003617 private View mCustomView;
3618 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003619 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003620
3621 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3622 // view, we should rewrite this.
3623 private int mCurrentMenuState = 0;
3624 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003625 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003626 private static final int EMPTY_MENU = -1;
3627 private Menu mMenu;
3628
3629 private FindDialog mFindDialog;
3630 // Used to prevent chording to result in firing two shortcuts immediately
3631 // one after another. Fixes bug 1211714.
3632 boolean mCanChord;
3633
3634 private boolean mInLoad;
3635 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003636 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003637
The Android Open Source Project0c908882009-03-03 19:32:16 -08003638 private boolean mActivityInPause = true;
3639
3640 private boolean mMenuIsDown;
3641
The Android Open Source Project0c908882009-03-03 19:32:16 -08003642 private static boolean mInTrace;
3643
3644 // Performance probe
3645 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3646 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3647 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3648 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3649 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3650 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3651 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3652 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3653 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3654 };
3655
3656 private long mStart;
3657 private long mProcessStart;
3658 private long mUserStart;
3659 private long mSystemStart;
3660 private long mIdleStart;
3661 private long mIrqStart;
3662
3663 private long mUiStart;
3664
3665 private Drawable mMixLockIcon;
3666 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003667
3668 /* hold a ref so we can auto-cancel if necessary */
3669 private AlertDialog mAlertDialog;
3670
3671 // Wait for credentials before loading google.com
3672 private ProgressDialog mCredsDlg;
3673
3674 // The up-to-date URL and title (these can be different from those stored
3675 // in WebView, since it takes some time for the information in WebView to
3676 // get updated)
3677 private String mUrl;
3678 private String mTitle;
3679
3680 // As PageInfo has different style for landscape / portrait, we have
3681 // to re-open it when configuration changed
3682 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003683 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003684 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3685 // dialog, we should not just dismiss it, but should get back to the
3686 // SSL-certificate-on-error dialog. This flag is used to store this state
3687 private Boolean mPageInfoFromShowSSLCertificateOnError;
3688
3689 // as SSLCertificateOnError has different style for landscape / portrait,
3690 // we have to re-open it when configuration changed
3691 private AlertDialog mSSLCertificateOnErrorDialog;
3692 private WebView mSSLCertificateOnErrorView;
3693 private SslErrorHandler mSSLCertificateOnErrorHandler;
3694 private SslError mSSLCertificateOnErrorError;
3695
3696 // as SSLCertificate has different style for landscape / portrait, we
3697 // have to re-open it when configuration changed
3698 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003699 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003700
3701 // as HttpAuthentication has different style for landscape / portrait, we
3702 // have to re-open it when configuration changed
3703 private AlertDialog mHttpAuthenticationDialog;
3704 private HttpAuthHandler mHttpAuthHandler;
3705
3706 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3707 new FrameLayout.LayoutParams(
3708 ViewGroup.LayoutParams.FILL_PARENT,
3709 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003710 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3711 new FrameLayout.LayoutParams(
3712 ViewGroup.LayoutParams.FILL_PARENT,
3713 ViewGroup.LayoutParams.FILL_PARENT,
3714 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003715 // Google search
3716 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003717 // Wikipedia search
3718 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3719 // Dictionary search
3720 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3721 // Google Mobile Local search
3722 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3723
3724 final static String QUERY_PLACE_HOLDER = "%s";
3725
3726 // "source" parameter for Google search through search key
3727 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3728 // "source" parameter for Google search through goto menu
3729 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3730 // "source" parameter for Google search through simplily type
3731 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3732 // "source" parameter for Google search suggested by the browser
3733 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3734 // "source" parameter for Google search from unknown source
3735 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3736
3737 private final static String LOGTAG = "browser";
3738
The Android Open Source Project0c908882009-03-03 19:32:16 -08003739 private String mLastEnteredUrl;
3740
3741 private PowerManager.WakeLock mWakeLock;
3742 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3743
3744 private Toast mStopToast;
3745
Leon Scroggins68579392009-09-15 15:31:54 -04003746 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003747
Ben Murdochbff2d602009-07-01 20:19:05 +01003748 private LinearLayout mErrorConsoleContainer = null;
3749 private boolean mShouldShowErrorConsole = false;
3750
The Android Open Source Project0c908882009-03-03 19:32:16 -08003751 // As the ids are dynamically created, we can't guarantee that they will
3752 // be in sequence, so this static array maps ids to a window number.
3753 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3754 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3755 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3756 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3757
3758 // monitor platform changes
3759 private IntentFilter mNetworkStateChangedFilter;
3760 private BroadcastReceiver mNetworkStateIntentReceiver;
3761
Grace Klobab4da0ad2009-05-14 14:45:40 -07003762 private BroadcastReceiver mPackageInstallationReceiver;
3763
The Android Open Source Project0c908882009-03-03 19:32:16 -08003764 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003765 final static int COMBO_PAGE = 1;
3766 final static int DOWNLOAD_PAGE = 2;
3767 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003768 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003769
Andrei Popescu540035d2009-09-18 18:59:20 +01003770 // the default <video> poster
3771 private Bitmap mDefaultVideoPoster;
3772 // the video progress view
3773 private View mVideoProgressView;
3774
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003775 /**
3776 * A UrlData class to abstract how the content will be set to WebView.
3777 * This base class uses loadUrl to show the content.
3778 */
3779 private static class UrlData {
3780 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07003781 byte[] mPostData;
3782
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003783 UrlData(String url) {
3784 this.mUrl = url;
3785 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003786
3787 void setPostData(byte[] postData) {
3788 mPostData = postData;
3789 }
3790
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003791 boolean isEmpty() {
3792 return mUrl == null || mUrl.length() == 0;
3793 }
3794
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003795 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07003796 if (mPostData != null) {
3797 webView.postUrl(mUrl, mPostData);
3798 } else {
3799 webView.loadUrl(mUrl);
3800 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003801 }
3802 };
3803
3804 /**
3805 * A subclass of UrlData class that can display inlined content using
3806 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
3807 */
3808 private static class InlinedUrlData extends UrlData {
3809 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
3810 super(failUrl);
3811 mInlined = inlined;
3812 mMimeType = mimeType;
3813 mEncoding = encoding;
3814 }
3815 String mMimeType;
3816 String mInlined;
3817 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003818 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003819 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01003820 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003821 }
3822
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003823 @Override
3824 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003825 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
3826 }
3827 }
3828
Leon Scroggins1f005d32009-08-10 17:36:42 -04003829 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003830}