blob: 46e6de1da1c15cbb8da5d6625ad1bc15578100cb [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
The Android Open Source Project0c908882009-03-03 19:32:16 -080019import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080020import android.app.AlertDialog;
21import android.app.ProgressDialog;
22import android.app.SearchManager;
23import android.content.ActivityNotFoundException;
24import android.content.BroadcastReceiver;
25import android.content.ComponentName;
26import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040027import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080028import android.content.ContentValues;
29import android.content.Context;
30import android.content.DialogInterface;
31import android.content.Intent;
32import android.content.IntentFilter;
33import android.content.ServiceConnection;
Grace Klobab4da0ad2009-05-14 14:45:40 -070034import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080035import android.content.pm.PackageManager;
36import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080037import android.content.res.Configuration;
38import android.content.res.Resources;
39import android.database.Cursor;
The Android Open Source Project0c908882009-03-03 19:32:16 -080040import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010041import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080042import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080043import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040044import android.graphics.PixelFormat;
45import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080046import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080047import android.net.ConnectivityManager;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -040048import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.net.Uri;
50import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.net.http.SslCertificate;
52import android.net.http.SslError;
53import android.os.AsyncTask;
54import android.os.Bundle;
55import android.os.Debug;
56import android.os.Environment;
57import android.os.Handler;
58import android.os.IBinder;
59import android.os.Message;
60import android.os.PowerManager;
61import android.os.Process;
62import android.os.RemoteException;
63import android.os.ServiceManager;
64import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080065import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040066import android.provider.ContactsContract;
67import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.provider.Downloads;
69import android.provider.MediaStore;
The Android Open Source Project0c908882009-03-03 19:32:16 -080070import android.text.IClipboard;
71import android.text.TextUtils;
72import android.text.format.DateFormat;
Leon Scrogginsb94bf272009-09-25 15:22:08 -040073import android.util.AttributeSet;
The Android Open Source Project0c908882009-03-03 19:32:16 -080074import android.util.Log;
75import android.view.ContextMenu;
76import android.view.Gravity;
77import android.view.KeyEvent;
78import android.view.LayoutInflater;
79import android.view.Menu;
80import android.view.MenuInflater;
81import android.view.MenuItem;
82import android.view.View;
83import android.view.ViewGroup;
84import android.view.Window;
85import android.view.WindowManager;
86import android.view.ContextMenu.ContextMenuInfo;
87import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080088import android.webkit.CookieManager;
89import android.webkit.CookieSyncManager;
90import android.webkit.DownloadListener;
91import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070092import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080093import android.webkit.SslErrorHandler;
94import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010095import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080096import android.webkit.WebChromeClient;
97import android.webkit.WebHistoryItem;
98import android.webkit.WebIconDatabase;
99import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800100import android.widget.EditText;
101import android.widget.FrameLayout;
102import android.widget.LinearLayout;
103import android.widget.TextView;
104import android.widget.Toast;
105
Dan Egnor5ee906c2009-11-18 12:11:49 -0800106import com.android.common.Patterns;
107
108import com.google.android.googleapps.IGoogleLoginService;
109import com.google.android.googlelogin.GoogleLoginServiceConstants;
110
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400111import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800112import java.io.File;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800113import java.net.MalformedURLException;
114import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700115import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800116import java.net.URL;
117import java.net.URLEncoder;
118import java.text.ParseException;
119import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import java.util.HashMap;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800121import java.util.regex.Matcher;
122import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800123
124public class BrowserActivity extends Activity
Grace Kloba5942df02009-09-18 11:48:29 -0700125 implements View.OnCreateContextMenuListener,
The Android Open Source Project0c908882009-03-03 19:32:16 -0800126 DownloadListener {
127
Dave Bort31a6d1c2009-04-13 15:56:49 -0700128 /* Define some aliases to make these debugging flags easier to refer to.
129 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
130 */
131 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
132 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
133 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
134
The Android Open Source Project0c908882009-03-03 19:32:16 -0800135 private IGoogleLoginService mGls = null;
136 private ServiceConnection mGlsConnection = null;
137
Satish Sampath565505b2009-05-29 15:37:27 +0100138 // These are single-character shortcuts for searching popular sources.
139 private static final int SHORTCUT_INVALID = 0;
140 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
141 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
142 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
143 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
144
The Android Open Source Project0c908882009-03-03 19:32:16 -0800145 private void setupHomePage() {
146 final Runnable getAccount = new Runnable() {
147 public void run() {
148 // Lower priority
149 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
150 // get the default home page
151 String homepage = mSettings.getHomePage();
152
153 try {
154 if (mGls == null) return;
155
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700156 if (!homepage.startsWith("http://www.google.")) return;
157 if (homepage.indexOf('?') == -1) return;
158
The Android Open Source Project0c908882009-03-03 19:32:16 -0800159 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
160 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
161
162 // three cases:
163 //
164 // hostedUser == googleUser
165 // The device has only a google account
166 //
167 // hostedUser != googleUser
168 // The device has a hosted account and a google account
169 //
170 // hostedUser != null, googleUser == null
171 // The device has only a hosted account (so far)
172
173 // developers might have no accounts at all
174 if (hostedUser == null) return;
175
176 if (googleUser == null || !hostedUser.equals(googleUser)) {
177 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700178 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800179 }
180 } catch (RemoteException ignore) {
181 // Login service died; carry on
182 } catch (RuntimeException ignore) {
183 // Login service died; carry on
184 } finally {
185 finish(homepage);
186 }
187 }
188
189 private void finish(final String homepage) {
190 mHandler.post(new Runnable() {
191 public void run() {
192 mSettings.setHomePage(BrowserActivity.this, homepage);
193 resumeAfterCredentials();
194
195 // as this is running in a separate thread,
196 // BrowserActivity's onDestroy() may have been called,
197 // which also calls unbindService().
198 if (mGlsConnection != null) {
199 // we no longer need to keep GLS open
200 unbindService(mGlsConnection);
201 mGlsConnection = null;
202 }
203 } });
204 } };
205
206 final boolean[] done = { false };
207
208 // Open a connection to the Google Login Service. The first
209 // time the connection is established, set up the homepage depending on
210 // the account in a background thread.
211 mGlsConnection = new ServiceConnection() {
212 public void onServiceConnected(ComponentName className, IBinder service) {
213 mGls = IGoogleLoginService.Stub.asInterface(service);
214 if (done[0] == false) {
215 done[0] = true;
216 Thread account = new Thread(getAccount);
217 account.setName("GLSAccount");
218 account.start();
219 }
220 }
221 public void onServiceDisconnected(ComponentName className) {
222 mGls = null;
223 }
224 };
225
226 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
227 mGlsConnection, Context.BIND_AUTO_CREATE);
228 }
229
Cary Clarka9771242009-08-11 16:42:26 -0400230 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800231 @Override
232 public Void doInBackground(File... files) {
233 if (files != null) {
234 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400235 if (!f.delete()) {
236 Log.e(LOGTAG, f.getPath() + " was not deleted");
237 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800238 }
239 }
240 return null;
241 }
242 }
243
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400244 /**
245 * This layout holds everything you see below the status bar, including the
246 * error console, the custom view container, and the webviews.
247 */
248 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400249
Grace Kloba22ac16e2009-10-07 18:00:23 -0700250 @Override
251 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700252 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800253 Log.v(LOGTAG, this + " onStart");
254 }
255 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800256 // test the browser in OpenGL
257 // requestWindowFeature(Window.FEATURE_OPENGL);
258
259 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
260
261 mResolver = getContentResolver();
262
Grace Kloba0923d692009-09-23 21:37:25 -0700263 // If this was a web search request, pass it on to the default web
264 // search provider and finish this activity.
265 if (handleWebSearchIntent(getIntent())) {
266 finish();
267 return;
268 }
269
The Android Open Source Project0c908882009-03-03 19:32:16 -0800270 mSecLockIcon = Resources.getSystem().getDrawable(
271 android.R.drawable.ic_secure);
272 mMixLockIcon = Resources.getSystem().getDrawable(
273 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800274
Leon Scroggins81db3662009-06-04 17:45:11 -0400275 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
276 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400277 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
278 .inflate(R.layout.custom_screen, null);
279 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
280 R.id.main_content);
281 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
282 .findViewById(R.id.error_console);
283 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
284 .findViewById(R.id.fullscreen_custom_content);
285 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400286 mTitleBar = new TitleBar(this);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400287 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800288
289 // Create the tab control and our initial tab
290 mTabControl = new TabControl(this);
291
292 // Open the icon database and retain all the bookmark urls for favicons
293 retainIconsOnStartup();
294
295 // Keep a settings instance handy.
296 mSettings = BrowserSettings.getInstance();
297 mSettings.setTabControl(mTabControl);
298 mSettings.loadFromDb(this);
299
300 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
301 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
302
Grace Klobaa34f6862009-07-31 16:28:17 -0700303 /* enables registration for changes in network status from
304 http stack */
305 mNetworkStateChangedFilter = new IntentFilter();
306 mNetworkStateChangedFilter.addAction(
307 ConnectivityManager.CONNECTIVITY_ACTION);
308 mNetworkStateIntentReceiver = new BroadcastReceiver() {
309 @Override
310 public void onReceive(Context context, Intent intent) {
311 if (intent.getAction().equals(
312 ConnectivityManager.CONNECTIVITY_ACTION)) {
Robert Greenwalt7d899d62009-10-23 10:33:48 -0700313 boolean noConnectivity = intent.getBooleanExtra(
314 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
315 onNetworkToggle(!noConnectivity);
Grace Klobaa34f6862009-07-31 16:28:17 -0700316 }
317 }
318 };
319
Grace Kloba615c6c92009-08-03 10:22:44 -0700320 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
321 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
322 filter.addDataScheme("package");
323 mPackageInstallationReceiver = new BroadcastReceiver() {
324 @Override
325 public void onReceive(Context context, Intent intent) {
326 final String action = intent.getAction();
327 final String packageName = intent.getData()
328 .getSchemeSpecificPart();
329 final boolean replacing = intent.getBooleanExtra(
330 Intent.EXTRA_REPLACING, false);
331 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
332 // if it is replacing, refreshPlugins() when adding
333 return;
334 }
335 PackageManager pm = BrowserActivity.this.getPackageManager();
336 PackageInfo pkgInfo = null;
337 try {
338 pkgInfo = pm.getPackageInfo(packageName,
339 PackageManager.GET_PERMISSIONS);
340 } catch (PackageManager.NameNotFoundException e) {
341 return;
342 }
343 if (pkgInfo != null) {
344 String permissions[] = pkgInfo.requestedPermissions;
345 if (permissions == null) {
346 return;
347 }
348 boolean permissionOk = false;
349 for (String permit : permissions) {
350 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
351 permissionOk = true;
352 break;
353 }
354 }
355 if (permissionOk) {
356 PluginManager.getInstance(BrowserActivity.this)
357 .refreshPlugins(
358 Intent.ACTION_PACKAGE_ADDED
359 .equals(action));
360 }
361 }
362 }
363 };
364 registerReceiver(mPackageInstallationReceiver, filter);
365
The Android Open Source Project0c908882009-03-03 19:32:16 -0800366 if (!mTabControl.restoreState(icicle)) {
367 // clear up the thumbnail directory if we can't restore the state as
368 // none of the files in the directory are referenced any more.
369 new ClearThumbnails().execute(
370 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700371 // there is no quit on Android. But if we can't restore the state,
372 // we can treat it as a new Browser, remove the old session cookies.
373 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800374 final Intent intent = getIntent();
375 final Bundle extra = intent.getExtras();
376 // Create an initial tab.
377 // If the intent is ACTION_VIEW and data is not null, the Browser is
378 // invoked to view the content by another application. In this case,
379 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700380 UrlData urlData = getUrlDataFromIntent(intent);
381
Grace Kloba22ac16e2009-10-07 18:00:23 -0700382 final Tab t = mTabControl.createNewTab(
The Android Open Source Project0c908882009-03-03 19:32:16 -0800383 Intent.ACTION_VIEW.equals(intent.getAction()) &&
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700384 intent.getData() != null,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700385 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800386 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800387 attachTabToContentView(t);
388 WebView webView = t.getWebView();
389 if (extra != null) {
390 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
391 if (scale > 0 && scale <= 1000) {
392 webView.setInitialScale(scale);
393 }
394 }
395 // If we are not restoring from an icicle, then there is a high
396 // likely hood this is the first run. So, check to see if the
397 // homepage needs to be configured and copy any plugins from our
398 // asset directory to the data partition.
399 if ((extra == null || !extra.getBoolean("testing"))
400 && !mSettings.isLoginInitialized()) {
401 setupHomePage();
402 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800403
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700404 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400405 if (mSettings.isLoginInitialized()) {
406 webView.loadUrl(mSettings.getHomePage());
407 } else {
408 waitForCredentials();
409 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800410 } else {
Grace Kloba81678d92009-06-30 07:09:56 -0700411 if (extra != null) {
412 urlData.setPostData(extra
413 .getByteArray(Browser.EXTRA_POST_DATA));
414 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700415 urlData.loadIn(webView);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800416 }
417 } else {
418 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400419 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800420 attachTabToContentView(mTabControl.getCurrentTab());
421 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700422
Feng Qianb3c02da2009-06-29 15:58:08 -0700423 // Read JavaScript flags if it exists.
424 String jsFlags = mSettings.getJsFlags();
425 if (jsFlags.trim().length() != 0) {
426 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
427 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800428 }
429
430 @Override
431 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700432 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800433 // When a tab is closed on exit, the current tab index is set to -1.
434 // Reset before proceed as Browser requires the current tab to be set.
435 if (current == null) {
436 // Try to reset the tab in case the index was incorrect.
437 current = mTabControl.getTab(0);
438 if (current == null) {
439 // No tabs at all so just ignore this intent.
440 return;
441 }
442 mTabControl.setCurrentTab(current);
443 attachTabToContentView(current);
444 resetTitleAndIcon(current.getWebView());
445 }
446 final String action = intent.getAction();
447 final int flags = intent.getFlags();
448 if (Intent.ACTION_MAIN.equals(action) ||
449 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
450 // just resume the browser
451 return;
452 }
453 if (Intent.ACTION_VIEW.equals(action)
454 || Intent.ACTION_SEARCH.equals(action)
455 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
456 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100457 // If this was a search request (e.g. search query directly typed into the address bar),
458 // pass it on to the default web search provider.
459 if (handleWebSearchIntent(intent)) {
460 return;
461 }
462
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700463 UrlData urlData = getUrlDataFromIntent(intent);
464 if (urlData.isEmpty()) {
465 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800466 }
Grace Kloba81678d92009-06-30 07:09:56 -0700467 urlData.setPostData(intent
468 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700469
Grace Klobacc634032009-07-28 15:58:19 -0700470 final String appId = intent
471 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
472 if (Intent.ACTION_VIEW.equals(action)
473 && !getPackageName().equals(appId)
474 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700475 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700476 if (appTab != null) {
477 Log.i(LOGTAG, "Reusing tab for " + appId);
478 // Dismiss the subwindow if applicable.
479 dismissSubWindow(appTab);
480 // Since we might kill the WebView, remove it from the
481 // content view first.
482 removeTabFromContentView(appTab);
483 // Recreate the main WebView after destroying the old one.
484 // If the WebView has the same original url and is on that
485 // page, it can be reused.
486 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700487 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100488
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700489 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400490 switchToTab(mTabControl.getTabIndex(appTab));
491 if (needsLoad) {
492 urlData.loadIn(appTab.getWebView());
493 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700494 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400495 // If the tab was the current tab, we have to attach
496 // it to the view system again.
497 attachTabToContentView(appTab);
498 if (needsLoad) {
499 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700500 }
501 }
502 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400503 } else {
504 // No matching application tab, try to find a regular tab
505 // with a matching url.
506 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400507 if (appTab != null) {
508 if (current != appTab) {
509 switchToTab(mTabControl.getTabIndex(appTab));
510 }
511 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400512 } else {
513 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
514 // will be opened in a new tab unless we have reached
515 // MAX_TABS. Then the url will be opened in the current
516 // tab. If a new tab is created, it will have "true" for
517 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400518 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400519 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700520 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800521 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800522 if (!urlData.isEmpty()
523 && urlData.mUrl.startsWith("about:debug")) {
524 if ("about:debug.dom".equals(urlData.mUrl)) {
525 current.getWebView().dumpDomTree(false);
526 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
527 current.getWebView().dumpDomTree(true);
528 } else if ("about:debug.render".equals(urlData.mUrl)) {
529 current.getWebView().dumpRenderTree(false);
530 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
531 current.getWebView().dumpRenderTree(true);
532 } else if ("about:debug.display".equals(urlData.mUrl)) {
533 current.getWebView().dumpDisplayTree();
534 } else {
535 mSettings.toggleDebugSettings();
536 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800537 return;
538 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400539 // Get rid of the subwindow if it exists
540 dismissSubWindow(current);
541 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800542 }
543 }
544 }
545
Satish Sampath565505b2009-05-29 15:37:27 +0100546 private int parseUrlShortcut(String url) {
547 if (url == null) return SHORTCUT_INVALID;
548
549 // FIXME: quick search, need to be customized by setting
550 if (url.length() > 2 && url.charAt(1) == ' ') {
551 switch (url.charAt(0)) {
552 case 'g': return SHORTCUT_GOOGLE_SEARCH;
553 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
554 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
555 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
556 }
557 }
558 return SHORTCUT_INVALID;
559 }
560
561 /**
562 * Launches the default web search activity with the query parameters if the given intent's data
563 * are identified as plain search terms and not URLs/shortcuts.
564 * @return true if the intent was handled and web search activity was launched, false if not.
565 */
566 private boolean handleWebSearchIntent(Intent intent) {
567 if (intent == null) return false;
568
569 String url = null;
570 final String action = intent.getAction();
571 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700572 Uri data = intent.getData();
573 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100574 } else if (Intent.ACTION_SEARCH.equals(action)
575 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
576 || Intent.ACTION_WEB_SEARCH.equals(action)) {
577 url = intent.getStringExtra(SearchManager.QUERY);
578 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100579 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
580 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100581 }
582
583 /**
584 * Launches the default web search activity with the query parameters if the given url string
585 * was identified as plain search terms and not URL/shortcut.
586 * @return true if the request was handled and web search activity was launched, false if not.
587 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100588 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100589 if (inUrl == null) return false;
590
591 // In general, we shouldn't modify URL from Intent.
592 // But currently, we get the user-typed URL from search box as well.
593 String url = fixUrl(inUrl).trim();
594
595 // URLs and site specific search shortcuts are handled by the regular flow of control, so
596 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800597 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100598 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100599 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
600 return false;
601 }
602
603 Browser.updateVisitedHistory(mResolver, url, false);
604 Browser.addSearchUrl(mResolver, url);
605
606 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
607 intent.addCategory(Intent.CATEGORY_DEFAULT);
608 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100609 if (appData != null) {
610 intent.putExtra(SearchManager.APP_DATA, appData);
611 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100612 if (extraData != null) {
613 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
614 }
Grace Klobacc634032009-07-28 15:58:19 -0700615 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100616 startActivity(intent);
617
618 return true;
619 }
620
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700621 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800622 String url = null;
623 if (intent != null) {
624 final String action = intent.getAction();
625 if (Intent.ACTION_VIEW.equals(action)) {
626 url = smartUrlFilter(intent.getData());
627 if (url != null && url.startsWith("content:")) {
628 /* Append mimetype so webview knows how to display */
629 String mimeType = intent.resolveType(getContentResolver());
630 if (mimeType != null) {
631 url += "?" + mimeType;
632 }
633 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700634 if ("inline:".equals(url)) {
635 return new InlinedUrlData(
636 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
637 intent.getType(),
638 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
639 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
640 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800641 } else if (Intent.ACTION_SEARCH.equals(action)
642 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
643 || Intent.ACTION_WEB_SEARCH.equals(action)) {
644 url = intent.getStringExtra(SearchManager.QUERY);
645 if (url != null) {
646 mLastEnteredUrl = url;
Leon Scrogginsb4464432009-11-25 12:37:50 -0500647 Browser.updateVisitedHistory(mResolver, url, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800648 // In general, we shouldn't modify URL from Intent.
649 // But currently, we get the user-typed URL from search box as well.
650 url = fixUrl(url);
651 url = smartUrlFilter(url);
652 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
653 if (url.contains(searchSource)) {
654 String source = null;
655 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
656 if (appData != null) {
657 source = appData.getString(SearchManager.SOURCE);
658 }
659 if (TextUtils.isEmpty(source)) {
660 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
661 }
662 url = url.replace(searchSource, "&source=android-"+source+"&");
663 }
664 }
665 }
666 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700667 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800668 }
669
670 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400671 // FIXME: Converting the url to lower case
672 // duplicates functionality in smartUrlFilter().
673 // However, changing all current callers of fixUrl to
674 // call smartUrlFilter in addition may have unwanted
675 // consequences, and is deferred for now.
676 int colon = inUrl.indexOf(':');
677 boolean allLower = true;
678 for (int index = 0; index < colon; index++) {
679 char ch = inUrl.charAt(index);
680 if (!Character.isLetter(ch)) {
681 break;
682 }
683 allLower &= Character.isLowerCase(ch);
684 if (index == colon - 1 && !allLower) {
685 inUrl = inUrl.substring(0, colon).toLowerCase()
686 + inUrl.substring(colon);
687 }
688 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800689 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
690 return inUrl;
691 if (inUrl.startsWith("http:") ||
692 inUrl.startsWith("https:")) {
693 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
694 inUrl = inUrl.replaceFirst("/", "//");
695 } else inUrl = inUrl.replaceFirst(":", "://");
696 }
697 return inUrl;
698 }
699
Grace Kloba22ac16e2009-10-07 18:00:23 -0700700 @Override
701 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800702 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700703 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800704 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
705 }
706
707 if (!mActivityInPause) {
708 Log.e(LOGTAG, "BrowserActivity is already resumed.");
709 return;
710 }
711
Mike Reed7bfa63b2009-05-28 11:08:32 -0400712 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800713 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400714 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800715
716 if (mWakeLock.isHeld()) {
717 mHandler.removeMessages(RELEASE_WAKELOCK);
718 mWakeLock.release();
719 }
720
721 if (mCredsDlg != null) {
722 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
723 // In case credential request never comes back
724 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
725 }
726 }
727
728 registerReceiver(mNetworkStateIntentReceiver,
729 mNetworkStateChangedFilter);
730 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800731 }
732
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400733 /**
734 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400735 * would change its appearance, use a different TitleBar to show overlayed
736 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400737 */
738 private TitleBar mFakeTitleBar;
739
740 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400741 * Holder for the fake title bar. It will have a foreground shadow, as well
742 * as a white background, so the fake title bar looks like the real one.
743 */
744 private ViewGroup mFakeTitleBarHolder;
745
746 /**
747 * Layout parameters for the fake title bar within mFakeTitleBarHolder
748 */
749 private FrameLayout.LayoutParams mFakeTitleBarParams
750 = new FrameLayout.LayoutParams(
Leon Scrogginsc01e4a82009-09-16 14:41:00 -0400751 ViewGroup.LayoutParams.FILL_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400752 ViewGroup.LayoutParams.WRAP_CONTENT);
753 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400754 * Keeps track of whether the options menu is open. This is important in
755 * determining whether to show or hide the title bar overlay.
756 */
757 private boolean mOptionsMenuOpen;
758
759 /**
760 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
761 * of whether the configuration has changed. The first onMenuOpened call
762 * after a configuration change is simply a reopening of the same menu
763 * (i.e. mIconView did not change).
764 */
765 private boolean mConfigChanged;
766
767 /**
768 * Whether or not the options menu is in its smaller, icon menu form. When
769 * true, we want the title bar overlay to be up. When false, we do not.
770 * Only meaningful if mOptionsMenuOpen is true.
771 */
772 private boolean mIconView;
773
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400774 @Override
775 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400776 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
777 if (mOptionsMenuOpen) {
778 if (mConfigChanged) {
779 // We do not need to make any changes to the state of the
780 // title bar, since the only thing that happened was a
781 // change in orientation
782 mConfigChanged = false;
783 } else {
784 if (mIconView) {
785 // Switching the menu to expanded view, so hide the
786 // title bar.
787 hideFakeTitleBar();
788 mIconView = false;
789 } else {
790 // Switching the menu back to icon view, so show the
791 // title bar once again.
792 showFakeTitleBar();
793 mIconView = true;
794 }
795 }
796 } else {
797 // The options menu is closed, so open it, and show the title
798 showFakeTitleBar();
799 mOptionsMenuOpen = true;
800 mConfigChanged = false;
801 mIconView = true;
802 }
803 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400804 return true;
805 }
806
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400807 /**
808 * Special class used exclusively for the shadow drawn underneath the fake
809 * title bar. The shadow does not need to be drawn if the WebView
810 * underneath is scrolled to the top, because it will draw directly on top
811 * of the embedded shadow.
812 */
813 private static class Shadow extends View {
814 private WebView mWebView;
815
816 public Shadow(Context context, AttributeSet attrs) {
817 super(context, attrs);
818 }
819
820 public void setWebView(WebView view) {
821 mWebView = view;
822 }
823
824 @Override
825 public void draw(Canvas canvas) {
826 // In general onDraw is the method to override, but we care about
827 // whether or not the background gets drawn, which happens in draw()
828 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
829 super.draw(canvas);
830 }
831 // Need to invalidate so that if the scroll position changes, we
832 // still draw as appropriate.
833 invalidate();
834 }
835 }
836
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400837 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400838 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400839 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400840 && !mActivityInPause && decor != null
841 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400842 Rect visRect = new Rect();
843 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
844 if (LOGD_ENABLED) {
845 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
846 }
847 return;
848 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400849
850 WindowManager manager
851 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
852
853 // Add the title bar to the window manager so it can receive touches
854 // while the menu is up
855 WindowManager.LayoutParams params
856 = new WindowManager.LayoutParams(
857 ViewGroup.LayoutParams.FILL_PARENT,
858 ViewGroup.LayoutParams.WRAP_CONTENT,
859 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
860 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400861 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400862 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400863 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400864 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400865 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400866 // XXX : Without providing an offset, the fake title bar will be
867 // placed underneath the status bar. Use the global visible rect
868 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400869 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400870 // Add a holder for the title bar. It also holds a shadow to show
871 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400872 if (mFakeTitleBarHolder == null) {
873 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
874 .inflate(R.layout.title_bar_bg, null);
875 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400876 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
877 R.id.shadow);
878 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400879 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400880 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400881 }
882 }
883
884 @Override
885 public void onOptionsMenuClosed(Menu menu) {
886 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400887 if (!mInLoad) {
888 hideFakeTitleBar();
889 } else if (!mIconView) {
890 // The page is currently loading, and we are in expanded mode, so
891 // we were not showing the menu. Show it once again. It will be
892 // removed when the page finishes.
893 showFakeTitleBar();
894 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400895 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700896
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400897 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400898 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400899 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
900 mFakeTitleBarHolder.getLayoutParams();
901 WebView mainView = mTabControl.getCurrentWebView();
902 // Although we decided whether or not to animate based on the current
903 // scroll position, the scroll position may have changed since the
904 // fake title bar was displayed. Make sure it has the appropriate
905 // animation/lack thereof before removing.
906 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400907 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400908 WindowManager manager
909 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -0400910 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400911 mFakeTitleBarHolder.removeView(mFakeTitleBar);
912 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400913 }
914
The Android Open Source Project0c908882009-03-03 19:32:16 -0800915 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400916 * Special method for the fake title bar to call when displaying its context
917 * menu, since it is in its own Window, and its parent does not show a
918 * context menu.
919 */
920 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400921 if (null == mTitleBar.getParent()) {
922 return;
923 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400924 openContextMenu(mTitleBar);
925 }
926
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400927 @Override
928 public void onContextMenuClosed(Menu menu) {
929 super.onContextMenuClosed(menu);
930 if (mInLoad) {
931 showFakeTitleBar();
932 }
933 }
934
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400935 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800936 * onSaveInstanceState(Bundle map)
937 * onSaveInstanceState is called right before onStop(). The map contains
938 * the saved state.
939 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700940 @Override
941 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700942 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800943 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
944 }
945 // the default implementation requires each view to have an id. As the
946 // browser handles the state itself and it doesn't use id for the views,
947 // don't call the default implementation. Otherwise it will trigger the
948 // warning like this, "couldn't save which view has focus because the
949 // focused view XXX has no id".
950
951 // Save all the tabs
952 mTabControl.saveState(outState);
953 }
954
Grace Kloba22ac16e2009-10-07 18:00:23 -0700955 @Override
956 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800957 super.onPause();
958
959 if (mActivityInPause) {
960 Log.e(LOGTAG, "BrowserActivity is already paused.");
961 return;
962 }
963
Mike Reed7bfa63b2009-05-28 11:08:32 -0400964 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800965 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400966 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800967 mWakeLock.acquire();
968 mHandler.sendMessageDelayed(mHandler
969 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
970 }
971
972 // Clear the credentials toast if it is up
973 if (mCredsDlg != null && mCredsDlg.isShowing()) {
974 mCredsDlg.dismiss();
975 }
976 mCredsDlg = null;
977
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400978 // FIXME: This removes the active tabs page and resets the menu to
979 // MAIN_MENU. A better solution might be to do this work in onNewIntent
980 // but then we would need to save it in onSaveInstanceState and restore
981 // it in onCreate/onRestoreInstanceState
982 if (mActiveTabsPage != null) {
983 removeActiveTabPage(true);
984 }
985
The Android Open Source Project0c908882009-03-03 19:32:16 -0800986 cancelStopToast();
987
988 // unregister network state listener
989 unregisterReceiver(mNetworkStateIntentReceiver);
990 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800991 }
992
Grace Kloba22ac16e2009-10-07 18:00:23 -0700993 @Override
994 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700995 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800996 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
997 }
998 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700999
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001000 if (mUploadMessage != null) {
1001 mUploadMessage.onReceiveValue(null);
1002 mUploadMessage = null;
1003 }
1004
Grace Kloba0923d692009-09-23 21:37:25 -07001005 if (mTabControl == null) return;
1006
Grace Kloba1fc98a32009-10-21 13:23:08 -07001007 // Remove the fake title bar if it is there
1008 hideFakeTitleBar();
1009
The Android Open Source Project0c908882009-03-03 19:32:16 -08001010 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001011 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001012 if (t != null) {
1013 dismissSubWindow(t);
1014 removeTabFromContentView(t);
1015 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001016 // Destroy all the tabs
1017 mTabControl.destroy();
1018 WebIconDatabase.getInstance().close();
1019 if (mGlsConnection != null) {
1020 unbindService(mGlsConnection);
1021 mGlsConnection = null;
1022 }
1023
Grace Klobab4da0ad2009-05-14 14:45:40 -07001024 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001025 }
1026
1027 @Override
1028 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001029 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001030 super.onConfigurationChanged(newConfig);
1031
1032 if (mPageInfoDialog != null) {
1033 mPageInfoDialog.dismiss();
1034 showPageInfo(
1035 mPageInfoView,
1036 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1037 }
1038 if (mSSLCertificateDialog != null) {
1039 mSSLCertificateDialog.dismiss();
1040 showSSLCertificate(
1041 mSSLCertificateView);
1042 }
1043 if (mSSLCertificateOnErrorDialog != null) {
1044 mSSLCertificateOnErrorDialog.dismiss();
1045 showSSLCertificateOnError(
1046 mSSLCertificateOnErrorView,
1047 mSSLCertificateOnErrorHandler,
1048 mSSLCertificateOnErrorError);
1049 }
1050 if (mHttpAuthenticationDialog != null) {
1051 String title = ((TextView) mHttpAuthenticationDialog
1052 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1053 .toString();
1054 String name = ((TextView) mHttpAuthenticationDialog
1055 .findViewById(R.id.username_edit)).getText().toString();
1056 String password = ((TextView) mHttpAuthenticationDialog
1057 .findViewById(R.id.password_edit)).getText().toString();
1058 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1059 .getId();
1060 mHttpAuthenticationDialog.dismiss();
1061 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1062 name, password, focusId);
1063 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001064 }
1065
Grace Kloba22ac16e2009-10-07 18:00:23 -07001066 @Override
1067 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001068 super.onLowMemory();
1069 mTabControl.freeMemory();
1070 }
1071
Mike Reed7bfa63b2009-05-28 11:08:32 -04001072 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001073 Tab tab = mTabControl.getCurrentTab();
1074 boolean inLoad = tab.inLoad();
1075 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001076 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001077 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001078 if (w != null) {
1079 w.resumeTimers();
1080 }
1081 return true;
1082 } else {
1083 return false;
1084 }
1085 }
1086
Mike Reed7bfa63b2009-05-28 11:08:32 -04001087 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001088 Tab tab = mTabControl.getCurrentTab();
1089 boolean inLoad = tab.inLoad();
1090 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001091 CookieSyncManager.getInstance().stopSync();
1092 WebView w = mTabControl.getCurrentWebView();
1093 if (w != null) {
1094 w.pauseTimers();
1095 }
1096 return true;
1097 } else {
1098 return false;
1099 }
1100 }
1101
Leon Scroggins1f005d32009-08-10 17:36:42 -04001102 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001103 /*
1104 * This function is called when we are launching for the first time. We
1105 * are waiting for the login credentials before loading Google home
1106 * pages. This way the user will be logged in straight away.
1107 */
1108 private void waitForCredentials() {
1109 // Show a toast
1110 mCredsDlg = new ProgressDialog(this);
1111 mCredsDlg.setIndeterminate(true);
1112 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1113 // If the user cancels the operation, then cancel the Google
1114 // Credentials request.
1115 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1116 mCredsDlg.show();
1117
1118 // We set a timeout for the retrieval of credentials in onResume()
1119 // as that is when we have freed up some CPU time to get
1120 // the login credentials.
1121 }
1122
1123 /*
1124 * If we have received the credentials or we have timed out and we are
1125 * showing the credentials dialog, then it is time to move on.
1126 */
1127 private void resumeAfterCredentials() {
1128 if (mCredsDlg == null) {
1129 return;
1130 }
1131
1132 // Clear the toast
1133 if (mCredsDlg.isShowing()) {
1134 mCredsDlg.dismiss();
1135 }
1136 mCredsDlg = null;
1137
1138 // Clear any pending timeout
1139 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1140
1141 // Load the page
1142 WebView w = mTabControl.getCurrentWebView();
1143 if (w != null) {
1144 w.loadUrl(mSettings.getHomePage());
1145 }
1146
1147 // Update the settings, need to do this last as it can take a moment
1148 // to persist the settings. In the mean time we could be loading
1149 // content.
1150 mSettings.setLoginInitialized(this);
1151 }
1152
1153 // Open the icon database and retain all the icons for visited sites.
1154 private void retainIconsOnStartup() {
1155 final WebIconDatabase db = WebIconDatabase.getInstance();
1156 db.open(getDir("icons", 0).getPath());
1157 try {
1158 Cursor c = Browser.getAllBookmarks(mResolver);
1159 if (!c.moveToFirst()) {
1160 c.deactivate();
1161 return;
1162 }
1163 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1164 do {
1165 String url = c.getString(urlIndex);
1166 db.retainIconForPageUrl(url);
1167 } while (c.moveToNext());
1168 c.deactivate();
1169 } catch (IllegalStateException e) {
1170 Log.e(LOGTAG, "retainIconsOnStartup", e);
1171 }
1172 }
1173
1174 // Helper method for getting the top window.
1175 WebView getTopWindow() {
1176 return mTabControl.getCurrentTopWebView();
1177 }
1178
Grace Kloba22ac16e2009-10-07 18:00:23 -07001179 TabControl getTabControl() {
1180 return mTabControl;
1181 }
1182
The Android Open Source Project0c908882009-03-03 19:32:16 -08001183 @Override
1184 public boolean onCreateOptionsMenu(Menu menu) {
1185 super.onCreateOptionsMenu(menu);
1186
1187 MenuInflater inflater = getMenuInflater();
1188 inflater.inflate(R.menu.browser, menu);
1189 mMenu = menu;
1190 updateInLoadMenuItems();
1191 return true;
1192 }
1193
1194 /**
1195 * As the menu can be open when loading state changes
1196 * we must manually update the state of the stop/reload menu
1197 * item
1198 */
1199 private void updateInLoadMenuItems() {
1200 if (mMenu == null) {
1201 return;
1202 }
1203 MenuItem src = mInLoad ?
1204 mMenu.findItem(R.id.stop_menu_id):
1205 mMenu.findItem(R.id.reload_menu_id);
1206 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1207 dest.setIcon(src.getIcon());
1208 dest.setTitle(src.getTitle());
1209 }
1210
1211 @Override
1212 public boolean onContextItemSelected(MenuItem item) {
1213 // chording is not an issue with context menus, but we use the same
1214 // options selector, so set mCanChord to true so we can access them.
1215 mCanChord = true;
1216 int id = item.getItemId();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001217 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001218 // For the context menu from the title bar
1219 case R.id.title_bar_share_page_url:
1220 case R.id.title_bar_copy_page_url:
1221 WebView mainView = mTabControl.getCurrentWebView();
1222 if (null == mainView) {
1223 return false;
1224 }
1225 if (id == R.id.title_bar_share_page_url) {
1226 Browser.sendString(this, mainView.getUrl());
1227 } else {
1228 copy(mainView.getUrl());
1229 }
1230 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001231 // -- Browser context menu
1232 case R.id.open_context_menu_id:
1233 case R.id.open_newtab_context_menu_id:
1234 case R.id.bookmark_context_menu_id:
1235 case R.id.save_link_context_menu_id:
1236 case R.id.share_link_context_menu_id:
1237 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001238 final WebView webView = getTopWindow();
1239 if (null == webView) {
1240 return false;
1241 }
1242 final HashMap hrefMap = new HashMap();
1243 hrefMap.put("webview", webView);
1244 final Message msg = mHandler.obtainMessage(
1245 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001246 webView.requestFocusNodeHref(msg);
1247 break;
1248
1249 default:
1250 // For other context menus
1251 return onOptionsItemSelected(item);
1252 }
1253 mCanChord = false;
1254 return true;
1255 }
1256
1257 private Bundle createGoogleSearchSourceBundle(String source) {
1258 Bundle bundle = new Bundle();
1259 bundle.putString(SearchManager.SOURCE, source);
1260 return bundle;
1261 }
1262
1263 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001264 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001265 */
1266 @Override
1267 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001268 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001269 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001270 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001271 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001272 return true;
1273 }
1274
1275 @Override
1276 public void startSearch(String initialQuery, boolean selectInitialQuery,
1277 Bundle appSearchData, boolean globalSearch) {
1278 if (appSearchData == null) {
1279 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1280 }
1281 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1282 }
1283
Leon Scroggins1f005d32009-08-10 17:36:42 -04001284 /**
1285 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1286 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001287 * @param index Index of the tab to change to, as defined by
1288 * mTabControl.getTabIndex(Tab t).
1289 * @return boolean True if we successfully switched to a different tab. If
1290 * the indexth tab is null, or if that tab is the same as
1291 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001292 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001293 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001294 Tab tab = mTabControl.getTab(index);
1295 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001296 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001297 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001298 }
1299 if (currentTab != null) {
1300 // currentTab may be null if it was just removed. In that case,
1301 // we do not need to remove it
1302 removeTabFromContentView(currentTab);
1303 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001304 mTabControl.setCurrentTab(tab);
1305 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001306 resetTitleIconAndProgress();
1307 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001308 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001309 }
1310
Grace Kloba22ac16e2009-10-07 18:00:23 -07001311 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001312 return openTabAndShow(mSettings.getHomePage(), false, null);
1313 }
1314
Leon Scroggins1f005d32009-08-10 17:36:42 -04001315 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001316 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001317 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001318 // This is the last tab. Open a new one, with the home
1319 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001320 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001321 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001322 return;
1323 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001324 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001325 int indexToShow = -1;
1326 if (parent != null) {
1327 indexToShow = mTabControl.getTabIndex(parent);
1328 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001329 final int currentIndex = mTabControl.getCurrentIndex();
1330 // Try to move to the tab to the right
1331 indexToShow = currentIndex + 1;
1332 if (indexToShow > mTabControl.getTabCount() - 1) {
1333 // Try to move to the tab to the left
1334 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001335 }
1336 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001337 if (switchToTab(indexToShow)) {
1338 // Close window
1339 closeTab(current);
1340 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001341 }
1342
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001343 private ActiveTabsPage mActiveTabsPage;
1344
1345 /**
1346 * Remove the active tabs page.
1347 * @param needToAttach If true, the active tabs page did not attach a tab
1348 * to the content view, so we need to do that here.
1349 */
1350 /* package */ void removeActiveTabPage(boolean needToAttach) {
1351 mContentView.removeView(mActiveTabsPage);
1352 mActiveTabsPage = null;
1353 mMenuState = R.id.MAIN_MENU;
1354 if (needToAttach) {
1355 attachTabToContentView(mTabControl.getCurrentTab());
1356 }
1357 getTopWindow().requestFocus();
1358 }
1359
The Android Open Source Project0c908882009-03-03 19:32:16 -08001360 @Override
1361 public boolean onOptionsItemSelected(MenuItem item) {
1362 if (!mCanChord) {
1363 // The user has already fired a shortcut with this hold down of the
1364 // menu key.
1365 return false;
1366 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001367 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001368 return false;
1369 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001370 if (mMenuIsDown) {
1371 // The shortcut action consumes the MENU. Even if it is still down,
1372 // it won't trigger the next shortcut action. In the case of the
1373 // shortcut action triggering a new activity, like Bookmarks, we
1374 // won't get onKeyUp for MENU. So it is important to reset it here.
1375 mMenuIsDown = false;
1376 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001377 switch (item.getItemId()) {
1378 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001379 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001380 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001381 break;
1382
Leon Scroggins64b80f32009-08-07 12:03:34 -04001383 case R.id.goto_menu_id:
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001384 onSearchRequested();
1385 break;
1386
1387 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001388 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001389 break;
1390
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001391 case R.id.active_tabs_menu_id:
1392 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1393 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001394 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001395 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1396 mActiveTabsPage.requestFocus();
1397 mMenuState = EMPTY_MENU;
1398 break;
1399
Leon Scroggins1f005d32009-08-10 17:36:42 -04001400 case R.id.add_bookmark_menu_id:
1401 Intent i = new Intent(BrowserActivity.this,
1402 AddBookmarkPage.class);
1403 WebView w = getTopWindow();
1404 i.putExtra("url", w.getUrl());
1405 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001406 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001407 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001408 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001409 break;
1410
1411 case R.id.stop_reload_menu_id:
1412 if (mInLoad) {
1413 stopLoading();
1414 } else {
1415 getTopWindow().reload();
1416 }
1417 break;
1418
1419 case R.id.back_menu_id:
1420 getTopWindow().goBack();
1421 break;
1422
1423 case R.id.forward_menu_id:
1424 getTopWindow().goForward();
1425 break;
1426
1427 case R.id.close_menu_id:
1428 // Close the subwindow if it exists.
1429 if (mTabControl.getCurrentSubWindow() != null) {
1430 dismissSubWindow(mTabControl.getCurrentTab());
1431 break;
1432 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001433 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001434 break;
1435
1436 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001437 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001438 if (current != null) {
1439 dismissSubWindow(current);
1440 current.getWebView().loadUrl(mSettings.getHomePage());
1441 }
1442 break;
1443
1444 case R.id.preferences_menu_id:
1445 Intent intent = new Intent(this,
1446 BrowserPreferencesPage.class);
1447 startActivityForResult(intent, PREFERENCES_PAGE);
1448 break;
1449
1450 case R.id.find_menu_id:
1451 if (null == mFindDialog) {
1452 mFindDialog = new FindDialog(this);
1453 }
1454 mFindDialog.setWebView(getTopWindow());
1455 mFindDialog.show();
1456 mMenuState = EMPTY_MENU;
1457 break;
1458
1459 case R.id.select_text_id:
1460 getTopWindow().emulateShiftHeld();
1461 break;
1462 case R.id.page_info_menu_id:
1463 showPageInfo(mTabControl.getCurrentTab(), false);
1464 break;
1465
1466 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001467 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001468 break;
1469
1470 case R.id.share_page_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01001471 Browser.sendString(this, getTopWindow().getUrl(),
1472 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001473 break;
1474
1475 case R.id.dump_nav_menu_id:
1476 getTopWindow().debugDump();
1477 break;
1478
1479 case R.id.zoom_in_menu_id:
1480 getTopWindow().zoomIn();
1481 break;
1482
1483 case R.id.zoom_out_menu_id:
1484 getTopWindow().zoomOut();
1485 break;
1486
1487 case R.id.view_downloads_menu_id:
1488 viewDownloads(null);
1489 break;
1490
The Android Open Source Project0c908882009-03-03 19:32:16 -08001491 case R.id.window_one_menu_id:
1492 case R.id.window_two_menu_id:
1493 case R.id.window_three_menu_id:
1494 case R.id.window_four_menu_id:
1495 case R.id.window_five_menu_id:
1496 case R.id.window_six_menu_id:
1497 case R.id.window_seven_menu_id:
1498 case R.id.window_eight_menu_id:
1499 {
1500 int menuid = item.getItemId();
1501 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1502 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001503 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001504 if (desiredTab != null &&
1505 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001506 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001507 }
1508 break;
1509 }
1510 }
1511 }
1512 break;
1513
1514 default:
1515 if (!super.onOptionsItemSelected(item)) {
1516 return false;
1517 }
1518 // Otherwise fall through.
1519 }
1520 mCanChord = false;
1521 return true;
1522 }
1523
1524 public void closeFind() {
1525 mMenuState = R.id.MAIN_MENU;
1526 }
1527
Grace Kloba22ac16e2009-10-07 18:00:23 -07001528 @Override
1529 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001530 // This happens when the user begins to hold down the menu key, so
1531 // allow them to chord to get a shortcut.
1532 mCanChord = true;
1533 // Note: setVisible will decide whether an item is visible; while
1534 // setEnabled() will decide whether an item is enabled, which also means
1535 // whether the matching shortcut key will function.
1536 super.onPrepareOptionsMenu(menu);
1537 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001538 case EMPTY_MENU:
1539 if (mCurrentMenuState != mMenuState) {
1540 menu.setGroupVisible(R.id.MAIN_MENU, false);
1541 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1542 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001543 }
1544 break;
1545 default:
1546 if (mCurrentMenuState != mMenuState) {
1547 menu.setGroupVisible(R.id.MAIN_MENU, true);
1548 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1549 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001550 }
1551 final WebView w = getTopWindow();
1552 boolean canGoBack = false;
1553 boolean canGoForward = false;
1554 boolean isHome = false;
1555 if (w != null) {
1556 canGoBack = w.canGoBack();
1557 canGoForward = w.canGoForward();
1558 isHome = mSettings.getHomePage().equals(w.getUrl());
1559 }
1560 final MenuItem back = menu.findItem(R.id.back_menu_id);
1561 back.setEnabled(canGoBack);
1562
1563 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1564 home.setEnabled(!isHome);
1565
1566 menu.findItem(R.id.forward_menu_id)
1567 .setEnabled(canGoForward);
1568
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001569 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001570 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001571
The Android Open Source Project0c908882009-03-03 19:32:16 -08001572 // decide whether to show the share link option
1573 PackageManager pm = getPackageManager();
1574 Intent send = new Intent(Intent.ACTION_SEND);
1575 send.setType("text/plain");
1576 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1577 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1578
The Android Open Source Project0c908882009-03-03 19:32:16 -08001579 boolean isNavDump = mSettings.isNavDump();
1580 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1581 nav.setVisible(isNavDump);
1582 nav.setEnabled(isNavDump);
1583 break;
1584 }
1585 mCurrentMenuState = mMenuState;
1586 return true;
1587 }
1588
1589 @Override
1590 public void onCreateContextMenu(ContextMenu menu, View v,
1591 ContextMenuInfo menuInfo) {
1592 WebView webview = (WebView) v;
1593 WebView.HitTestResult result = webview.getHitTestResult();
1594 if (result == null) {
1595 return;
1596 }
1597
1598 int type = result.getType();
1599 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1600 Log.w(LOGTAG,
1601 "We should not show context menu when nothing is touched");
1602 return;
1603 }
1604 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1605 // let TextView handles context menu
1606 return;
1607 }
1608
1609 // Note, http://b/issue?id=1106666 is requesting that
1610 // an inflated menu can be used again. This is not available
1611 // yet, so inflate each time (yuk!)
1612 MenuInflater inflater = getMenuInflater();
1613 inflater.inflate(R.menu.browsercontext, menu);
1614
1615 // Show the correct menu group
1616 String extra = result.getExtra();
1617 menu.setGroupVisible(R.id.PHONE_MENU,
1618 type == WebView.HitTestResult.PHONE_TYPE);
1619 menu.setGroupVisible(R.id.EMAIL_MENU,
1620 type == WebView.HitTestResult.EMAIL_TYPE);
1621 menu.setGroupVisible(R.id.GEO_MENU,
1622 type == WebView.HitTestResult.GEO_TYPE);
1623 menu.setGroupVisible(R.id.IMAGE_MENU,
1624 type == WebView.HitTestResult.IMAGE_TYPE
1625 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1626 menu.setGroupVisible(R.id.ANCHOR_MENU,
1627 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1628 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1629
1630 // Setup custom handling depending on the type
1631 switch (type) {
1632 case WebView.HitTestResult.PHONE_TYPE:
1633 menu.setHeaderTitle(Uri.decode(extra));
1634 menu.findItem(R.id.dial_context_menu_id).setIntent(
1635 new Intent(Intent.ACTION_VIEW, Uri
1636 .parse(WebView.SCHEME_TEL + extra)));
1637 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1638 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001639 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001640 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1641 addIntent);
1642 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1643 new Copy(extra));
1644 break;
1645
1646 case WebView.HitTestResult.EMAIL_TYPE:
1647 menu.setHeaderTitle(extra);
1648 menu.findItem(R.id.email_context_menu_id).setIntent(
1649 new Intent(Intent.ACTION_VIEW, Uri
1650 .parse(WebView.SCHEME_MAILTO + extra)));
1651 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1652 new Copy(extra));
1653 break;
1654
1655 case WebView.HitTestResult.GEO_TYPE:
1656 menu.setHeaderTitle(extra);
1657 menu.findItem(R.id.map_context_menu_id).setIntent(
1658 new Intent(Intent.ACTION_VIEW, Uri
1659 .parse(WebView.SCHEME_GEO
1660 + URLEncoder.encode(extra))));
1661 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1662 new Copy(extra));
1663 break;
1664
1665 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1666 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1667 TextView titleView = (TextView) LayoutInflater.from(this)
1668 .inflate(android.R.layout.browser_link_context_header,
1669 null);
1670 titleView.setText(extra);
1671 menu.setHeaderView(titleView);
1672 // decide whether to show the open link in new tab option
1673 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001674 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001675 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1676 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001677 PackageManager pm = getPackageManager();
1678 Intent send = new Intent(Intent.ACTION_SEND);
1679 send.setType("text/plain");
1680 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1681 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1682 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1683 break;
1684 }
1685 // otherwise fall through to handle image part
1686 case WebView.HitTestResult.IMAGE_TYPE:
1687 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1688 menu.setHeaderTitle(extra);
1689 }
1690 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1691 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1692 menu.findItem(R.id.download_context_menu_id).
1693 setOnMenuItemClickListener(new Download(extra));
1694 break;
1695
1696 default:
1697 Log.w(LOGTAG, "We should not get here.");
1698 break;
1699 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001700 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001701 }
1702
The Android Open Source Project0c908882009-03-03 19:32:16 -08001703 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001704 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001705 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001706 // Attach the container that contains the main WebView and any other UI
1707 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001708 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001709
1710 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001711 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001712 if (errorConsole.numberOfErrors() == 0) {
1713 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1714 } else {
1715 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1716 }
1717
1718 mErrorConsoleContainer.addView(errorConsole,
1719 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1720 ViewGroup.LayoutParams.WRAP_CONTENT));
1721 }
1722
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001723 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001724 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001725 // Request focus on the top window.
1726 t.getTopWindow().requestFocus();
1727 }
1728
1729 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001730 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001731 t.attachSubWindow(mContentView);
1732 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001733 }
1734
1735 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001736 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001737 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001738 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001739
Grace Kloba22ac16e2009-10-07 18:00:23 -07001740 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1741 if (errorConsole != null) {
1742 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001743 }
1744
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001745 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001746 if (view != null) {
1747 view.setEmbeddedTitleBar(null);
1748 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001749 }
1750
1751 // Remove the sub window if it exists. Also called by TabControl when the
1752 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001753 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001754 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001755 // dismiss the subwindow. This will destroy the WebView.
1756 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001757 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001758 }
1759
Leon Scroggins1f005d32009-08-10 17:36:42 -04001760 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001761 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001762 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001763 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001764 }
1765
1766 // This method does a ton of stuff. It will attempt to create a new tab
1767 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001768 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001769 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1770 String appId) {
1771 final Tab currentTab = mTabControl.getCurrentTab();
1772 if (mTabControl.canCreateNewTab()) {
1773 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1774 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001775 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001776 // If the last tab was removed from the active tabs page, currentTab
1777 // will be null.
1778 if (currentTab != null) {
1779 removeTabFromContentView(currentTab);
1780 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001781 // We must set the new tab as the current tab to reflect the old
1782 // animation behavior.
1783 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001784 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001785 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001786 urlData.loadIn(webview);
1787 }
1788 return tab;
1789 } else {
1790 // Get rid of the subwindow if it exists
1791 dismissSubWindow(currentTab);
1792 if (!urlData.isEmpty()) {
1793 // Load the given url.
1794 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001795 }
1796 }
Grace Klobac9181842009-04-14 08:53:22 -07001797 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001798 }
1799
Grace Kloba22ac16e2009-10-07 18:00:23 -07001800 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001801 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001802 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001803 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001804 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001805 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001806 }
Grace Klobac9181842009-04-14 08:53:22 -07001807 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001808 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001809 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001810 }
1811 }
1812
1813 private class Copy implements OnMenuItemClickListener {
1814 private CharSequence mText;
1815
1816 public boolean onMenuItemClick(MenuItem item) {
1817 copy(mText);
1818 return true;
1819 }
1820
1821 public Copy(CharSequence toCopy) {
1822 mText = toCopy;
1823 }
1824 }
1825
1826 private class Download implements OnMenuItemClickListener {
1827 private String mText;
1828
1829 public boolean onMenuItemClick(MenuItem item) {
1830 onDownloadStartNoStream(mText, null, null, null, -1);
1831 return true;
1832 }
1833
1834 public Download(String toDownload) {
1835 mText = toDownload;
1836 }
1837 }
1838
1839 private void copy(CharSequence text) {
1840 try {
1841 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1842 if (clip != null) {
1843 clip.setClipboardText(text);
1844 }
1845 } catch (android.os.RemoteException e) {
1846 Log.e(LOGTAG, "Copy failed", e);
1847 }
1848 }
1849
1850 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001851 * Resets the browser title-view to whatever it must be
1852 * (for example, if we had a loading error)
1853 * When we have a new page, we call resetTitle, when we
1854 * have to reset the titlebar to whatever it used to be
1855 * (for example, if the user chose to stop loading), we
1856 * call resetTitleAndRevertLockIcon.
1857 */
1858 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001859 mTabControl.getCurrentTab().revertLockIcon();
1860 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001861 resetTitleIconAndProgress();
1862 }
1863
1864 /**
1865 * Reset the title, favicon, and progress.
1866 */
1867 private void resetTitleIconAndProgress() {
1868 WebView current = mTabControl.getCurrentWebView();
1869 if (current == null) {
1870 return;
1871 }
1872 resetTitleAndIcon(current);
1873 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001874 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001875 }
1876
1877 // Reset the title and the icon based on the given item.
1878 private void resetTitleAndIcon(WebView view) {
1879 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1880 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001881 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001882 setFavicon(item.getFavicon());
1883 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001884 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001885 setFavicon(null);
1886 }
1887 }
1888
1889 /**
1890 * Sets a title composed of the URL and the title string.
1891 * @param url The URL of the site being loaded.
1892 * @param title The title of the site being loaded.
1893 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001894 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001895 mUrl = url;
1896 mTitle = title;
1897
Leon Scroggins68579392009-09-15 15:31:54 -04001898 mTitleBar.setTitleAndUrl(title, url);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001899 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001900 }
1901
1902 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001903 * @param url The URL to build a title version of the URL from.
1904 * @return The title version of the URL or null if fails.
1905 * The title version of the URL can be either the URL hostname,
1906 * or the hostname with an "https://" prefix (for secure URLs),
1907 * or an empty string if, for example, the URL in question is a
1908 * file:// URL with no hostname.
1909 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001910 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001911 String titleUrl = null;
1912
1913 if (url != null) {
1914 try {
1915 // parse the url string
1916 URL urlObj = new URL(url);
1917 if (urlObj != null) {
1918 titleUrl = "";
1919
1920 String protocol = urlObj.getProtocol();
1921 String host = urlObj.getHost();
1922
1923 if (host != null && 0 < host.length()) {
1924 titleUrl = host;
1925 if (protocol != null) {
1926 // if a secure site, add an "https://" prefix!
1927 if (protocol.equalsIgnoreCase("https")) {
1928 titleUrl = protocol + "://" + host;
1929 }
1930 }
1931 }
1932 }
1933 } catch (MalformedURLException e) {}
1934 }
1935
1936 return titleUrl;
1937 }
1938
1939 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001940 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04001941 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001942 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001943 }
1944
1945 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001946 * Close the tab, remove its associated title bar, and adjust mTabControl's
1947 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001948 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001949 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001950 int currentIndex = mTabControl.getCurrentIndex();
1951 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001952 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001953 if (currentIndex >= removeIndex && currentIndex != 0) {
1954 currentIndex--;
1955 }
1956 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01001957 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001958 }
1959
1960 private void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001961 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001962 if (current == null) {
1963 /*
1964 * Instead of finishing the activity, simply push this to the back
1965 * of the stack and let ActivityManager to choose the foreground
1966 * activity. As BrowserActivity is singleTask, it will be always the
1967 * root of the task. So we can use either true or false for
1968 * moveTaskToBack().
1969 */
1970 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07001971 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001972 }
1973 WebView w = current.getWebView();
1974 if (w.canGoBack()) {
1975 w.goBack();
1976 } else {
1977 // Check to see if we are closing a window that was created by
1978 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001979 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001980 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001981 switchToTab(mTabControl.getTabIndex(parent));
1982 // Now we close the other tab
1983 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001984 } else {
1985 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001986 // force the tab's inLoad() to be false as we are going to
1987 // either finish the activity or remove the tab. This will
1988 // ensure pauseWebViewTimers() taking action.
1989 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001990 if (mTabControl.getTabCount() == 1) {
1991 finish();
1992 return;
1993 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04001994 // call pauseWebViewTimers() now, we won't be able to call
1995 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07001996 // Temporarily change mActivityInPause to be true as
1997 // pauseWebViewTimers() will do nothing if mActivityInPause
1998 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07001999 boolean savedState = mActivityInPause;
2000 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002001 Log.e(LOGTAG, "BrowserActivity is already paused "
2002 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002003 }
2004 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002005 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002006 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002007 removeTabFromContentView(current);
2008 mTabControl.removeTab(current);
2009 }
2010 /*
2011 * Instead of finishing the activity, simply push this to the back
2012 * of the stack and let ActivityManager to choose the foreground
2013 * activity. As BrowserActivity is singleTask, it will be always the
2014 * root of the task. So we can use either true or false for
2015 * moveTaskToBack().
2016 */
2017 moveTaskToBack(true);
2018 }
2019 }
2020 }
2021
Grace Kloba22ac16e2009-10-07 18:00:23 -07002022 boolean isMenuDown() {
2023 return mMenuIsDown;
2024 }
2025
Grace Kloba5942df02009-09-18 11:48:29 -07002026 @Override
2027 public boolean onKeyDown(int keyCode, KeyEvent event) {
2028 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2029 // still down, we don't want to trigger the search. Pretend to consume
2030 // the key and do nothing.
2031 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002032
Grace Kloba5942df02009-09-18 11:48:29 -07002033 switch(keyCode) {
2034 case KeyEvent.KEYCODE_MENU:
2035 mMenuIsDown = true;
2036 break;
2037 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002038 // WebView/WebTextView handle the keys in the KeyDown. As
2039 // the Activity's shortcut keys are only handled when WebView
2040 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2041 if (event.isShiftPressed()) {
2042 getTopWindow().pageUp(false);
2043 } else {
2044 getTopWindow().pageDown(false);
2045 }
Grace Kloba5942df02009-09-18 11:48:29 -07002046 return true;
2047 case KeyEvent.KEYCODE_BACK:
2048 if (event.getRepeatCount() == 0) {
2049 event.startTracking();
2050 return true;
2051 } else if (mCustomView == null && mActiveTabsPage == null
2052 && event.isLongPress()) {
2053 bookmarksOrHistoryPicker(true);
2054 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002055 }
Grace Kloba5942df02009-09-18 11:48:29 -07002056 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002057 }
Grace Kloba5942df02009-09-18 11:48:29 -07002058 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002059 }
2060
Grace Kloba5942df02009-09-18 11:48:29 -07002061 @Override
2062 public boolean onKeyUp(int keyCode, KeyEvent event) {
2063 switch(keyCode) {
2064 case KeyEvent.KEYCODE_MENU:
2065 mMenuIsDown = false;
2066 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002067 case KeyEvent.KEYCODE_BACK:
2068 if (event.isTracking() && !event.isCanceled()) {
2069 if (mCustomView != null) {
2070 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002071 mTabControl.getCurrentWebView().getWebChromeClient()
2072 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002073 } else if (mActiveTabsPage != null) {
2074 // if tab page is showing, hide it
2075 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002076 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002077 WebView subwindow = mTabControl.getCurrentSubWindow();
2078 if (subwindow != null) {
2079 if (subwindow.canGoBack()) {
2080 subwindow.goBack();
2081 } else {
2082 dismissSubWindow(mTabControl.getCurrentTab());
2083 }
2084 } else {
2085 goBackOnePageOrQuit();
2086 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002087 }
Grace Kloba5942df02009-09-18 11:48:29 -07002088 return true;
2089 }
2090 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002091 }
Grace Kloba5942df02009-09-18 11:48:29 -07002092 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002093 }
2094
Leon Scroggins68579392009-09-15 15:31:54 -04002095 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002096 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002097 resetTitleAndRevertLockIcon();
2098 WebView w = getTopWindow();
2099 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002100 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2101 // same logic here. But for subwindow case, should we call into the main
2102 // WebView's onPageFinished as we never call its onPageStarted and if
2103 // the page finishes itself, we don't call onPageFinished.
2104 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2105 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002106
2107 cancelStopToast();
2108 mStopToast = Toast
2109 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2110 mStopToast.show();
2111 }
2112
Grace Kloba22ac16e2009-10-07 18:00:23 -07002113 boolean didUserStopLoading() {
2114 return mDidStopLoad;
2115 }
2116
The Android Open Source Project0c908882009-03-03 19:32:16 -08002117 private void cancelStopToast() {
2118 if (mStopToast != null) {
2119 mStopToast.cancel();
2120 mStopToast = null;
2121 }
2122 }
2123
Grace Kloba22ac16e2009-10-07 18:00:23 -07002124 // called by a UI or non-UI thread to post the message
2125 public void postMessage(int what, int arg1, int arg2, Object obj,
2126 long delayMillis) {
2127 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2128 obj), delayMillis);
2129 }
2130
2131 // called by a UI or non-UI thread to remove the message
2132 void removeMessages(int what, Object object) {
2133 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002134 }
2135
2136 // public message ids
2137 public final static int LOAD_URL = 1001;
2138 public final static int STOP_LOAD = 1002;
2139
2140 // Message Ids
2141 private static final int FOCUS_NODE_HREF = 102;
2142 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002143 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002144
Grace Kloba22ac16e2009-10-07 18:00:23 -07002145 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002146
The Android Open Source Project0c908882009-03-03 19:32:16 -08002147 // Private handler for handling javascript and saving passwords
2148 private Handler mHandler = new Handler() {
2149
2150 public void handleMessage(Message msg) {
2151 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002152 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002153 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002154 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002155 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002156 if (url == null || url.length() == 0) {
2157 break;
2158 }
2159 HashMap focusNodeMap = (HashMap) msg.obj;
2160 WebView view = (WebView) focusNodeMap.get("webview");
2161 // Only apply the action if the top window did not change.
2162 if (getTopWindow() != view) {
2163 break;
2164 }
2165 switch (msg.arg1) {
2166 case R.id.open_context_menu_id:
2167 case R.id.view_image_context_menu_id:
2168 loadURL(getTopWindow(), url);
2169 break;
2170 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002171 final Tab parent = mTabControl.getCurrentTab();
2172 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002173 if (newTab != parent) {
2174 parent.addChildTab(newTab);
2175 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002176 break;
2177 case R.id.bookmark_context_menu_id:
2178 Intent intent = new Intent(BrowserActivity.this,
2179 AddBookmarkPage.class);
2180 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002181 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002182 startActivity(intent);
2183 break;
2184 case R.id.share_link_context_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01002185 Browser.sendString(BrowserActivity.this, url,
2186 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002187 break;
2188 case R.id.copy_link_context_menu_id:
2189 copy(url);
2190 break;
2191 case R.id.save_link_context_menu_id:
2192 case R.id.download_context_menu_id:
2193 onDownloadStartNoStream(url, null, null, null, -1);
2194 break;
2195 }
2196 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002197 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002198
2199 case LOAD_URL:
2200 loadURL(getTopWindow(), (String) msg.obj);
2201 break;
2202
2203 case STOP_LOAD:
2204 stopLoading();
2205 break;
2206
2207 case CANCEL_CREDS_REQUEST:
2208 resumeAfterCredentials();
2209 break;
2210
The Android Open Source Project0c908882009-03-03 19:32:16 -08002211 case RELEASE_WAKELOCK:
2212 if (mWakeLock.isHeld()) {
2213 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002214 // if we reach here, Browser should be still in the
2215 // background loading after WAKELOCK_TIMEOUT (5-min).
2216 // To avoid burning the battery, stop loading.
2217 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002218 }
2219 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002220
2221 case UPDATE_BOOKMARK_THUMBNAIL:
2222 WebView view = (WebView) msg.obj;
2223 if (view != null) {
2224 updateScreenshot(view);
2225 }
2226 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002227 }
2228 }
2229 };
2230
Leon Scroggins89c6d362009-07-15 16:54:37 -04002231 private void updateScreenshot(WebView view) {
2232 // If this is a bookmarked site, add a screenshot to the database.
2233 // FIXME: When should we update? Every time?
2234 // FIXME: Would like to make sure there is actually something to
2235 // draw, but the API for that (WebViewCore.pictureReady()) is not
2236 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002237
Patrick Scott3918d442009-08-04 13:22:29 -04002238 ContentResolver cr = getContentResolver();
2239 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002240 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002241 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002242 boolean succeed = c.moveToFirst();
2243 ContentValues values = null;
2244 while (succeed) {
2245 if (values == null) {
2246 final ByteArrayOutputStream os
2247 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002248 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002249 if (bm == null) {
2250 c.close();
2251 return;
2252 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002253 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2254 values = new ContentValues();
2255 values.put(Browser.BookmarkColumns.THUMBNAIL,
2256 os.toByteArray());
2257 }
2258 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2259 c.getInt(0)), values, null, null);
2260 succeed = c.moveToNext();
2261 }
2262 c.close();
2263 }
2264 }
2265
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002266 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002267 * Values for the size of the thumbnail created when taking a screenshot.
2268 * Lazily initialized. Instead of using these directly, use
2269 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002270 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002271 private static int THUMBNAIL_WIDTH = 0;
2272 private static int THUMBNAIL_HEIGHT = 0;
2273
2274 /**
2275 * Return the desired width for thumbnail screenshots, which are stored in
2276 * the database, and used on the bookmarks screen.
2277 * @param context Context for finding out the density of the screen.
2278 * @return int desired width for thumbnail screenshot.
2279 */
2280 /* package */ static int getDesiredThumbnailWidth(Context context) {
2281 if (THUMBNAIL_WIDTH == 0) {
2282 float density = context.getResources().getDisplayMetrics().density;
2283 THUMBNAIL_WIDTH = (int) (90 * density);
2284 THUMBNAIL_HEIGHT = (int) (80 * density);
2285 }
2286 return THUMBNAIL_WIDTH;
2287 }
2288
2289 /**
2290 * Return the desired height for thumbnail screenshots, which are stored in
2291 * the database, and used on the bookmarks screen.
2292 * @param context Context for finding out the density of the screen.
2293 * @return int desired height for thumbnail screenshot.
2294 */
2295 /* package */ static int getDesiredThumbnailHeight(Context context) {
2296 // To ensure that they are both initialized.
2297 getDesiredThumbnailWidth(context);
2298 return THUMBNAIL_HEIGHT;
2299 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002300
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002301 private Bitmap createScreenshot(WebView view) {
2302 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002303 if (thumbnail == null) {
2304 return null;
2305 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002306 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2307 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002308 Canvas canvas = new Canvas(bm);
2309 // May need to tweak these values to determine what is the
2310 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002311 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002312 int thumbnailHeight = thumbnail.getHeight();
2313 float scaleFactorX = 1.0f;
2314 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002315 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002316 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002317 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002318 } else {
2319 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002320 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002321
2322 if (view.getWidth() > view.getHeight() &&
2323 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2324 // If the device is in landscape and the page is shorter
2325 // than the height of the view, stretch the thumbnail to fill the
2326 // space.
2327 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2328 (float)thumbnailHeight;
2329 } else {
2330 // In the portrait case, this looks nice.
2331 scaleFactorY = scaleFactorX;
2332 }
2333
2334 canvas.scale(scaleFactorX, scaleFactorY);
2335
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002336 thumbnail.draw(canvas);
2337 return bm;
2338 }
2339
The Android Open Source Project0c908882009-03-03 19:32:16 -08002340 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002341 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002342 //-------------------------------------------------------------------------
2343
2344 // Use in overrideUrlLoading
2345 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2346 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2347 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2348 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2349
Grace Kloba22ac16e2009-10-07 18:00:23 -07002350 void onPageStarted(WebView view, String url, Bitmap favicon) {
2351 // when BrowserActivity just starts, onPageStarted may be called before
2352 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2353 // to start the timer. As we won't switch tabs while an activity is in
2354 // pause state, we can ensure calling resume and pause in pair.
2355 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002356
Grace Kloba22ac16e2009-10-07 18:00:23 -07002357 resetLockIcon(url);
2358 setUrlTitle(url, null);
2359 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002360 // Keep this initial progress in sync with initialProgressValue (* 100)
2361 // in ProgressTracker.cpp
2362 // Show some progress so that the user knows the page is beginning to
2363 // load
2364 onProgressChanged(view, 10);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002365 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002366 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002367
Grace Kloba22ac16e2009-10-07 18:00:23 -07002368 if (mSettings.isTracing()) {
2369 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002370 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002371 WebAddress uri = new WebAddress(url);
2372 host = uri.mHost;
2373 } catch (android.net.ParseException ex) {
2374 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002375 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002376 host = host.replace('.', '_');
2377 host += ".trace";
2378 mInTrace = true;
2379 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2380 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002381
Grace Kloba22ac16e2009-10-07 18:00:23 -07002382 // Performance probe
2383 if (false) {
2384 mStart = SystemClock.uptimeMillis();
2385 mProcessStart = Process.getElapsedCpuTime();
2386 long[] sysCpu = new long[7];
2387 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2388 sysCpu, null)) {
2389 mUserStart = sysCpu[0] + sysCpu[1];
2390 mSystemStart = sysCpu[2];
2391 mIdleStart = sysCpu[3];
2392 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2393 }
2394 mUiStart = SystemClock.currentThreadTimeMillis();
2395 }
2396 }
2397
2398 void onPageFinished(WebView view, String url) {
2399 // Reset the title and icon in case we stopped a provisional load.
2400 resetTitleAndIcon(view);
2401 // Update the lock icon image only once we are done loading
2402 updateLockIconToLatest();
2403 // pause the WebView timer and release the wake lock if it is finished
2404 // while BrowserActivity is in pause state.
2405 if (mActivityInPause && pauseWebViewTimers()) {
2406 if (mWakeLock.isHeld()) {
2407 mHandler.removeMessages(RELEASE_WAKELOCK);
2408 mWakeLock.release();
2409 }
2410 }
2411
2412 // Performance probe
2413 if (false) {
2414 long[] sysCpu = new long[7];
2415 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2416 sysCpu, null)) {
2417 String uiInfo = "UI thread used "
2418 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2419 + " ms";
2420 if (LOGD_ENABLED) {
2421 Log.d(LOGTAG, uiInfo);
2422 }
2423 //The string that gets written to the log
2424 String performanceString = "It took total "
2425 + (SystemClock.uptimeMillis() - mStart)
2426 + " ms clock time to load the page."
2427 + "\nbrowser process used "
2428 + (Process.getElapsedCpuTime() - mProcessStart)
2429 + " ms, user processes used "
2430 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2431 + " ms, kernel used "
2432 + (sysCpu[2] - mSystemStart) * 10
2433 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2434 + " ms and irq took "
2435 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2436 * 10 + " ms, " + uiInfo;
2437 if (LOGD_ENABLED) {
2438 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2439 }
2440 if (url != null) {
2441 // strip the url to maintain consistency
2442 String newUrl = new String(url);
2443 if (newUrl.startsWith("http://www.")) {
2444 newUrl = newUrl.substring(11);
2445 } else if (newUrl.startsWith("http://")) {
2446 newUrl = newUrl.substring(7);
2447 } else if (newUrl.startsWith("https://www.")) {
2448 newUrl = newUrl.substring(12);
2449 } else if (newUrl.startsWith("https://")) {
2450 newUrl = newUrl.substring(8);
2451 }
2452 if (LOGD_ENABLED) {
2453 Log.d(LOGTAG, newUrl + " loaded");
2454 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002455 }
2456 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002457 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002458
Grace Kloba22ac16e2009-10-07 18:00:23 -07002459 if (mInTrace) {
2460 mInTrace = false;
2461 Debug.stopMethodTracing();
2462 }
2463 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002464
Grace Kloba22ac16e2009-10-07 18:00:23 -07002465 boolean shouldOverrideUrlLoading(WebView view, String url) {
2466 if (url.startsWith(SCHEME_WTAI)) {
2467 // wtai://wp/mc;number
2468 // number=string(phone-number)
2469 if (url.startsWith(SCHEME_WTAI_MC)) {
2470 Intent intent = new Intent(Intent.ACTION_VIEW,
2471 Uri.parse(WebView.SCHEME_TEL +
2472 url.substring(SCHEME_WTAI_MC.length())));
2473 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002474 return true;
2475 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002476 // wtai://wp/sd;dtmf
2477 // dtmf=string(dialstring)
2478 if (url.startsWith(SCHEME_WTAI_SD)) {
2479 // TODO: only send when there is active voice connection
2480 return false;
2481 }
2482 // wtai://wp/ap;number;name
2483 // number=string(phone-number)
2484 // name=string
2485 if (url.startsWith(SCHEME_WTAI_AP)) {
2486 // TODO
2487 return false;
2488 }
2489 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002490
Grace Kloba22ac16e2009-10-07 18:00:23 -07002491 // The "about:" schemes are internal to the browser; don't want these to
2492 // be dispatched to other apps.
2493 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002494 return false;
2495 }
2496
Grace Kloba22ac16e2009-10-07 18:00:23 -07002497 Intent intent;
2498 // perform generic parsing of the URI to turn it into an Intent.
2499 try {
2500 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2501 } catch (URISyntaxException ex) {
2502 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2503 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002504 }
2505
Grace Kloba22ac16e2009-10-07 18:00:23 -07002506 // check whether the intent can be resolved. If not, we will see
2507 // whether we can download it from the Market.
2508 if (getPackageManager().resolveActivity(intent, 0) == null) {
2509 String packagename = intent.getPackage();
2510 if (packagename != null) {
2511 intent = new Intent(Intent.ACTION_VIEW, Uri
2512 .parse("market://search?q=pname:" + packagename));
2513 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2514 startActivity(intent);
2515 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002516 } else {
2517 return false;
2518 }
2519 }
2520
Grace Kloba22ac16e2009-10-07 18:00:23 -07002521 // sanitize the Intent, ensuring web pages can not bypass browser
2522 // security (only access to BROWSABLE activities).
2523 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2524 intent.setComponent(null);
2525 try {
2526 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002527 return true;
2528 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002529 } catch (ActivityNotFoundException ex) {
2530 // ignore the error. If no application can handle the URL,
2531 // eg about:blank, assume the browser can handle it.
2532 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002533
Grace Kloba22ac16e2009-10-07 18:00:23 -07002534 if (mMenuIsDown) {
2535 openTab(url);
2536 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002537 return true;
2538 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002539 return false;
2540 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002541
Grace Kloba22ac16e2009-10-07 18:00:23 -07002542 // -------------------------------------------------------------------------
2543 // Helper function for WebChromeClient
2544 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002545
Grace Kloba22ac16e2009-10-07 18:00:23 -07002546 void onProgressChanged(WebView view, int newProgress) {
2547 mTitleBar.setProgress(newProgress);
2548 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002549
Grace Kloba22ac16e2009-10-07 18:00:23 -07002550 if (newProgress == 100) {
2551 // onProgressChanged() may continue to be called after the main
2552 // frame has finished loading, as any remaining sub frames continue
2553 // to load. We'll only get called once though with newProgress as
2554 // 100 when everything is loaded. (onPageFinished is called once
2555 // when the main frame completes loading regardless of the state of
2556 // any sub frames so calls to onProgressChanges may continue after
2557 // onPageFinished has executed)
2558 if (mInLoad) {
2559 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002560 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002561 // If the options menu is open, leave the title bar
2562 if (!mOptionsMenuOpen || !mIconView) {
2563 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002564 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002565 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002566 } else if (!mInLoad) {
2567 // onPageFinished may have already been called but a subframe is
2568 // still loading and updating the progress. Reset mInLoad and update
2569 // the menu items.
2570 mInLoad = true;
2571 updateInLoadMenuItems();
2572 if (!mOptionsMenuOpen || mIconView) {
2573 // This page has begun to load, so show the title bar
2574 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002575 }
2576 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002577 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002578
Grace Kloba22ac16e2009-10-07 18:00:23 -07002579 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2580 if (mCustomView != null)
2581 return;
2582
2583 // Add the custom view to its container.
2584 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2585 mCustomView = view;
2586 mCustomViewCallback = callback;
2587 // Save the menu state and set it to empty while the custom
2588 // view is showing.
2589 mOldMenuState = mMenuState;
2590 mMenuState = EMPTY_MENU;
2591 // Hide the content view.
2592 mContentView.setVisibility(View.GONE);
2593 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002594 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002595 mCustomViewContainer.setVisibility(View.VISIBLE);
2596 mCustomViewContainer.bringToFront();
2597 }
2598
2599 void onHideCustomView() {
2600 if (mCustomView == null)
2601 return;
2602
2603 // Hide the custom view.
2604 mCustomView.setVisibility(View.GONE);
2605 // Remove the custom view from its container.
2606 mCustomViewContainer.removeView(mCustomView);
2607 mCustomView = null;
2608 // Reset the old menu state.
2609 mMenuState = mOldMenuState;
2610 mOldMenuState = EMPTY_MENU;
2611 mCustomViewContainer.setVisibility(View.GONE);
2612 mCustomViewCallback.onCustomViewHidden();
2613 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002614 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002615 mContentView.setVisibility(View.VISIBLE);
2616 }
2617
2618 Bitmap getDefaultVideoPoster() {
2619 if (mDefaultVideoPoster == null) {
2620 mDefaultVideoPoster = BitmapFactory.decodeResource(
2621 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002622 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002623 return mDefaultVideoPoster;
2624 }
Patrick Scott3918d442009-08-04 13:22:29 -04002625
Grace Kloba22ac16e2009-10-07 18:00:23 -07002626 View getVideoLoadingProgressView() {
2627 if (mVideoProgressView == null) {
2628 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2629 mVideoProgressView = inflater.inflate(
2630 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002631 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002632 return mVideoProgressView;
2633 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002634
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002635 /*
2636 * The Object used to inform the WebView of the file to upload.
2637 */
2638 private ValueCallback<Uri> mUploadMessage;
2639
Grace Kloba22ac16e2009-10-07 18:00:23 -07002640 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2641 if (mUploadMessage != null) return;
2642 mUploadMessage = uploadMsg;
2643 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2644 i.addCategory(Intent.CATEGORY_OPENABLE);
2645 i.setType("*/*");
2646 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2647 getString(R.string.choose_upload)), FILE_SELECTED);
2648 }
2649
2650 // -------------------------------------------------------------------------
2651 // Implement functions for DownloadListener
2652 // -------------------------------------------------------------------------
2653
The Android Open Source Project0c908882009-03-03 19:32:16 -08002654 /**
2655 * Notify the host application a download should be done, or that
2656 * the data should be streamed if a streaming viewer is available.
2657 * @param url The full url to the content that should be downloaded
2658 * @param contentDisposition Content-disposition http header, if
2659 * present.
2660 * @param mimetype The mimetype of the content reported by the server
2661 * @param contentLength The file size reported by the server
2662 */
2663 public void onDownloadStart(String url, String userAgent,
2664 String contentDisposition, String mimetype, long contentLength) {
2665 // if we're dealing wih A/V content that's not explicitly marked
2666 // for download, check if it's streamable.
2667 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002668 || !contentDisposition.regionMatches(
2669 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002670 // query the package manager to see if there's a registered handler
2671 // that matches.
2672 Intent intent = new Intent(Intent.ACTION_VIEW);
2673 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002674 ResolveInfo info = getPackageManager().resolveActivity(intent,
2675 PackageManager.MATCH_DEFAULT_ONLY);
2676 if (info != null) {
2677 ComponentName myName = getComponentName();
2678 // If we resolved to ourselves, we don't want to attempt to
2679 // load the url only to try and download it again.
2680 if (!myName.getPackageName().equals(
2681 info.activityInfo.packageName)
2682 || !myName.getClassName().equals(
2683 info.activityInfo.name)) {
2684 // someone (other than us) knows how to handle this mime
2685 // type with this scheme, don't download.
2686 try {
2687 startActivity(intent);
2688 return;
2689 } catch (ActivityNotFoundException ex) {
2690 if (LOGD_ENABLED) {
2691 Log.d(LOGTAG, "activity not found for " + mimetype
2692 + " over " + Uri.parse(url).getScheme(),
2693 ex);
2694 }
2695 // Best behavior is to fall back to a download in this
2696 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002697 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002698 }
2699 }
2700 }
2701 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2702 }
2703
2704 /**
2705 * Notify the host application a download should be done, even if there
2706 * is a streaming viewer available for thise type.
2707 * @param url The full url to the content that should be downloaded
2708 * @param contentDisposition Content-disposition http header, if
2709 * present.
2710 * @param mimetype The mimetype of the content reported by the server
2711 * @param contentLength The file size reported by the server
2712 */
2713 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2714 String contentDisposition, String mimetype, long contentLength) {
2715
2716 String filename = URLUtil.guessFileName(url,
2717 contentDisposition, mimetype);
2718
2719 // Check to see if we have an SDCard
2720 String status = Environment.getExternalStorageState();
2721 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2722 int title;
2723 String msg;
2724
2725 // Check to see if the SDCard is busy, same as the music app
2726 if (status.equals(Environment.MEDIA_SHARED)) {
2727 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2728 title = R.string.download_sdcard_busy_dlg_title;
2729 } else {
2730 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2731 title = R.string.download_no_sdcard_dlg_title;
2732 }
2733
2734 new AlertDialog.Builder(this)
2735 .setTitle(title)
2736 .setIcon(android.R.drawable.ic_dialog_alert)
2737 .setMessage(msg)
2738 .setPositiveButton(R.string.ok, null)
2739 .show();
2740 return;
2741 }
2742
2743 // java.net.URI is a lot stricter than KURL so we have to undo
2744 // KURL's percent-encoding and redo the encoding using java.net.URI.
2745 URI uri = null;
2746 try {
2747 // Undo the percent-encoding that KURL may have done.
2748 String newUrl = new String(URLUtil.decode(url.getBytes()));
2749 // Parse the url into pieces
2750 WebAddress w = new WebAddress(newUrl);
2751 String frag = null;
2752 String query = null;
2753 String path = w.mPath;
2754 // Break the path into path, query, and fragment
2755 if (path.length() > 0) {
2756 // Strip the fragment
2757 int idx = path.lastIndexOf('#');
2758 if (idx != -1) {
2759 frag = path.substring(idx + 1);
2760 path = path.substring(0, idx);
2761 }
2762 idx = path.lastIndexOf('?');
2763 if (idx != -1) {
2764 query = path.substring(idx + 1);
2765 path = path.substring(0, idx);
2766 }
2767 }
2768 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2769 query, frag);
2770 } catch (Exception e) {
2771 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2772 return;
2773 }
2774
2775 // XXX: Have to use the old url since the cookies were stored using the
2776 // old percent-encoded url.
2777 String cookies = CookieManager.getInstance().getCookie(url);
2778
2779 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002780 values.put(Downloads.COLUMN_URI, uri.toString());
2781 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
2782 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
2783 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002784 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002785 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002786 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002787 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2788 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
2789 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
2790 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002791 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002792 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002793 }
2794 if (mimetype == null) {
2795 // We must have long pressed on a link or image to download it. We
2796 // are not sure of the mimetype in this case, so do a head request
2797 new FetchUrlMimeType(this).execute(values);
2798 } else {
2799 final Uri contentUri =
2800 getContentResolver().insert(Downloads.CONTENT_URI, values);
2801 viewDownloads(contentUri);
2802 }
2803
2804 }
2805
Grace Kloba22ac16e2009-10-07 18:00:23 -07002806 // -------------------------------------------------------------------------
2807
The Android Open Source Project0c908882009-03-03 19:32:16 -08002808 /**
2809 * Resets the lock icon. This method is called when we start a new load and
2810 * know the url to be loaded.
2811 */
2812 private void resetLockIcon(String url) {
2813 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002814 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002815 updateLockIconImage(LOCK_ICON_UNSECURE);
2816 }
2817
The Android Open Source Project0c908882009-03-03 19:32:16 -08002818 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002819 * Update the lock icon to correspond to our latest state.
2820 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002821 private void updateLockIconToLatest() {
2822 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002823 }
2824
2825 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002826 * Updates the lock-icon image in the title-bar.
2827 */
2828 private void updateLockIconImage(int lockIconType) {
2829 Drawable d = null;
2830 if (lockIconType == LOCK_ICON_SECURE) {
2831 d = mSecLockIcon;
2832 } else if (lockIconType == LOCK_ICON_MIXED) {
2833 d = mMixLockIcon;
2834 }
Leon Scroggins68579392009-09-15 15:31:54 -04002835 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002836 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002837 }
2838
2839 /**
2840 * Displays a page-info dialog.
2841 * @param tab The tab to show info about
2842 * @param fromShowSSLCertificateOnError The flag that indicates whether
2843 * this dialog was opened from the SSL-certificate-on-error dialog or
2844 * not. This is important, since we need to know whether to return to
2845 * the parent dialog or simply dismiss.
2846 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002847 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002848 final boolean fromShowSSLCertificateOnError) {
2849 final LayoutInflater factory = LayoutInflater
2850 .from(this);
2851
2852 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2853
2854 final WebView view = tab.getWebView();
2855
2856 String url = null;
2857 String title = null;
2858
2859 if (view == null) {
2860 url = tab.getUrl();
2861 title = tab.getTitle();
2862 } else if (view == mTabControl.getCurrentWebView()) {
2863 // Use the cached title and url if this is the current WebView
2864 url = mUrl;
2865 title = mTitle;
2866 } else {
2867 url = view.getUrl();
2868 title = view.getTitle();
2869 }
2870
2871 if (url == null) {
2872 url = "";
2873 }
2874 if (title == null) {
2875 title = "";
2876 }
2877
2878 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
2879 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
2880
2881 mPageInfoView = tab;
2882 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
2883
2884 AlertDialog.Builder alertDialogBuilder =
2885 new AlertDialog.Builder(this)
2886 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
2887 .setView(pageInfoView)
2888 .setPositiveButton(
2889 R.string.ok,
2890 new DialogInterface.OnClickListener() {
2891 public void onClick(DialogInterface dialog,
2892 int whichButton) {
2893 mPageInfoDialog = null;
2894 mPageInfoView = null;
2895 mPageInfoFromShowSSLCertificateOnError = null;
2896
2897 // if we came here from the SSL error dialog
2898 if (fromShowSSLCertificateOnError) {
2899 // go back to the SSL error dialog
2900 showSSLCertificateOnError(
2901 mSSLCertificateOnErrorView,
2902 mSSLCertificateOnErrorHandler,
2903 mSSLCertificateOnErrorError);
2904 }
2905 }
2906 })
2907 .setOnCancelListener(
2908 new DialogInterface.OnCancelListener() {
2909 public void onCancel(DialogInterface dialog) {
2910 mPageInfoDialog = null;
2911 mPageInfoView = null;
2912 mPageInfoFromShowSSLCertificateOnError = null;
2913
2914 // if we came here from the SSL error dialog
2915 if (fromShowSSLCertificateOnError) {
2916 // go back to the SSL error dialog
2917 showSSLCertificateOnError(
2918 mSSLCertificateOnErrorView,
2919 mSSLCertificateOnErrorHandler,
2920 mSSLCertificateOnErrorError);
2921 }
2922 }
2923 });
2924
2925 // if we have a main top-level page SSL certificate set or a certificate
2926 // error
2927 if (fromShowSSLCertificateOnError ||
2928 (view != null && view.getCertificate() != null)) {
2929 // add a 'View Certificate' button
2930 alertDialogBuilder.setNeutralButton(
2931 R.string.view_certificate,
2932 new DialogInterface.OnClickListener() {
2933 public void onClick(DialogInterface dialog,
2934 int whichButton) {
2935 mPageInfoDialog = null;
2936 mPageInfoView = null;
2937 mPageInfoFromShowSSLCertificateOnError = null;
2938
2939 // if we came here from the SSL error dialog
2940 if (fromShowSSLCertificateOnError) {
2941 // go back to the SSL error dialog
2942 showSSLCertificateOnError(
2943 mSSLCertificateOnErrorView,
2944 mSSLCertificateOnErrorHandler,
2945 mSSLCertificateOnErrorError);
2946 } else {
2947 // otherwise, display the top-most certificate from
2948 // the chain
2949 if (view.getCertificate() != null) {
2950 showSSLCertificate(tab);
2951 }
2952 }
2953 }
2954 });
2955 }
2956
2957 mPageInfoDialog = alertDialogBuilder.show();
2958 }
2959
2960 /**
2961 * Displays the main top-level page SSL certificate dialog
2962 * (accessible from the Page-Info dialog).
2963 * @param tab The tab to show certificate for.
2964 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002965 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002966 final View certificateView =
2967 inflateCertificateView(tab.getWebView().getCertificate());
2968 if (certificateView == null) {
2969 return;
2970 }
2971
2972 LayoutInflater factory = LayoutInflater.from(this);
2973
2974 final LinearLayout placeholder =
2975 (LinearLayout)certificateView.findViewById(R.id.placeholder);
2976
2977 LinearLayout ll = (LinearLayout) factory.inflate(
2978 R.layout.ssl_success, placeholder);
2979 ((TextView)ll.findViewById(R.id.success))
2980 .setText(R.string.ssl_certificate_is_valid);
2981
2982 mSSLCertificateView = tab;
2983 mSSLCertificateDialog =
2984 new AlertDialog.Builder(this)
2985 .setTitle(R.string.ssl_certificate).setIcon(
2986 R.drawable.ic_dialog_browser_certificate_secure)
2987 .setView(certificateView)
2988 .setPositiveButton(R.string.ok,
2989 new DialogInterface.OnClickListener() {
2990 public void onClick(DialogInterface dialog,
2991 int whichButton) {
2992 mSSLCertificateDialog = null;
2993 mSSLCertificateView = null;
2994
2995 showPageInfo(tab, false);
2996 }
2997 })
2998 .setOnCancelListener(
2999 new DialogInterface.OnCancelListener() {
3000 public void onCancel(DialogInterface dialog) {
3001 mSSLCertificateDialog = null;
3002 mSSLCertificateView = null;
3003
3004 showPageInfo(tab, false);
3005 }
3006 })
3007 .show();
3008 }
3009
3010 /**
3011 * Displays the SSL error certificate dialog.
3012 * @param view The target web-view.
3013 * @param handler The SSL error handler responsible for cancelling the
3014 * connection that resulted in an SSL error or proceeding per user request.
3015 * @param error The SSL error object.
3016 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003017 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003018 final WebView view, final SslErrorHandler handler, final SslError error) {
3019
3020 final View certificateView =
3021 inflateCertificateView(error.getCertificate());
3022 if (certificateView == null) {
3023 return;
3024 }
3025
3026 LayoutInflater factory = LayoutInflater.from(this);
3027
3028 final LinearLayout placeholder =
3029 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3030
3031 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3032 LinearLayout ll = (LinearLayout)factory
3033 .inflate(R.layout.ssl_warning, placeholder);
3034 ((TextView)ll.findViewById(R.id.warning))
3035 .setText(R.string.ssl_untrusted);
3036 }
3037
3038 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3039 LinearLayout ll = (LinearLayout)factory
3040 .inflate(R.layout.ssl_warning, placeholder);
3041 ((TextView)ll.findViewById(R.id.warning))
3042 .setText(R.string.ssl_mismatch);
3043 }
3044
3045 if (error.hasError(SslError.SSL_EXPIRED)) {
3046 LinearLayout ll = (LinearLayout)factory
3047 .inflate(R.layout.ssl_warning, placeholder);
3048 ((TextView)ll.findViewById(R.id.warning))
3049 .setText(R.string.ssl_expired);
3050 }
3051
3052 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3053 LinearLayout ll = (LinearLayout)factory
3054 .inflate(R.layout.ssl_warning, placeholder);
3055 ((TextView)ll.findViewById(R.id.warning))
3056 .setText(R.string.ssl_not_yet_valid);
3057 }
3058
3059 mSSLCertificateOnErrorHandler = handler;
3060 mSSLCertificateOnErrorView = view;
3061 mSSLCertificateOnErrorError = error;
3062 mSSLCertificateOnErrorDialog =
3063 new AlertDialog.Builder(this)
3064 .setTitle(R.string.ssl_certificate).setIcon(
3065 R.drawable.ic_dialog_browser_certificate_partially_secure)
3066 .setView(certificateView)
3067 .setPositiveButton(R.string.ok,
3068 new DialogInterface.OnClickListener() {
3069 public void onClick(DialogInterface dialog,
3070 int whichButton) {
3071 mSSLCertificateOnErrorDialog = null;
3072 mSSLCertificateOnErrorView = null;
3073 mSSLCertificateOnErrorHandler = null;
3074 mSSLCertificateOnErrorError = null;
3075
Grace Kloba22ac16e2009-10-07 18:00:23 -07003076 view.getWebViewClient().onReceivedSslError(
3077 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003078 }
3079 })
3080 .setNeutralButton(R.string.page_info_view,
3081 new DialogInterface.OnClickListener() {
3082 public void onClick(DialogInterface dialog,
3083 int whichButton) {
3084 mSSLCertificateOnErrorDialog = null;
3085
3086 // do not clear the dialog state: we will
3087 // need to show the dialog again once the
3088 // user is done exploring the page-info details
3089
3090 showPageInfo(mTabControl.getTabFromView(view),
3091 true);
3092 }
3093 })
3094 .setOnCancelListener(
3095 new DialogInterface.OnCancelListener() {
3096 public void onCancel(DialogInterface dialog) {
3097 mSSLCertificateOnErrorDialog = null;
3098 mSSLCertificateOnErrorView = null;
3099 mSSLCertificateOnErrorHandler = null;
3100 mSSLCertificateOnErrorError = null;
3101
Grace Kloba22ac16e2009-10-07 18:00:23 -07003102 view.getWebViewClient().onReceivedSslError(
3103 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003104 }
3105 })
3106 .show();
3107 }
3108
3109 /**
3110 * Inflates the SSL certificate view (helper method).
3111 * @param certificate The SSL certificate.
3112 * @return The resultant certificate view with issued-to, issued-by,
3113 * issued-on, expires-on, and possibly other fields set.
3114 * If the input certificate is null, returns null.
3115 */
3116 private View inflateCertificateView(SslCertificate certificate) {
3117 if (certificate == null) {
3118 return null;
3119 }
3120
3121 LayoutInflater factory = LayoutInflater.from(this);
3122
3123 View certificateView = factory.inflate(
3124 R.layout.ssl_certificate, null);
3125
3126 // issued to:
3127 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3128 if (issuedTo != null) {
3129 ((TextView) certificateView.findViewById(R.id.to_common))
3130 .setText(issuedTo.getCName());
3131 ((TextView) certificateView.findViewById(R.id.to_org))
3132 .setText(issuedTo.getOName());
3133 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3134 .setText(issuedTo.getUName());
3135 }
3136
3137 // issued by:
3138 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3139 if (issuedBy != null) {
3140 ((TextView) certificateView.findViewById(R.id.by_common))
3141 .setText(issuedBy.getCName());
3142 ((TextView) certificateView.findViewById(R.id.by_org))
3143 .setText(issuedBy.getOName());
3144 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3145 .setText(issuedBy.getUName());
3146 }
3147
3148 // issued on:
3149 String issuedOn = reformatCertificateDate(
3150 certificate.getValidNotBefore());
3151 ((TextView) certificateView.findViewById(R.id.issued_on))
3152 .setText(issuedOn);
3153
3154 // expires on:
3155 String expiresOn = reformatCertificateDate(
3156 certificate.getValidNotAfter());
3157 ((TextView) certificateView.findViewById(R.id.expires_on))
3158 .setText(expiresOn);
3159
3160 return certificateView;
3161 }
3162
3163 /**
3164 * Re-formats the certificate date (Date.toString()) string to
3165 * a properly localized date string.
3166 * @return Properly localized version of the certificate date string and
3167 * the original certificate date string if fails to localize.
3168 * If the original string is null, returns an empty string "".
3169 */
3170 private String reformatCertificateDate(String certificateDate) {
3171 String reformattedDate = null;
3172
3173 if (certificateDate != null) {
3174 Date date = null;
3175 try {
3176 date = java.text.DateFormat.getInstance().parse(certificateDate);
3177 } catch (ParseException e) {
3178 date = null;
3179 }
3180
3181 if (date != null) {
3182 reformattedDate =
3183 DateFormat.getDateFormat(this).format(date);
3184 }
3185 }
3186
3187 return reformattedDate != null ? reformattedDate :
3188 (certificateDate != null ? certificateDate : "");
3189 }
3190
3191 /**
3192 * Displays an http-authentication dialog.
3193 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003194 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003195 final String host, final String realm, final String title,
3196 final String name, final String password, int focusId) {
3197 LayoutInflater factory = LayoutInflater.from(this);
3198 final View v = factory
3199 .inflate(R.layout.http_authentication, null);
3200 if (name != null) {
3201 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3202 }
3203 if (password != null) {
3204 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3205 }
3206
3207 String titleText = title;
3208 if (titleText == null) {
3209 titleText = getText(R.string.sign_in_to).toString().replace(
3210 "%s1", host).replace("%s2", realm);
3211 }
3212
3213 mHttpAuthHandler = handler;
3214 AlertDialog dialog = new AlertDialog.Builder(this)
3215 .setTitle(titleText)
3216 .setIcon(android.R.drawable.ic_dialog_alert)
3217 .setView(v)
3218 .setPositiveButton(R.string.action,
3219 new DialogInterface.OnClickListener() {
3220 public void onClick(DialogInterface dialog,
3221 int whichButton) {
3222 String nm = ((EditText) v
3223 .findViewById(R.id.username_edit))
3224 .getText().toString();
3225 String pw = ((EditText) v
3226 .findViewById(R.id.password_edit))
3227 .getText().toString();
3228 BrowserActivity.this.setHttpAuthUsernamePassword
3229 (host, realm, nm, pw);
3230 handler.proceed(nm, pw);
3231 mHttpAuthenticationDialog = null;
3232 mHttpAuthHandler = null;
3233 }})
3234 .setNegativeButton(R.string.cancel,
3235 new DialogInterface.OnClickListener() {
3236 public void onClick(DialogInterface dialog,
3237 int whichButton) {
3238 handler.cancel();
3239 BrowserActivity.this.resetTitleAndRevertLockIcon();
3240 mHttpAuthenticationDialog = null;
3241 mHttpAuthHandler = null;
3242 }})
3243 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3244 public void onCancel(DialogInterface dialog) {
3245 handler.cancel();
3246 BrowserActivity.this.resetTitleAndRevertLockIcon();
3247 mHttpAuthenticationDialog = null;
3248 mHttpAuthHandler = null;
3249 }})
3250 .create();
3251 // Make the IME appear when the dialog is displayed if applicable.
3252 dialog.getWindow().setSoftInputMode(
3253 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3254 dialog.show();
3255 if (focusId != 0) {
3256 dialog.findViewById(focusId).requestFocus();
3257 } else {
3258 v.findViewById(R.id.username_edit).requestFocus();
3259 }
3260 mHttpAuthenticationDialog = dialog;
3261 }
3262
3263 public int getProgress() {
3264 WebView w = mTabControl.getCurrentWebView();
3265 if (w != null) {
3266 return w.getProgress();
3267 } else {
3268 return 100;
3269 }
3270 }
3271
3272 /**
3273 * Set HTTP authentication password.
3274 *
3275 * @param host The host for the password
3276 * @param realm The realm for the password
3277 * @param username The username for the password. If it is null, it means
3278 * password can't be saved.
3279 * @param password The password
3280 */
3281 public void setHttpAuthUsernamePassword(String host, String realm,
3282 String username,
3283 String password) {
3284 WebView w = mTabControl.getCurrentWebView();
3285 if (w != null) {
3286 w.setHttpAuthUsernamePassword(host, realm, username, password);
3287 }
3288 }
3289
3290 /**
3291 * connectivity manager says net has come or gone... inform the user
3292 * @param up true if net has come up, false if net has gone down
3293 */
3294 public void onNetworkToggle(boolean up) {
3295 if (up == mIsNetworkUp) {
3296 return;
3297 } else if (up) {
3298 mIsNetworkUp = true;
3299 if (mAlertDialog != null) {
3300 mAlertDialog.cancel();
3301 mAlertDialog = null;
3302 }
3303 } else {
3304 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003305 if (mInLoad) {
3306 createAndShowNetworkDialog();
3307 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003308 }
3309 WebView w = mTabControl.getCurrentWebView();
3310 if (w != null) {
3311 w.setNetworkAvailable(up);
3312 }
3313 }
3314
Grace Kloba22ac16e2009-10-07 18:00:23 -07003315 boolean isNetworkUp() {
3316 return mIsNetworkUp;
3317 }
3318
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003319 // This method shows the network dialog alerting the user that the net is
3320 // down. It will only show the dialog if mAlertDialog is null.
3321 private void createAndShowNetworkDialog() {
3322 if (mAlertDialog == null) {
3323 mAlertDialog = new AlertDialog.Builder(this)
3324 .setTitle(R.string.loadSuspendedTitle)
3325 .setMessage(R.string.loadSuspended)
3326 .setPositiveButton(R.string.ok, null)
3327 .show();
3328 }
3329 }
3330
The Android Open Source Project0c908882009-03-03 19:32:16 -08003331 @Override
3332 protected void onActivityResult(int requestCode, int resultCode,
3333 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003334 if (getTopWindow() == null) return;
3335
The Android Open Source Project0c908882009-03-03 19:32:16 -08003336 switch (requestCode) {
3337 case COMBO_PAGE:
3338 if (resultCode == RESULT_OK && intent != null) {
3339 String data = intent.getAction();
3340 Bundle extras = intent.getExtras();
3341 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003342 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003343 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003344 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003345 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003346 dismissSubWindow(currentTab);
3347 if (data != null && data.length() != 0) {
3348 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003349 }
3350 }
3351 }
3352 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003353 // Choose a file from the file picker.
3354 case FILE_SELECTED:
3355 if (null == mUploadMessage) break;
3356 Uri result = intent == null || resultCode != RESULT_OK ? null
3357 : intent.getData();
3358 mUploadMessage.onReceiveValue(result);
3359 mUploadMessage = null;
3360 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003361 default:
3362 break;
3363 }
Leon Scroggins30444232009-09-04 18:36:20 -04003364 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003365 }
3366
3367 /*
3368 * This method is called as a result of the user selecting the options
3369 * menu to see the download window, or when a download changes state. It
3370 * shows the download window ontop of the current window.
3371 */
3372 /* package */ void viewDownloads(Uri downloadRecord) {
3373 Intent intent = new Intent(this,
3374 BrowserDownloadPage.class);
3375 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003376 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003377
3378 }
3379
Leon Scroggins160a7e72009-08-14 18:28:01 -04003380 /**
3381 * Open the Go page.
3382 * @param startWithHistory If true, open starting on the history tab.
3383 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003384 */
Leon Scroggins30444232009-09-04 18:36:20 -04003385 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003386 WebView current = mTabControl.getCurrentWebView();
3387 if (current == null) {
3388 return;
3389 }
3390 Intent intent = new Intent(this,
3391 CombinedBookmarkHistoryActivity.class);
3392 String title = current.getTitle();
3393 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003394 Bitmap thumbnail = createScreenshot(current);
3395
The Android Open Source Project0c908882009-03-03 19:32:16 -08003396 // Just in case the user opens bookmarks before a page finishes loading
3397 // so the current history item, and therefore the page, is null.
3398 if (null == url) {
3399 url = mLastEnteredUrl;
3400 // This can happen.
3401 if (null == url) {
3402 url = mSettings.getHomePage();
3403 }
3404 }
3405 // In case the web page has not yet received its associated title.
3406 if (title == null) {
3407 title = url;
3408 }
3409 intent.putExtra("title", title);
3410 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003411 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003412 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003413 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003414 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003415 if (startWithHistory) {
3416 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3417 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3418 }
3419 startActivityForResult(intent, COMBO_PAGE);
3420 }
3421
3422 // Called when loading from context menu or LOAD_URL message
3423 private void loadURL(WebView view, String url) {
3424 // In case the user enters nothing.
3425 if (url != null && url.length() != 0 && view != null) {
3426 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003427 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003428 view.loadUrl(url);
3429 }
3430 }
3431 }
3432
The Android Open Source Project0c908882009-03-03 19:32:16 -08003433 private String smartUrlFilter(Uri inUri) {
3434 if (inUri != null) {
3435 return smartUrlFilter(inUri.toString());
3436 }
3437 return null;
3438 }
3439
Feng Qianb34f87a2009-03-24 21:27:26 -07003440 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003441 "(?i)" + // switch on case insensitive matching
3442 "(" + // begin group for schema
3443 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003444 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003445 ")" +
3446 "(.*)" );
3447
3448 /**
3449 * Attempts to determine whether user input is a URL or search
3450 * terms. Anything with a space is passed to search.
3451 *
3452 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3453 * "Http://" converts to "http://"
3454 *
3455 * @return Original or modified URL
3456 *
3457 */
3458 String smartUrlFilter(String url) {
3459
3460 String inUrl = url.trim();
3461 boolean hasSpace = inUrl.indexOf(' ') != -1;
3462
3463 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3464 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003465 // force scheme to lowercase
3466 String scheme = matcher.group(1);
3467 String lcScheme = scheme.toLowerCase();
3468 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003469 inUrl = lcScheme + matcher.group(2);
3470 }
3471 if (hasSpace) {
3472 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003473 }
3474 return inUrl;
3475 }
3476 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003477 // FIXME: Is this the correct place to add to searches?
3478 // what if someone else calls this function?
3479 int shortcut = parseUrlShortcut(inUrl);
3480 if (shortcut != SHORTCUT_INVALID) {
3481 Browser.addSearchUrl(mResolver, inUrl);
3482 String query = inUrl.substring(2);
3483 switch (shortcut) {
3484 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003485 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003486 case SHORTCUT_WIKIPEDIA_SEARCH:
3487 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3488 case SHORTCUT_DICTIONARY_SEARCH:
3489 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3490 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003491 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003492 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003493 }
3494 }
3495 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003496 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003497 return URLUtil.guessUrl(inUrl);
3498 }
3499 }
3500
3501 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003502 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003503 }
3504
Ben Murdochbff2d602009-07-01 20:19:05 +01003505 /* package */ void setShouldShowErrorConsole(boolean flag) {
3506 if (flag == mShouldShowErrorConsole) {
3507 // Nothing to do.
3508 return;
3509 }
3510
3511 mShouldShowErrorConsole = flag;
3512
Grace Kloba22ac16e2009-10-07 18:00:23 -07003513 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3514 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003515
3516 if (flag) {
3517 // Setting the show state of the console will cause it's the layout to be inflated.
3518 if (errorConsole.numberOfErrors() > 0) {
3519 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3520 } else {
3521 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3522 }
3523
3524 // Now we can add it to the main view.
3525 mErrorConsoleContainer.addView(errorConsole,
3526 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
3527 ViewGroup.LayoutParams.WRAP_CONTENT));
3528 } else {
3529 mErrorConsoleContainer.removeView(errorConsole);
3530 }
3531
3532 }
3533
Grace Kloba22ac16e2009-10-07 18:00:23 -07003534 boolean shouldShowErrorConsole() {
3535 return mShouldShowErrorConsole;
3536 }
3537
Andrei Popescu163ab742009-10-20 17:58:23 +01003538 private void setStatusBarVisibility(boolean visible) {
3539 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3540 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3541 }
3542
Grace Klobaeb6eef42009-09-15 17:56:32 -07003543 final static int LOCK_ICON_UNSECURE = 0;
3544 final static int LOCK_ICON_SECURE = 1;
3545 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003546
The Android Open Source Project0c908882009-03-03 19:32:16 -08003547 private BrowserSettings mSettings;
3548 private TabControl mTabControl;
3549 private ContentResolver mResolver;
3550 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003551 private View mCustomView;
3552 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003553 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003554
3555 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3556 // view, we should rewrite this.
3557 private int mCurrentMenuState = 0;
3558 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003559 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003560 private static final int EMPTY_MENU = -1;
3561 private Menu mMenu;
3562
3563 private FindDialog mFindDialog;
3564 // Used to prevent chording to result in firing two shortcuts immediately
3565 // one after another. Fixes bug 1211714.
3566 boolean mCanChord;
3567
3568 private boolean mInLoad;
3569 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003570 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003571
The Android Open Source Project0c908882009-03-03 19:32:16 -08003572 private boolean mActivityInPause = true;
3573
3574 private boolean mMenuIsDown;
3575
The Android Open Source Project0c908882009-03-03 19:32:16 -08003576 private static boolean mInTrace;
3577
3578 // Performance probe
3579 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3580 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3581 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3582 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3583 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3584 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3585 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3586 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3587 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3588 };
3589
3590 private long mStart;
3591 private long mProcessStart;
3592 private long mUserStart;
3593 private long mSystemStart;
3594 private long mIdleStart;
3595 private long mIrqStart;
3596
3597 private long mUiStart;
3598
3599 private Drawable mMixLockIcon;
3600 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003601
3602 /* hold a ref so we can auto-cancel if necessary */
3603 private AlertDialog mAlertDialog;
3604
3605 // Wait for credentials before loading google.com
3606 private ProgressDialog mCredsDlg;
3607
3608 // The up-to-date URL and title (these can be different from those stored
3609 // in WebView, since it takes some time for the information in WebView to
3610 // get updated)
3611 private String mUrl;
3612 private String mTitle;
3613
3614 // As PageInfo has different style for landscape / portrait, we have
3615 // to re-open it when configuration changed
3616 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003617 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003618 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3619 // dialog, we should not just dismiss it, but should get back to the
3620 // SSL-certificate-on-error dialog. This flag is used to store this state
3621 private Boolean mPageInfoFromShowSSLCertificateOnError;
3622
3623 // as SSLCertificateOnError has different style for landscape / portrait,
3624 // we have to re-open it when configuration changed
3625 private AlertDialog mSSLCertificateOnErrorDialog;
3626 private WebView mSSLCertificateOnErrorView;
3627 private SslErrorHandler mSSLCertificateOnErrorHandler;
3628 private SslError mSSLCertificateOnErrorError;
3629
3630 // as SSLCertificate has different style for landscape / portrait, we
3631 // have to re-open it when configuration changed
3632 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003633 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003634
3635 // as HttpAuthentication has different style for landscape / portrait, we
3636 // have to re-open it when configuration changed
3637 private AlertDialog mHttpAuthenticationDialog;
3638 private HttpAuthHandler mHttpAuthHandler;
3639
3640 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3641 new FrameLayout.LayoutParams(
3642 ViewGroup.LayoutParams.FILL_PARENT,
3643 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003644 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3645 new FrameLayout.LayoutParams(
3646 ViewGroup.LayoutParams.FILL_PARENT,
3647 ViewGroup.LayoutParams.FILL_PARENT,
3648 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003649 // Google search
3650 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003651 // Wikipedia search
3652 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3653 // Dictionary search
3654 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3655 // Google Mobile Local search
3656 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3657
3658 final static String QUERY_PLACE_HOLDER = "%s";
3659
3660 // "source" parameter for Google search through search key
3661 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3662 // "source" parameter for Google search through goto menu
3663 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3664 // "source" parameter for Google search through simplily type
3665 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3666 // "source" parameter for Google search suggested by the browser
3667 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3668 // "source" parameter for Google search from unknown source
3669 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3670
3671 private final static String LOGTAG = "browser";
3672
The Android Open Source Project0c908882009-03-03 19:32:16 -08003673 private String mLastEnteredUrl;
3674
3675 private PowerManager.WakeLock mWakeLock;
3676 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3677
3678 private Toast mStopToast;
3679
Leon Scroggins68579392009-09-15 15:31:54 -04003680 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003681
Ben Murdochbff2d602009-07-01 20:19:05 +01003682 private LinearLayout mErrorConsoleContainer = null;
3683 private boolean mShouldShowErrorConsole = false;
3684
The Android Open Source Project0c908882009-03-03 19:32:16 -08003685 // As the ids are dynamically created, we can't guarantee that they will
3686 // be in sequence, so this static array maps ids to a window number.
3687 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3688 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3689 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3690 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3691
3692 // monitor platform changes
3693 private IntentFilter mNetworkStateChangedFilter;
3694 private BroadcastReceiver mNetworkStateIntentReceiver;
3695
Grace Klobab4da0ad2009-05-14 14:45:40 -07003696 private BroadcastReceiver mPackageInstallationReceiver;
3697
The Android Open Source Project0c908882009-03-03 19:32:16 -08003698 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003699 final static int COMBO_PAGE = 1;
3700 final static int DOWNLOAD_PAGE = 2;
3701 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003702 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003703
Andrei Popescu540035d2009-09-18 18:59:20 +01003704 // the default <video> poster
3705 private Bitmap mDefaultVideoPoster;
3706 // the video progress view
3707 private View mVideoProgressView;
3708
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003709 /**
3710 * A UrlData class to abstract how the content will be set to WebView.
3711 * This base class uses loadUrl to show the content.
3712 */
3713 private static class UrlData {
3714 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07003715 byte[] mPostData;
3716
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003717 UrlData(String url) {
3718 this.mUrl = url;
3719 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003720
3721 void setPostData(byte[] postData) {
3722 mPostData = postData;
3723 }
3724
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003725 boolean isEmpty() {
3726 return mUrl == null || mUrl.length() == 0;
3727 }
3728
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003729 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07003730 if (mPostData != null) {
3731 webView.postUrl(mUrl, mPostData);
3732 } else {
3733 webView.loadUrl(mUrl);
3734 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003735 }
3736 };
3737
3738 /**
3739 * A subclass of UrlData class that can display inlined content using
3740 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
3741 */
3742 private static class InlinedUrlData extends UrlData {
3743 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
3744 super(failUrl);
3745 mInlined = inlined;
3746 mMimeType = mimeType;
3747 mEncoding = encoding;
3748 }
3749 String mMimeType;
3750 String mInlined;
3751 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003752 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003753 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01003754 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003755 }
3756
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003757 @Override
3758 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003759 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
3760 }
3761 }
3762
Leon Scroggins1f005d32009-08-10 17:36:42 -04003763 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003764}