blob: 55e3dda27e2674c3b1f5a4279032b15b0a7eb2a1 [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 {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700522 if ("about:debug".equals(urlData.mUrl)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800523 mSettings.toggleDebugSettings();
524 return;
525 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400526 // Get rid of the subwindow if it exists
527 dismissSubWindow(current);
528 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800529 }
530 }
531 }
532
Satish Sampath565505b2009-05-29 15:37:27 +0100533 private int parseUrlShortcut(String url) {
534 if (url == null) return SHORTCUT_INVALID;
535
536 // FIXME: quick search, need to be customized by setting
537 if (url.length() > 2 && url.charAt(1) == ' ') {
538 switch (url.charAt(0)) {
539 case 'g': return SHORTCUT_GOOGLE_SEARCH;
540 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
541 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
542 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
543 }
544 }
545 return SHORTCUT_INVALID;
546 }
547
548 /**
549 * Launches the default web search activity with the query parameters if the given intent's data
550 * are identified as plain search terms and not URLs/shortcuts.
551 * @return true if the intent was handled and web search activity was launched, false if not.
552 */
553 private boolean handleWebSearchIntent(Intent intent) {
554 if (intent == null) return false;
555
556 String url = null;
557 final String action = intent.getAction();
558 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700559 Uri data = intent.getData();
560 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100561 } else if (Intent.ACTION_SEARCH.equals(action)
562 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
563 || Intent.ACTION_WEB_SEARCH.equals(action)) {
564 url = intent.getStringExtra(SearchManager.QUERY);
565 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100566 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
567 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100568 }
569
570 /**
571 * Launches the default web search activity with the query parameters if the given url string
572 * was identified as plain search terms and not URL/shortcut.
573 * @return true if the request was handled and web search activity was launched, false if not.
574 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100575 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100576 if (inUrl == null) return false;
577
578 // In general, we shouldn't modify URL from Intent.
579 // But currently, we get the user-typed URL from search box as well.
580 String url = fixUrl(inUrl).trim();
581
582 // URLs and site specific search shortcuts are handled by the regular flow of control, so
583 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800584 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100585 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100586 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
587 return false;
588 }
589
590 Browser.updateVisitedHistory(mResolver, url, false);
591 Browser.addSearchUrl(mResolver, url);
592
593 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
594 intent.addCategory(Intent.CATEGORY_DEFAULT);
595 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100596 if (appData != null) {
597 intent.putExtra(SearchManager.APP_DATA, appData);
598 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100599 if (extraData != null) {
600 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
601 }
Grace Klobacc634032009-07-28 15:58:19 -0700602 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100603 startActivity(intent);
604
605 return true;
606 }
607
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700608 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800609 String url = null;
610 if (intent != null) {
611 final String action = intent.getAction();
612 if (Intent.ACTION_VIEW.equals(action)) {
613 url = smartUrlFilter(intent.getData());
614 if (url != null && url.startsWith("content:")) {
615 /* Append mimetype so webview knows how to display */
616 String mimeType = intent.resolveType(getContentResolver());
617 if (mimeType != null) {
618 url += "?" + mimeType;
619 }
620 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700621 if ("inline:".equals(url)) {
622 return new InlinedUrlData(
623 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
624 intent.getType(),
625 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
626 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
627 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800628 } else if (Intent.ACTION_SEARCH.equals(action)
629 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
630 || Intent.ACTION_WEB_SEARCH.equals(action)) {
631 url = intent.getStringExtra(SearchManager.QUERY);
632 if (url != null) {
633 mLastEnteredUrl = url;
634 // Don't add Urls, just search terms.
635 // Urls will get added when the page is loaded.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800636 if (!Patterns.WEB_URL.matcher(url).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800637 Browser.updateVisitedHistory(mResolver, url, false);
638 }
639 // In general, we shouldn't modify URL from Intent.
640 // But currently, we get the user-typed URL from search box as well.
641 url = fixUrl(url);
642 url = smartUrlFilter(url);
643 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
644 if (url.contains(searchSource)) {
645 String source = null;
646 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
647 if (appData != null) {
648 source = appData.getString(SearchManager.SOURCE);
649 }
650 if (TextUtils.isEmpty(source)) {
651 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
652 }
653 url = url.replace(searchSource, "&source=android-"+source+"&");
654 }
655 }
656 }
657 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700658 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800659 }
660
661 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400662 // FIXME: Converting the url to lower case
663 // duplicates functionality in smartUrlFilter().
664 // However, changing all current callers of fixUrl to
665 // call smartUrlFilter in addition may have unwanted
666 // consequences, and is deferred for now.
667 int colon = inUrl.indexOf(':');
668 boolean allLower = true;
669 for (int index = 0; index < colon; index++) {
670 char ch = inUrl.charAt(index);
671 if (!Character.isLetter(ch)) {
672 break;
673 }
674 allLower &= Character.isLowerCase(ch);
675 if (index == colon - 1 && !allLower) {
676 inUrl = inUrl.substring(0, colon).toLowerCase()
677 + inUrl.substring(colon);
678 }
679 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800680 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
681 return inUrl;
682 if (inUrl.startsWith("http:") ||
683 inUrl.startsWith("https:")) {
684 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
685 inUrl = inUrl.replaceFirst("/", "//");
686 } else inUrl = inUrl.replaceFirst(":", "://");
687 }
688 return inUrl;
689 }
690
Grace Kloba22ac16e2009-10-07 18:00:23 -0700691 @Override
692 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800693 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700694 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800695 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
696 }
697
698 if (!mActivityInPause) {
699 Log.e(LOGTAG, "BrowserActivity is already resumed.");
700 return;
701 }
702
Mike Reed7bfa63b2009-05-28 11:08:32 -0400703 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800704 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400705 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800706
707 if (mWakeLock.isHeld()) {
708 mHandler.removeMessages(RELEASE_WAKELOCK);
709 mWakeLock.release();
710 }
711
712 if (mCredsDlg != null) {
713 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
714 // In case credential request never comes back
715 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
716 }
717 }
718
719 registerReceiver(mNetworkStateIntentReceiver,
720 mNetworkStateChangedFilter);
721 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800722 }
723
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400724 /**
725 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400726 * would change its appearance, use a different TitleBar to show overlayed
727 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400728 */
729 private TitleBar mFakeTitleBar;
730
731 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400732 * Holder for the fake title bar. It will have a foreground shadow, as well
733 * as a white background, so the fake title bar looks like the real one.
734 */
735 private ViewGroup mFakeTitleBarHolder;
736
737 /**
738 * Layout parameters for the fake title bar within mFakeTitleBarHolder
739 */
740 private FrameLayout.LayoutParams mFakeTitleBarParams
741 = new FrameLayout.LayoutParams(
Leon Scrogginsc01e4a82009-09-16 14:41:00 -0400742 ViewGroup.LayoutParams.FILL_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400743 ViewGroup.LayoutParams.WRAP_CONTENT);
744 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400745 * Keeps track of whether the options menu is open. This is important in
746 * determining whether to show or hide the title bar overlay.
747 */
748 private boolean mOptionsMenuOpen;
749
750 /**
751 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
752 * of whether the configuration has changed. The first onMenuOpened call
753 * after a configuration change is simply a reopening of the same menu
754 * (i.e. mIconView did not change).
755 */
756 private boolean mConfigChanged;
757
758 /**
759 * Whether or not the options menu is in its smaller, icon menu form. When
760 * true, we want the title bar overlay to be up. When false, we do not.
761 * Only meaningful if mOptionsMenuOpen is true.
762 */
763 private boolean mIconView;
764
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400765 @Override
766 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400767 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
768 if (mOptionsMenuOpen) {
769 if (mConfigChanged) {
770 // We do not need to make any changes to the state of the
771 // title bar, since the only thing that happened was a
772 // change in orientation
773 mConfigChanged = false;
774 } else {
775 if (mIconView) {
776 // Switching the menu to expanded view, so hide the
777 // title bar.
778 hideFakeTitleBar();
779 mIconView = false;
780 } else {
781 // Switching the menu back to icon view, so show the
782 // title bar once again.
783 showFakeTitleBar();
784 mIconView = true;
785 }
786 }
787 } else {
788 // The options menu is closed, so open it, and show the title
789 showFakeTitleBar();
790 mOptionsMenuOpen = true;
791 mConfigChanged = false;
792 mIconView = true;
793 }
794 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400795 return true;
796 }
797
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400798 /**
799 * Special class used exclusively for the shadow drawn underneath the fake
800 * title bar. The shadow does not need to be drawn if the WebView
801 * underneath is scrolled to the top, because it will draw directly on top
802 * of the embedded shadow.
803 */
804 private static class Shadow extends View {
805 private WebView mWebView;
806
807 public Shadow(Context context, AttributeSet attrs) {
808 super(context, attrs);
809 }
810
811 public void setWebView(WebView view) {
812 mWebView = view;
813 }
814
815 @Override
816 public void draw(Canvas canvas) {
817 // In general onDraw is the method to override, but we care about
818 // whether or not the background gets drawn, which happens in draw()
819 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
820 super.draw(canvas);
821 }
822 // Need to invalidate so that if the scroll position changes, we
823 // still draw as appropriate.
824 invalidate();
825 }
826 }
827
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400828 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400829 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400830 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400831 && !mActivityInPause && decor != null
832 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400833 Rect visRect = new Rect();
834 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
835 if (LOGD_ENABLED) {
836 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
837 }
838 return;
839 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400840
841 WindowManager manager
842 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
843
844 // Add the title bar to the window manager so it can receive touches
845 // while the menu is up
846 WindowManager.LayoutParams params
847 = new WindowManager.LayoutParams(
848 ViewGroup.LayoutParams.FILL_PARENT,
849 ViewGroup.LayoutParams.WRAP_CONTENT,
850 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
851 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400852 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400853 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400854 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400855 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400856 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400857 // XXX : Without providing an offset, the fake title bar will be
858 // placed underneath the status bar. Use the global visible rect
859 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400860 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400861 // Add a holder for the title bar. It also holds a shadow to show
862 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400863 if (mFakeTitleBarHolder == null) {
864 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
865 .inflate(R.layout.title_bar_bg, null);
866 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400867 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
868 R.id.shadow);
869 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400870 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400871 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400872 }
873 }
874
875 @Override
876 public void onOptionsMenuClosed(Menu menu) {
877 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400878 if (!mInLoad) {
879 hideFakeTitleBar();
880 } else if (!mIconView) {
881 // The page is currently loading, and we are in expanded mode, so
882 // we were not showing the menu. Show it once again. It will be
883 // removed when the page finishes.
884 showFakeTitleBar();
885 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400886 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700887
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400888 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400889 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400890 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
891 mFakeTitleBarHolder.getLayoutParams();
892 WebView mainView = mTabControl.getCurrentWebView();
893 // Although we decided whether or not to animate based on the current
894 // scroll position, the scroll position may have changed since the
895 // fake title bar was displayed. Make sure it has the appropriate
896 // animation/lack thereof before removing.
897 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400898 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400899 WindowManager manager
900 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -0400901 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400902 mFakeTitleBarHolder.removeView(mFakeTitleBar);
903 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400904 }
905
The Android Open Source Project0c908882009-03-03 19:32:16 -0800906 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400907 * Special method for the fake title bar to call when displaying its context
908 * menu, since it is in its own Window, and its parent does not show a
909 * context menu.
910 */
911 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400912 if (null == mTitleBar.getParent()) {
913 return;
914 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400915 openContextMenu(mTitleBar);
916 }
917
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400918 @Override
919 public void onContextMenuClosed(Menu menu) {
920 super.onContextMenuClosed(menu);
921 if (mInLoad) {
922 showFakeTitleBar();
923 }
924 }
925
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400926 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800927 * onSaveInstanceState(Bundle map)
928 * onSaveInstanceState is called right before onStop(). The map contains
929 * the saved state.
930 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700931 @Override
932 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700933 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800934 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
935 }
936 // the default implementation requires each view to have an id. As the
937 // browser handles the state itself and it doesn't use id for the views,
938 // don't call the default implementation. Otherwise it will trigger the
939 // warning like this, "couldn't save which view has focus because the
940 // focused view XXX has no id".
941
942 // Save all the tabs
943 mTabControl.saveState(outState);
944 }
945
Grace Kloba22ac16e2009-10-07 18:00:23 -0700946 @Override
947 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800948 super.onPause();
949
950 if (mActivityInPause) {
951 Log.e(LOGTAG, "BrowserActivity is already paused.");
952 return;
953 }
954
Mike Reed7bfa63b2009-05-28 11:08:32 -0400955 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800956 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400957 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800958 mWakeLock.acquire();
959 mHandler.sendMessageDelayed(mHandler
960 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
961 }
962
963 // Clear the credentials toast if it is up
964 if (mCredsDlg != null && mCredsDlg.isShowing()) {
965 mCredsDlg.dismiss();
966 }
967 mCredsDlg = null;
968
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400969 // FIXME: This removes the active tabs page and resets the menu to
970 // MAIN_MENU. A better solution might be to do this work in onNewIntent
971 // but then we would need to save it in onSaveInstanceState and restore
972 // it in onCreate/onRestoreInstanceState
973 if (mActiveTabsPage != null) {
974 removeActiveTabPage(true);
975 }
976
The Android Open Source Project0c908882009-03-03 19:32:16 -0800977 cancelStopToast();
978
979 // unregister network state listener
980 unregisterReceiver(mNetworkStateIntentReceiver);
981 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800982 }
983
Grace Kloba22ac16e2009-10-07 18:00:23 -0700984 @Override
985 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700986 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800987 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
988 }
989 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700990
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400991 if (mUploadMessage != null) {
992 mUploadMessage.onReceiveValue(null);
993 mUploadMessage = null;
994 }
995
Grace Kloba0923d692009-09-23 21:37:25 -0700996 if (mTabControl == null) return;
997
Grace Kloba1fc98a32009-10-21 13:23:08 -0700998 // Remove the fake title bar if it is there
999 hideFakeTitleBar();
1000
The Android Open Source Project0c908882009-03-03 19:32:16 -08001001 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001002 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001003 if (t != null) {
1004 dismissSubWindow(t);
1005 removeTabFromContentView(t);
1006 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001007 // Destroy all the tabs
1008 mTabControl.destroy();
1009 WebIconDatabase.getInstance().close();
1010 if (mGlsConnection != null) {
1011 unbindService(mGlsConnection);
1012 mGlsConnection = null;
1013 }
1014
Grace Klobab4da0ad2009-05-14 14:45:40 -07001015 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001016 }
1017
1018 @Override
1019 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001020 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001021 super.onConfigurationChanged(newConfig);
1022
1023 if (mPageInfoDialog != null) {
1024 mPageInfoDialog.dismiss();
1025 showPageInfo(
1026 mPageInfoView,
1027 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1028 }
1029 if (mSSLCertificateDialog != null) {
1030 mSSLCertificateDialog.dismiss();
1031 showSSLCertificate(
1032 mSSLCertificateView);
1033 }
1034 if (mSSLCertificateOnErrorDialog != null) {
1035 mSSLCertificateOnErrorDialog.dismiss();
1036 showSSLCertificateOnError(
1037 mSSLCertificateOnErrorView,
1038 mSSLCertificateOnErrorHandler,
1039 mSSLCertificateOnErrorError);
1040 }
1041 if (mHttpAuthenticationDialog != null) {
1042 String title = ((TextView) mHttpAuthenticationDialog
1043 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1044 .toString();
1045 String name = ((TextView) mHttpAuthenticationDialog
1046 .findViewById(R.id.username_edit)).getText().toString();
1047 String password = ((TextView) mHttpAuthenticationDialog
1048 .findViewById(R.id.password_edit)).getText().toString();
1049 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1050 .getId();
1051 mHttpAuthenticationDialog.dismiss();
1052 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1053 name, password, focusId);
1054 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001055 }
1056
Grace Kloba22ac16e2009-10-07 18:00:23 -07001057 @Override
1058 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001059 super.onLowMemory();
1060 mTabControl.freeMemory();
1061 }
1062
Mike Reed7bfa63b2009-05-28 11:08:32 -04001063 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001064 Tab tab = mTabControl.getCurrentTab();
1065 boolean inLoad = tab.inLoad();
1066 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001067 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001068 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001069 if (w != null) {
1070 w.resumeTimers();
1071 }
1072 return true;
1073 } else {
1074 return false;
1075 }
1076 }
1077
Mike Reed7bfa63b2009-05-28 11:08:32 -04001078 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001079 Tab tab = mTabControl.getCurrentTab();
1080 boolean inLoad = tab.inLoad();
1081 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001082 CookieSyncManager.getInstance().stopSync();
1083 WebView w = mTabControl.getCurrentWebView();
1084 if (w != null) {
1085 w.pauseTimers();
1086 }
1087 return true;
1088 } else {
1089 return false;
1090 }
1091 }
1092
Leon Scroggins1f005d32009-08-10 17:36:42 -04001093 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001094 /*
1095 * This function is called when we are launching for the first time. We
1096 * are waiting for the login credentials before loading Google home
1097 * pages. This way the user will be logged in straight away.
1098 */
1099 private void waitForCredentials() {
1100 // Show a toast
1101 mCredsDlg = new ProgressDialog(this);
1102 mCredsDlg.setIndeterminate(true);
1103 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1104 // If the user cancels the operation, then cancel the Google
1105 // Credentials request.
1106 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1107 mCredsDlg.show();
1108
1109 // We set a timeout for the retrieval of credentials in onResume()
1110 // as that is when we have freed up some CPU time to get
1111 // the login credentials.
1112 }
1113
1114 /*
1115 * If we have received the credentials or we have timed out and we are
1116 * showing the credentials dialog, then it is time to move on.
1117 */
1118 private void resumeAfterCredentials() {
1119 if (mCredsDlg == null) {
1120 return;
1121 }
1122
1123 // Clear the toast
1124 if (mCredsDlg.isShowing()) {
1125 mCredsDlg.dismiss();
1126 }
1127 mCredsDlg = null;
1128
1129 // Clear any pending timeout
1130 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1131
1132 // Load the page
1133 WebView w = mTabControl.getCurrentWebView();
1134 if (w != null) {
1135 w.loadUrl(mSettings.getHomePage());
1136 }
1137
1138 // Update the settings, need to do this last as it can take a moment
1139 // to persist the settings. In the mean time we could be loading
1140 // content.
1141 mSettings.setLoginInitialized(this);
1142 }
1143
1144 // Open the icon database and retain all the icons for visited sites.
1145 private void retainIconsOnStartup() {
1146 final WebIconDatabase db = WebIconDatabase.getInstance();
1147 db.open(getDir("icons", 0).getPath());
1148 try {
1149 Cursor c = Browser.getAllBookmarks(mResolver);
1150 if (!c.moveToFirst()) {
1151 c.deactivate();
1152 return;
1153 }
1154 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1155 do {
1156 String url = c.getString(urlIndex);
1157 db.retainIconForPageUrl(url);
1158 } while (c.moveToNext());
1159 c.deactivate();
1160 } catch (IllegalStateException e) {
1161 Log.e(LOGTAG, "retainIconsOnStartup", e);
1162 }
1163 }
1164
1165 // Helper method for getting the top window.
1166 WebView getTopWindow() {
1167 return mTabControl.getCurrentTopWebView();
1168 }
1169
Grace Kloba22ac16e2009-10-07 18:00:23 -07001170 TabControl getTabControl() {
1171 return mTabControl;
1172 }
1173
The Android Open Source Project0c908882009-03-03 19:32:16 -08001174 @Override
1175 public boolean onCreateOptionsMenu(Menu menu) {
1176 super.onCreateOptionsMenu(menu);
1177
1178 MenuInflater inflater = getMenuInflater();
1179 inflater.inflate(R.menu.browser, menu);
1180 mMenu = menu;
1181 updateInLoadMenuItems();
1182 return true;
1183 }
1184
1185 /**
1186 * As the menu can be open when loading state changes
1187 * we must manually update the state of the stop/reload menu
1188 * item
1189 */
1190 private void updateInLoadMenuItems() {
1191 if (mMenu == null) {
1192 return;
1193 }
1194 MenuItem src = mInLoad ?
1195 mMenu.findItem(R.id.stop_menu_id):
1196 mMenu.findItem(R.id.reload_menu_id);
1197 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1198 dest.setIcon(src.getIcon());
1199 dest.setTitle(src.getTitle());
1200 }
1201
1202 @Override
1203 public boolean onContextItemSelected(MenuItem item) {
1204 // chording is not an issue with context menus, but we use the same
1205 // options selector, so set mCanChord to true so we can access them.
1206 mCanChord = true;
1207 int id = item.getItemId();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001208 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001209 // For the context menu from the title bar
1210 case R.id.title_bar_share_page_url:
1211 case R.id.title_bar_copy_page_url:
1212 WebView mainView = mTabControl.getCurrentWebView();
1213 if (null == mainView) {
1214 return false;
1215 }
1216 if (id == R.id.title_bar_share_page_url) {
1217 Browser.sendString(this, mainView.getUrl());
1218 } else {
1219 copy(mainView.getUrl());
1220 }
1221 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001222 // -- Browser context menu
1223 case R.id.open_context_menu_id:
1224 case R.id.open_newtab_context_menu_id:
1225 case R.id.bookmark_context_menu_id:
1226 case R.id.save_link_context_menu_id:
1227 case R.id.share_link_context_menu_id:
1228 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001229 final WebView webView = getTopWindow();
1230 if (null == webView) {
1231 return false;
1232 }
1233 final HashMap hrefMap = new HashMap();
1234 hrefMap.put("webview", webView);
1235 final Message msg = mHandler.obtainMessage(
1236 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001237 webView.requestFocusNodeHref(msg);
1238 break;
1239
1240 default:
1241 // For other context menus
1242 return onOptionsItemSelected(item);
1243 }
1244 mCanChord = false;
1245 return true;
1246 }
1247
1248 private Bundle createGoogleSearchSourceBundle(String source) {
1249 Bundle bundle = new Bundle();
1250 bundle.putString(SearchManager.SOURCE, source);
1251 return bundle;
1252 }
1253
1254 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001255 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001256 */
1257 @Override
1258 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001259 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001260 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001261 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001262 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001263 return true;
1264 }
1265
1266 @Override
1267 public void startSearch(String initialQuery, boolean selectInitialQuery,
1268 Bundle appSearchData, boolean globalSearch) {
1269 if (appSearchData == null) {
1270 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1271 }
1272 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1273 }
1274
Leon Scroggins1f005d32009-08-10 17:36:42 -04001275 /**
1276 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1277 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001278 * @param index Index of the tab to change to, as defined by
1279 * mTabControl.getTabIndex(Tab t).
1280 * @return boolean True if we successfully switched to a different tab. If
1281 * the indexth tab is null, or if that tab is the same as
1282 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001283 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001284 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001285 Tab tab = mTabControl.getTab(index);
1286 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001287 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001288 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001289 }
1290 if (currentTab != null) {
1291 // currentTab may be null if it was just removed. In that case,
1292 // we do not need to remove it
1293 removeTabFromContentView(currentTab);
1294 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001295 mTabControl.setCurrentTab(tab);
1296 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001297 resetTitleIconAndProgress();
1298 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001299 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001300 }
1301
Grace Kloba22ac16e2009-10-07 18:00:23 -07001302 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001303 return openTabAndShow(mSettings.getHomePage(), false, null);
1304 }
1305
Leon Scroggins1f005d32009-08-10 17:36:42 -04001306 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001307 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001308 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001309 // This is the last tab. Open a new one, with the home
1310 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001311 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001312 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001313 return;
1314 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001315 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001316 int indexToShow = -1;
1317 if (parent != null) {
1318 indexToShow = mTabControl.getTabIndex(parent);
1319 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001320 final int currentIndex = mTabControl.getCurrentIndex();
1321 // Try to move to the tab to the right
1322 indexToShow = currentIndex + 1;
1323 if (indexToShow > mTabControl.getTabCount() - 1) {
1324 // Try to move to the tab to the left
1325 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001326 }
1327 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001328 if (switchToTab(indexToShow)) {
1329 // Close window
1330 closeTab(current);
1331 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001332 }
1333
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001334 private ActiveTabsPage mActiveTabsPage;
1335
1336 /**
1337 * Remove the active tabs page.
1338 * @param needToAttach If true, the active tabs page did not attach a tab
1339 * to the content view, so we need to do that here.
1340 */
1341 /* package */ void removeActiveTabPage(boolean needToAttach) {
1342 mContentView.removeView(mActiveTabsPage);
1343 mActiveTabsPage = null;
1344 mMenuState = R.id.MAIN_MENU;
1345 if (needToAttach) {
1346 attachTabToContentView(mTabControl.getCurrentTab());
1347 }
1348 getTopWindow().requestFocus();
1349 }
1350
The Android Open Source Project0c908882009-03-03 19:32:16 -08001351 @Override
1352 public boolean onOptionsItemSelected(MenuItem item) {
1353 if (!mCanChord) {
1354 // The user has already fired a shortcut with this hold down of the
1355 // menu key.
1356 return false;
1357 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001358 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001359 return false;
1360 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001361 if (mMenuIsDown) {
1362 // The shortcut action consumes the MENU. Even if it is still down,
1363 // it won't trigger the next shortcut action. In the case of the
1364 // shortcut action triggering a new activity, like Bookmarks, we
1365 // won't get onKeyUp for MENU. So it is important to reset it here.
1366 mMenuIsDown = false;
1367 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001368 switch (item.getItemId()) {
1369 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001370 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001371 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001372 break;
1373
Leon Scroggins64b80f32009-08-07 12:03:34 -04001374 case R.id.goto_menu_id:
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001375 onSearchRequested();
1376 break;
1377
1378 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001379 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001380 break;
1381
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001382 case R.id.active_tabs_menu_id:
1383 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1384 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001385 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001386 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1387 mActiveTabsPage.requestFocus();
1388 mMenuState = EMPTY_MENU;
1389 break;
1390
Leon Scroggins1f005d32009-08-10 17:36:42 -04001391 case R.id.add_bookmark_menu_id:
1392 Intent i = new Intent(BrowserActivity.this,
1393 AddBookmarkPage.class);
1394 WebView w = getTopWindow();
1395 i.putExtra("url", w.getUrl());
1396 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001397 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001398 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001399 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001400 break;
1401
1402 case R.id.stop_reload_menu_id:
1403 if (mInLoad) {
1404 stopLoading();
1405 } else {
1406 getTopWindow().reload();
1407 }
1408 break;
1409
1410 case R.id.back_menu_id:
1411 getTopWindow().goBack();
1412 break;
1413
1414 case R.id.forward_menu_id:
1415 getTopWindow().goForward();
1416 break;
1417
1418 case R.id.close_menu_id:
1419 // Close the subwindow if it exists.
1420 if (mTabControl.getCurrentSubWindow() != null) {
1421 dismissSubWindow(mTabControl.getCurrentTab());
1422 break;
1423 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001424 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001425 break;
1426
1427 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001428 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001429 if (current != null) {
1430 dismissSubWindow(current);
1431 current.getWebView().loadUrl(mSettings.getHomePage());
1432 }
1433 break;
1434
1435 case R.id.preferences_menu_id:
1436 Intent intent = new Intent(this,
1437 BrowserPreferencesPage.class);
1438 startActivityForResult(intent, PREFERENCES_PAGE);
1439 break;
1440
1441 case R.id.find_menu_id:
1442 if (null == mFindDialog) {
1443 mFindDialog = new FindDialog(this);
1444 }
1445 mFindDialog.setWebView(getTopWindow());
1446 mFindDialog.show();
1447 mMenuState = EMPTY_MENU;
1448 break;
1449
1450 case R.id.select_text_id:
1451 getTopWindow().emulateShiftHeld();
1452 break;
1453 case R.id.page_info_menu_id:
1454 showPageInfo(mTabControl.getCurrentTab(), false);
1455 break;
1456
1457 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001458 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001459 break;
1460
1461 case R.id.share_page_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01001462 Browser.sendString(this, getTopWindow().getUrl(),
1463 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001464 break;
1465
1466 case R.id.dump_nav_menu_id:
1467 getTopWindow().debugDump();
1468 break;
1469
1470 case R.id.zoom_in_menu_id:
1471 getTopWindow().zoomIn();
1472 break;
1473
1474 case R.id.zoom_out_menu_id:
1475 getTopWindow().zoomOut();
1476 break;
1477
1478 case R.id.view_downloads_menu_id:
1479 viewDownloads(null);
1480 break;
1481
The Android Open Source Project0c908882009-03-03 19:32:16 -08001482 case R.id.window_one_menu_id:
1483 case R.id.window_two_menu_id:
1484 case R.id.window_three_menu_id:
1485 case R.id.window_four_menu_id:
1486 case R.id.window_five_menu_id:
1487 case R.id.window_six_menu_id:
1488 case R.id.window_seven_menu_id:
1489 case R.id.window_eight_menu_id:
1490 {
1491 int menuid = item.getItemId();
1492 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1493 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001494 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001495 if (desiredTab != null &&
1496 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001497 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001498 }
1499 break;
1500 }
1501 }
1502 }
1503 break;
1504
1505 default:
1506 if (!super.onOptionsItemSelected(item)) {
1507 return false;
1508 }
1509 // Otherwise fall through.
1510 }
1511 mCanChord = false;
1512 return true;
1513 }
1514
1515 public void closeFind() {
1516 mMenuState = R.id.MAIN_MENU;
1517 }
1518
Grace Kloba22ac16e2009-10-07 18:00:23 -07001519 @Override
1520 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001521 // This happens when the user begins to hold down the menu key, so
1522 // allow them to chord to get a shortcut.
1523 mCanChord = true;
1524 // Note: setVisible will decide whether an item is visible; while
1525 // setEnabled() will decide whether an item is enabled, which also means
1526 // whether the matching shortcut key will function.
1527 super.onPrepareOptionsMenu(menu);
1528 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001529 case EMPTY_MENU:
1530 if (mCurrentMenuState != mMenuState) {
1531 menu.setGroupVisible(R.id.MAIN_MENU, false);
1532 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1533 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001534 }
1535 break;
1536 default:
1537 if (mCurrentMenuState != mMenuState) {
1538 menu.setGroupVisible(R.id.MAIN_MENU, true);
1539 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1540 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001541 }
1542 final WebView w = getTopWindow();
1543 boolean canGoBack = false;
1544 boolean canGoForward = false;
1545 boolean isHome = false;
1546 if (w != null) {
1547 canGoBack = w.canGoBack();
1548 canGoForward = w.canGoForward();
1549 isHome = mSettings.getHomePage().equals(w.getUrl());
1550 }
1551 final MenuItem back = menu.findItem(R.id.back_menu_id);
1552 back.setEnabled(canGoBack);
1553
1554 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1555 home.setEnabled(!isHome);
1556
1557 menu.findItem(R.id.forward_menu_id)
1558 .setEnabled(canGoForward);
1559
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001560 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001561 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001562
The Android Open Source Project0c908882009-03-03 19:32:16 -08001563 // decide whether to show the share link option
1564 PackageManager pm = getPackageManager();
1565 Intent send = new Intent(Intent.ACTION_SEND);
1566 send.setType("text/plain");
1567 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1568 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1569
The Android Open Source Project0c908882009-03-03 19:32:16 -08001570 boolean isNavDump = mSettings.isNavDump();
1571 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1572 nav.setVisible(isNavDump);
1573 nav.setEnabled(isNavDump);
1574 break;
1575 }
1576 mCurrentMenuState = mMenuState;
1577 return true;
1578 }
1579
1580 @Override
1581 public void onCreateContextMenu(ContextMenu menu, View v,
1582 ContextMenuInfo menuInfo) {
1583 WebView webview = (WebView) v;
1584 WebView.HitTestResult result = webview.getHitTestResult();
1585 if (result == null) {
1586 return;
1587 }
1588
1589 int type = result.getType();
1590 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1591 Log.w(LOGTAG,
1592 "We should not show context menu when nothing is touched");
1593 return;
1594 }
1595 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1596 // let TextView handles context menu
1597 return;
1598 }
1599
1600 // Note, http://b/issue?id=1106666 is requesting that
1601 // an inflated menu can be used again. This is not available
1602 // yet, so inflate each time (yuk!)
1603 MenuInflater inflater = getMenuInflater();
1604 inflater.inflate(R.menu.browsercontext, menu);
1605
1606 // Show the correct menu group
1607 String extra = result.getExtra();
1608 menu.setGroupVisible(R.id.PHONE_MENU,
1609 type == WebView.HitTestResult.PHONE_TYPE);
1610 menu.setGroupVisible(R.id.EMAIL_MENU,
1611 type == WebView.HitTestResult.EMAIL_TYPE);
1612 menu.setGroupVisible(R.id.GEO_MENU,
1613 type == WebView.HitTestResult.GEO_TYPE);
1614 menu.setGroupVisible(R.id.IMAGE_MENU,
1615 type == WebView.HitTestResult.IMAGE_TYPE
1616 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1617 menu.setGroupVisible(R.id.ANCHOR_MENU,
1618 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1619 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1620
1621 // Setup custom handling depending on the type
1622 switch (type) {
1623 case WebView.HitTestResult.PHONE_TYPE:
1624 menu.setHeaderTitle(Uri.decode(extra));
1625 menu.findItem(R.id.dial_context_menu_id).setIntent(
1626 new Intent(Intent.ACTION_VIEW, Uri
1627 .parse(WebView.SCHEME_TEL + extra)));
1628 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1629 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001630 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001631 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1632 addIntent);
1633 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1634 new Copy(extra));
1635 break;
1636
1637 case WebView.HitTestResult.EMAIL_TYPE:
1638 menu.setHeaderTitle(extra);
1639 menu.findItem(R.id.email_context_menu_id).setIntent(
1640 new Intent(Intent.ACTION_VIEW, Uri
1641 .parse(WebView.SCHEME_MAILTO + extra)));
1642 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1643 new Copy(extra));
1644 break;
1645
1646 case WebView.HitTestResult.GEO_TYPE:
1647 menu.setHeaderTitle(extra);
1648 menu.findItem(R.id.map_context_menu_id).setIntent(
1649 new Intent(Intent.ACTION_VIEW, Uri
1650 .parse(WebView.SCHEME_GEO
1651 + URLEncoder.encode(extra))));
1652 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1653 new Copy(extra));
1654 break;
1655
1656 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1657 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1658 TextView titleView = (TextView) LayoutInflater.from(this)
1659 .inflate(android.R.layout.browser_link_context_header,
1660 null);
1661 titleView.setText(extra);
1662 menu.setHeaderView(titleView);
1663 // decide whether to show the open link in new tab option
1664 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001665 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001666 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1667 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001668 PackageManager pm = getPackageManager();
1669 Intent send = new Intent(Intent.ACTION_SEND);
1670 send.setType("text/plain");
1671 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1672 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1673 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1674 break;
1675 }
1676 // otherwise fall through to handle image part
1677 case WebView.HitTestResult.IMAGE_TYPE:
1678 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1679 menu.setHeaderTitle(extra);
1680 }
1681 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1682 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1683 menu.findItem(R.id.download_context_menu_id).
1684 setOnMenuItemClickListener(new Download(extra));
1685 break;
1686
1687 default:
1688 Log.w(LOGTAG, "We should not get here.");
1689 break;
1690 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001691 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001692 }
1693
The Android Open Source Project0c908882009-03-03 19:32:16 -08001694 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001695 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001696 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001697 // Attach the container that contains the main WebView and any other UI
1698 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001699 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001700
1701 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001702 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001703 if (errorConsole.numberOfErrors() == 0) {
1704 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1705 } else {
1706 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1707 }
1708
1709 mErrorConsoleContainer.addView(errorConsole,
1710 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1711 ViewGroup.LayoutParams.WRAP_CONTENT));
1712 }
1713
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001714 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001715 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001716 // Request focus on the top window.
1717 t.getTopWindow().requestFocus();
1718 }
1719
1720 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001721 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001722 t.attachSubWindow(mContentView);
1723 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001724 }
1725
1726 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001727 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001728 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001729 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001730
Grace Kloba22ac16e2009-10-07 18:00:23 -07001731 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1732 if (errorConsole != null) {
1733 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001734 }
1735
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001736 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001737 if (view != null) {
1738 view.setEmbeddedTitleBar(null);
1739 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001740 }
1741
1742 // Remove the sub window if it exists. Also called by TabControl when the
1743 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001744 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001745 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001746 // dismiss the subwindow. This will destroy the WebView.
1747 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001748 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001749 }
1750
Leon Scroggins1f005d32009-08-10 17:36:42 -04001751 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001752 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001753 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001754 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001755 }
1756
1757 // This method does a ton of stuff. It will attempt to create a new tab
1758 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001759 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001760 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1761 String appId) {
1762 final Tab currentTab = mTabControl.getCurrentTab();
1763 if (mTabControl.canCreateNewTab()) {
1764 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1765 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001766 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001767 // If the last tab was removed from the active tabs page, currentTab
1768 // will be null.
1769 if (currentTab != null) {
1770 removeTabFromContentView(currentTab);
1771 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001772 // We must set the new tab as the current tab to reflect the old
1773 // animation behavior.
1774 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001775 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001776 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001777 urlData.loadIn(webview);
1778 }
1779 return tab;
1780 } else {
1781 // Get rid of the subwindow if it exists
1782 dismissSubWindow(currentTab);
1783 if (!urlData.isEmpty()) {
1784 // Load the given url.
1785 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001786 }
1787 }
Grace Klobac9181842009-04-14 08:53:22 -07001788 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001789 }
1790
Grace Kloba22ac16e2009-10-07 18:00:23 -07001791 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001792 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001793 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001794 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001795 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001796 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001797 }
Grace Klobac9181842009-04-14 08:53:22 -07001798 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001799 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001800 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001801 }
1802 }
1803
1804 private class Copy implements OnMenuItemClickListener {
1805 private CharSequence mText;
1806
1807 public boolean onMenuItemClick(MenuItem item) {
1808 copy(mText);
1809 return true;
1810 }
1811
1812 public Copy(CharSequence toCopy) {
1813 mText = toCopy;
1814 }
1815 }
1816
1817 private class Download implements OnMenuItemClickListener {
1818 private String mText;
1819
1820 public boolean onMenuItemClick(MenuItem item) {
1821 onDownloadStartNoStream(mText, null, null, null, -1);
1822 return true;
1823 }
1824
1825 public Download(String toDownload) {
1826 mText = toDownload;
1827 }
1828 }
1829
1830 private void copy(CharSequence text) {
1831 try {
1832 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1833 if (clip != null) {
1834 clip.setClipboardText(text);
1835 }
1836 } catch (android.os.RemoteException e) {
1837 Log.e(LOGTAG, "Copy failed", e);
1838 }
1839 }
1840
1841 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001842 * Resets the browser title-view to whatever it must be
1843 * (for example, if we had a loading error)
1844 * When we have a new page, we call resetTitle, when we
1845 * have to reset the titlebar to whatever it used to be
1846 * (for example, if the user chose to stop loading), we
1847 * call resetTitleAndRevertLockIcon.
1848 */
1849 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001850 mTabControl.getCurrentTab().revertLockIcon();
1851 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001852 resetTitleIconAndProgress();
1853 }
1854
1855 /**
1856 * Reset the title, favicon, and progress.
1857 */
1858 private void resetTitleIconAndProgress() {
1859 WebView current = mTabControl.getCurrentWebView();
1860 if (current == null) {
1861 return;
1862 }
1863 resetTitleAndIcon(current);
1864 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001865 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001866 }
1867
1868 // Reset the title and the icon based on the given item.
1869 private void resetTitleAndIcon(WebView view) {
1870 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1871 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001872 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001873 setFavicon(item.getFavicon());
1874 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001875 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001876 setFavicon(null);
1877 }
1878 }
1879
1880 /**
1881 * Sets a title composed of the URL and the title string.
1882 * @param url The URL of the site being loaded.
1883 * @param title The title of the site being loaded.
1884 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001885 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001886 mUrl = url;
1887 mTitle = title;
1888
Leon Scroggins68579392009-09-15 15:31:54 -04001889 mTitleBar.setTitleAndUrl(title, url);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001890 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001891 }
1892
1893 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001894 * @param url The URL to build a title version of the URL from.
1895 * @return The title version of the URL or null if fails.
1896 * The title version of the URL can be either the URL hostname,
1897 * or the hostname with an "https://" prefix (for secure URLs),
1898 * or an empty string if, for example, the URL in question is a
1899 * file:// URL with no hostname.
1900 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001901 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001902 String titleUrl = null;
1903
1904 if (url != null) {
1905 try {
1906 // parse the url string
1907 URL urlObj = new URL(url);
1908 if (urlObj != null) {
1909 titleUrl = "";
1910
1911 String protocol = urlObj.getProtocol();
1912 String host = urlObj.getHost();
1913
1914 if (host != null && 0 < host.length()) {
1915 titleUrl = host;
1916 if (protocol != null) {
1917 // if a secure site, add an "https://" prefix!
1918 if (protocol.equalsIgnoreCase("https")) {
1919 titleUrl = protocol + "://" + host;
1920 }
1921 }
1922 }
1923 }
1924 } catch (MalformedURLException e) {}
1925 }
1926
1927 return titleUrl;
1928 }
1929
1930 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001931 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04001932 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001933 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001934 }
1935
1936 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001937 * Close the tab, remove its associated title bar, and adjust mTabControl's
1938 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001939 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001940 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001941 int currentIndex = mTabControl.getCurrentIndex();
1942 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001943 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001944 if (currentIndex >= removeIndex && currentIndex != 0) {
1945 currentIndex--;
1946 }
1947 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01001948 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001949 }
1950
1951 private void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001952 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001953 if (current == null) {
1954 /*
1955 * Instead of finishing the activity, simply push this to the back
1956 * of the stack and let ActivityManager to choose the foreground
1957 * activity. As BrowserActivity is singleTask, it will be always the
1958 * root of the task. So we can use either true or false for
1959 * moveTaskToBack().
1960 */
1961 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07001962 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001963 }
1964 WebView w = current.getWebView();
1965 if (w.canGoBack()) {
1966 w.goBack();
1967 } else {
1968 // Check to see if we are closing a window that was created by
1969 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001970 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001971 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001972 switchToTab(mTabControl.getTabIndex(parent));
1973 // Now we close the other tab
1974 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001975 } else {
1976 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001977 // force the tab's inLoad() to be false as we are going to
1978 // either finish the activity or remove the tab. This will
1979 // ensure pauseWebViewTimers() taking action.
1980 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001981 if (mTabControl.getTabCount() == 1) {
1982 finish();
1983 return;
1984 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04001985 // call pauseWebViewTimers() now, we won't be able to call
1986 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07001987 // Temporarily change mActivityInPause to be true as
1988 // pauseWebViewTimers() will do nothing if mActivityInPause
1989 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07001990 boolean savedState = mActivityInPause;
1991 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07001992 Log.e(LOGTAG, "BrowserActivity is already paused "
1993 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07001994 }
1995 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001996 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07001997 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001998 removeTabFromContentView(current);
1999 mTabControl.removeTab(current);
2000 }
2001 /*
2002 * Instead of finishing the activity, simply push this to the back
2003 * of the stack and let ActivityManager to choose the foreground
2004 * activity. As BrowserActivity is singleTask, it will be always the
2005 * root of the task. So we can use either true or false for
2006 * moveTaskToBack().
2007 */
2008 moveTaskToBack(true);
2009 }
2010 }
2011 }
2012
Grace Kloba22ac16e2009-10-07 18:00:23 -07002013 boolean isMenuDown() {
2014 return mMenuIsDown;
2015 }
2016
Grace Kloba5942df02009-09-18 11:48:29 -07002017 @Override
2018 public boolean onKeyDown(int keyCode, KeyEvent event) {
2019 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2020 // still down, we don't want to trigger the search. Pretend to consume
2021 // the key and do nothing.
2022 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002023
Grace Kloba5942df02009-09-18 11:48:29 -07002024 switch(keyCode) {
2025 case KeyEvent.KEYCODE_MENU:
2026 mMenuIsDown = true;
2027 break;
2028 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002029 // WebView/WebTextView handle the keys in the KeyDown. As
2030 // the Activity's shortcut keys are only handled when WebView
2031 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2032 if (event.isShiftPressed()) {
2033 getTopWindow().pageUp(false);
2034 } else {
2035 getTopWindow().pageDown(false);
2036 }
Grace Kloba5942df02009-09-18 11:48:29 -07002037 return true;
2038 case KeyEvent.KEYCODE_BACK:
2039 if (event.getRepeatCount() == 0) {
2040 event.startTracking();
2041 return true;
2042 } else if (mCustomView == null && mActiveTabsPage == null
2043 && event.isLongPress()) {
2044 bookmarksOrHistoryPicker(true);
2045 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002046 }
Grace Kloba5942df02009-09-18 11:48:29 -07002047 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002048 }
Grace Kloba5942df02009-09-18 11:48:29 -07002049 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002050 }
2051
Grace Kloba5942df02009-09-18 11:48:29 -07002052 @Override
2053 public boolean onKeyUp(int keyCode, KeyEvent event) {
2054 switch(keyCode) {
2055 case KeyEvent.KEYCODE_MENU:
2056 mMenuIsDown = false;
2057 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002058 case KeyEvent.KEYCODE_BACK:
2059 if (event.isTracking() && !event.isCanceled()) {
2060 if (mCustomView != null) {
2061 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002062 mTabControl.getCurrentWebView().getWebChromeClient()
2063 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002064 } else if (mActiveTabsPage != null) {
2065 // if tab page is showing, hide it
2066 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002067 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002068 WebView subwindow = mTabControl.getCurrentSubWindow();
2069 if (subwindow != null) {
2070 if (subwindow.canGoBack()) {
2071 subwindow.goBack();
2072 } else {
2073 dismissSubWindow(mTabControl.getCurrentTab());
2074 }
2075 } else {
2076 goBackOnePageOrQuit();
2077 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002078 }
Grace Kloba5942df02009-09-18 11:48:29 -07002079 return true;
2080 }
2081 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002082 }
Grace Kloba5942df02009-09-18 11:48:29 -07002083 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002084 }
2085
Leon Scroggins68579392009-09-15 15:31:54 -04002086 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002087 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002088 resetTitleAndRevertLockIcon();
2089 WebView w = getTopWindow();
2090 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002091 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2092 // same logic here. But for subwindow case, should we call into the main
2093 // WebView's onPageFinished as we never call its onPageStarted and if
2094 // the page finishes itself, we don't call onPageFinished.
2095 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2096 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002097
2098 cancelStopToast();
2099 mStopToast = Toast
2100 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2101 mStopToast.show();
2102 }
2103
Grace Kloba22ac16e2009-10-07 18:00:23 -07002104 boolean didUserStopLoading() {
2105 return mDidStopLoad;
2106 }
2107
The Android Open Source Project0c908882009-03-03 19:32:16 -08002108 private void cancelStopToast() {
2109 if (mStopToast != null) {
2110 mStopToast.cancel();
2111 mStopToast = null;
2112 }
2113 }
2114
Grace Kloba22ac16e2009-10-07 18:00:23 -07002115 // called by a UI or non-UI thread to post the message
2116 public void postMessage(int what, int arg1, int arg2, Object obj,
2117 long delayMillis) {
2118 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2119 obj), delayMillis);
2120 }
2121
2122 // called by a UI or non-UI thread to remove the message
2123 void removeMessages(int what, Object object) {
2124 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002125 }
2126
2127 // public message ids
2128 public final static int LOAD_URL = 1001;
2129 public final static int STOP_LOAD = 1002;
2130
2131 // Message Ids
2132 private static final int FOCUS_NODE_HREF = 102;
2133 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002134 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002135
Grace Kloba22ac16e2009-10-07 18:00:23 -07002136 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002137
The Android Open Source Project0c908882009-03-03 19:32:16 -08002138 // Private handler for handling javascript and saving passwords
2139 private Handler mHandler = new Handler() {
2140
2141 public void handleMessage(Message msg) {
2142 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002143 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002144 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002145 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002146 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002147 if (url == null || url.length() == 0) {
2148 break;
2149 }
2150 HashMap focusNodeMap = (HashMap) msg.obj;
2151 WebView view = (WebView) focusNodeMap.get("webview");
2152 // Only apply the action if the top window did not change.
2153 if (getTopWindow() != view) {
2154 break;
2155 }
2156 switch (msg.arg1) {
2157 case R.id.open_context_menu_id:
2158 case R.id.view_image_context_menu_id:
2159 loadURL(getTopWindow(), url);
2160 break;
2161 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002162 final Tab parent = mTabControl.getCurrentTab();
2163 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002164 if (newTab != parent) {
2165 parent.addChildTab(newTab);
2166 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002167 break;
2168 case R.id.bookmark_context_menu_id:
2169 Intent intent = new Intent(BrowserActivity.this,
2170 AddBookmarkPage.class);
2171 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002172 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002173 startActivity(intent);
2174 break;
2175 case R.id.share_link_context_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01002176 Browser.sendString(BrowserActivity.this, url,
2177 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002178 break;
2179 case R.id.copy_link_context_menu_id:
2180 copy(url);
2181 break;
2182 case R.id.save_link_context_menu_id:
2183 case R.id.download_context_menu_id:
2184 onDownloadStartNoStream(url, null, null, null, -1);
2185 break;
2186 }
2187 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002188 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002189
2190 case LOAD_URL:
2191 loadURL(getTopWindow(), (String) msg.obj);
2192 break;
2193
2194 case STOP_LOAD:
2195 stopLoading();
2196 break;
2197
2198 case CANCEL_CREDS_REQUEST:
2199 resumeAfterCredentials();
2200 break;
2201
The Android Open Source Project0c908882009-03-03 19:32:16 -08002202 case RELEASE_WAKELOCK:
2203 if (mWakeLock.isHeld()) {
2204 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002205 // if we reach here, Browser should be still in the
2206 // background loading after WAKELOCK_TIMEOUT (5-min).
2207 // To avoid burning the battery, stop loading.
2208 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002209 }
2210 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002211
2212 case UPDATE_BOOKMARK_THUMBNAIL:
2213 WebView view = (WebView) msg.obj;
2214 if (view != null) {
2215 updateScreenshot(view);
2216 }
2217 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002218 }
2219 }
2220 };
2221
Leon Scroggins89c6d362009-07-15 16:54:37 -04002222 private void updateScreenshot(WebView view) {
2223 // If this is a bookmarked site, add a screenshot to the database.
2224 // FIXME: When should we update? Every time?
2225 // FIXME: Would like to make sure there is actually something to
2226 // draw, but the API for that (WebViewCore.pictureReady()) is not
2227 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002228
Patrick Scott3918d442009-08-04 13:22:29 -04002229 ContentResolver cr = getContentResolver();
2230 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002231 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002232 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002233 boolean succeed = c.moveToFirst();
2234 ContentValues values = null;
2235 while (succeed) {
2236 if (values == null) {
2237 final ByteArrayOutputStream os
2238 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002239 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002240 if (bm == null) {
2241 c.close();
2242 return;
2243 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002244 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2245 values = new ContentValues();
2246 values.put(Browser.BookmarkColumns.THUMBNAIL,
2247 os.toByteArray());
2248 }
2249 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2250 c.getInt(0)), values, null, null);
2251 succeed = c.moveToNext();
2252 }
2253 c.close();
2254 }
2255 }
2256
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002257 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002258 * Values for the size of the thumbnail created when taking a screenshot.
2259 * Lazily initialized. Instead of using these directly, use
2260 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002261 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002262 private static int THUMBNAIL_WIDTH = 0;
2263 private static int THUMBNAIL_HEIGHT = 0;
2264
2265 /**
2266 * Return the desired width for thumbnail screenshots, which are stored in
2267 * the database, and used on the bookmarks screen.
2268 * @param context Context for finding out the density of the screen.
2269 * @return int desired width for thumbnail screenshot.
2270 */
2271 /* package */ static int getDesiredThumbnailWidth(Context context) {
2272 if (THUMBNAIL_WIDTH == 0) {
2273 float density = context.getResources().getDisplayMetrics().density;
2274 THUMBNAIL_WIDTH = (int) (90 * density);
2275 THUMBNAIL_HEIGHT = (int) (80 * density);
2276 }
2277 return THUMBNAIL_WIDTH;
2278 }
2279
2280 /**
2281 * Return the desired height for thumbnail screenshots, which are stored in
2282 * the database, and used on the bookmarks screen.
2283 * @param context Context for finding out the density of the screen.
2284 * @return int desired height for thumbnail screenshot.
2285 */
2286 /* package */ static int getDesiredThumbnailHeight(Context context) {
2287 // To ensure that they are both initialized.
2288 getDesiredThumbnailWidth(context);
2289 return THUMBNAIL_HEIGHT;
2290 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002291
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002292 private Bitmap createScreenshot(WebView view) {
2293 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002294 if (thumbnail == null) {
2295 return null;
2296 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002297 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2298 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002299 Canvas canvas = new Canvas(bm);
2300 // May need to tweak these values to determine what is the
2301 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002302 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002303 int thumbnailHeight = thumbnail.getHeight();
2304 float scaleFactorX = 1.0f;
2305 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002306 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002307 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002308 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002309 } else {
2310 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002311 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002312
2313 if (view.getWidth() > view.getHeight() &&
2314 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2315 // If the device is in landscape and the page is shorter
2316 // than the height of the view, stretch the thumbnail to fill the
2317 // space.
2318 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2319 (float)thumbnailHeight;
2320 } else {
2321 // In the portrait case, this looks nice.
2322 scaleFactorY = scaleFactorX;
2323 }
2324
2325 canvas.scale(scaleFactorX, scaleFactorY);
2326
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002327 thumbnail.draw(canvas);
2328 return bm;
2329 }
2330
The Android Open Source Project0c908882009-03-03 19:32:16 -08002331 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002332 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002333 //-------------------------------------------------------------------------
2334
2335 // Use in overrideUrlLoading
2336 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2337 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2338 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2339 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2340
Grace Kloba22ac16e2009-10-07 18:00:23 -07002341 void onPageStarted(WebView view, String url, Bitmap favicon) {
2342 // when BrowserActivity just starts, onPageStarted may be called before
2343 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2344 // to start the timer. As we won't switch tabs while an activity is in
2345 // pause state, we can ensure calling resume and pause in pair.
2346 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002347
Grace Kloba22ac16e2009-10-07 18:00:23 -07002348 resetLockIcon(url);
2349 setUrlTitle(url, null);
2350 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002351 // Keep this initial progress in sync with initialProgressValue (* 100)
2352 // in ProgressTracker.cpp
2353 // Show some progress so that the user knows the page is beginning to
2354 // load
2355 onProgressChanged(view, 10);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002356 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002357 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002358
Grace Kloba22ac16e2009-10-07 18:00:23 -07002359 if (mSettings.isTracing()) {
2360 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002361 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002362 WebAddress uri = new WebAddress(url);
2363 host = uri.mHost;
2364 } catch (android.net.ParseException ex) {
2365 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002366 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002367 host = host.replace('.', '_');
2368 host += ".trace";
2369 mInTrace = true;
2370 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2371 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002372
Grace Kloba22ac16e2009-10-07 18:00:23 -07002373 // Performance probe
2374 if (false) {
2375 mStart = SystemClock.uptimeMillis();
2376 mProcessStart = Process.getElapsedCpuTime();
2377 long[] sysCpu = new long[7];
2378 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2379 sysCpu, null)) {
2380 mUserStart = sysCpu[0] + sysCpu[1];
2381 mSystemStart = sysCpu[2];
2382 mIdleStart = sysCpu[3];
2383 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2384 }
2385 mUiStart = SystemClock.currentThreadTimeMillis();
2386 }
2387 }
2388
2389 void onPageFinished(WebView view, String url) {
2390 // Reset the title and icon in case we stopped a provisional load.
2391 resetTitleAndIcon(view);
2392 // Update the lock icon image only once we are done loading
2393 updateLockIconToLatest();
2394 // pause the WebView timer and release the wake lock if it is finished
2395 // while BrowserActivity is in pause state.
2396 if (mActivityInPause && pauseWebViewTimers()) {
2397 if (mWakeLock.isHeld()) {
2398 mHandler.removeMessages(RELEASE_WAKELOCK);
2399 mWakeLock.release();
2400 }
2401 }
2402
2403 // Performance probe
2404 if (false) {
2405 long[] sysCpu = new long[7];
2406 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2407 sysCpu, null)) {
2408 String uiInfo = "UI thread used "
2409 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2410 + " ms";
2411 if (LOGD_ENABLED) {
2412 Log.d(LOGTAG, uiInfo);
2413 }
2414 //The string that gets written to the log
2415 String performanceString = "It took total "
2416 + (SystemClock.uptimeMillis() - mStart)
2417 + " ms clock time to load the page."
2418 + "\nbrowser process used "
2419 + (Process.getElapsedCpuTime() - mProcessStart)
2420 + " ms, user processes used "
2421 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2422 + " ms, kernel used "
2423 + (sysCpu[2] - mSystemStart) * 10
2424 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2425 + " ms and irq took "
2426 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2427 * 10 + " ms, " + uiInfo;
2428 if (LOGD_ENABLED) {
2429 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2430 }
2431 if (url != null) {
2432 // strip the url to maintain consistency
2433 String newUrl = new String(url);
2434 if (newUrl.startsWith("http://www.")) {
2435 newUrl = newUrl.substring(11);
2436 } else if (newUrl.startsWith("http://")) {
2437 newUrl = newUrl.substring(7);
2438 } else if (newUrl.startsWith("https://www.")) {
2439 newUrl = newUrl.substring(12);
2440 } else if (newUrl.startsWith("https://")) {
2441 newUrl = newUrl.substring(8);
2442 }
2443 if (LOGD_ENABLED) {
2444 Log.d(LOGTAG, newUrl + " loaded");
2445 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002446 }
2447 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002448 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002449
Grace Kloba22ac16e2009-10-07 18:00:23 -07002450 if (mInTrace) {
2451 mInTrace = false;
2452 Debug.stopMethodTracing();
2453 }
2454 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002455
Grace Kloba22ac16e2009-10-07 18:00:23 -07002456 boolean shouldOverrideUrlLoading(WebView view, String url) {
2457 if (url.startsWith(SCHEME_WTAI)) {
2458 // wtai://wp/mc;number
2459 // number=string(phone-number)
2460 if (url.startsWith(SCHEME_WTAI_MC)) {
2461 Intent intent = new Intent(Intent.ACTION_VIEW,
2462 Uri.parse(WebView.SCHEME_TEL +
2463 url.substring(SCHEME_WTAI_MC.length())));
2464 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002465 return true;
2466 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002467 // wtai://wp/sd;dtmf
2468 // dtmf=string(dialstring)
2469 if (url.startsWith(SCHEME_WTAI_SD)) {
2470 // TODO: only send when there is active voice connection
2471 return false;
2472 }
2473 // wtai://wp/ap;number;name
2474 // number=string(phone-number)
2475 // name=string
2476 if (url.startsWith(SCHEME_WTAI_AP)) {
2477 // TODO
2478 return false;
2479 }
2480 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002481
Grace Kloba22ac16e2009-10-07 18:00:23 -07002482 // The "about:" schemes are internal to the browser; don't want these to
2483 // be dispatched to other apps.
2484 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002485 return false;
2486 }
2487
Grace Kloba22ac16e2009-10-07 18:00:23 -07002488 Intent intent;
2489 // perform generic parsing of the URI to turn it into an Intent.
2490 try {
2491 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2492 } catch (URISyntaxException ex) {
2493 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2494 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002495 }
2496
Grace Kloba22ac16e2009-10-07 18:00:23 -07002497 // check whether the intent can be resolved. If not, we will see
2498 // whether we can download it from the Market.
2499 if (getPackageManager().resolveActivity(intent, 0) == null) {
2500 String packagename = intent.getPackage();
2501 if (packagename != null) {
2502 intent = new Intent(Intent.ACTION_VIEW, Uri
2503 .parse("market://search?q=pname:" + packagename));
2504 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2505 startActivity(intent);
2506 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002507 } else {
2508 return false;
2509 }
2510 }
2511
Grace Kloba22ac16e2009-10-07 18:00:23 -07002512 // sanitize the Intent, ensuring web pages can not bypass browser
2513 // security (only access to BROWSABLE activities).
2514 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2515 intent.setComponent(null);
2516 try {
2517 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002518 return true;
2519 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002520 } catch (ActivityNotFoundException ex) {
2521 // ignore the error. If no application can handle the URL,
2522 // eg about:blank, assume the browser can handle it.
2523 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002524
Grace Kloba22ac16e2009-10-07 18:00:23 -07002525 if (mMenuIsDown) {
2526 openTab(url);
2527 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002528 return true;
2529 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002530 return false;
2531 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002532
Grace Kloba22ac16e2009-10-07 18:00:23 -07002533 // -------------------------------------------------------------------------
2534 // Helper function for WebChromeClient
2535 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002536
Grace Kloba22ac16e2009-10-07 18:00:23 -07002537 void onProgressChanged(WebView view, int newProgress) {
2538 mTitleBar.setProgress(newProgress);
2539 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002540
Grace Kloba22ac16e2009-10-07 18:00:23 -07002541 if (newProgress == 100) {
2542 // onProgressChanged() may continue to be called after the main
2543 // frame has finished loading, as any remaining sub frames continue
2544 // to load. We'll only get called once though with newProgress as
2545 // 100 when everything is loaded. (onPageFinished is called once
2546 // when the main frame completes loading regardless of the state of
2547 // any sub frames so calls to onProgressChanges may continue after
2548 // onPageFinished has executed)
2549 if (mInLoad) {
2550 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002551 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002552 // If the options menu is open, leave the title bar
2553 if (!mOptionsMenuOpen || !mIconView) {
2554 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002555 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002556 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002557 } else if (!mInLoad) {
2558 // onPageFinished may have already been called but a subframe is
2559 // still loading and updating the progress. Reset mInLoad and update
2560 // the menu items.
2561 mInLoad = true;
2562 updateInLoadMenuItems();
2563 if (!mOptionsMenuOpen || mIconView) {
2564 // This page has begun to load, so show the title bar
2565 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002566 }
2567 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002568 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002569
Grace Kloba22ac16e2009-10-07 18:00:23 -07002570 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2571 if (mCustomView != null)
2572 return;
2573
2574 // Add the custom view to its container.
2575 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2576 mCustomView = view;
2577 mCustomViewCallback = callback;
2578 // Save the menu state and set it to empty while the custom
2579 // view is showing.
2580 mOldMenuState = mMenuState;
2581 mMenuState = EMPTY_MENU;
2582 // Hide the content view.
2583 mContentView.setVisibility(View.GONE);
2584 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002585 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002586 mCustomViewContainer.setVisibility(View.VISIBLE);
2587 mCustomViewContainer.bringToFront();
2588 }
2589
2590 void onHideCustomView() {
2591 if (mCustomView == null)
2592 return;
2593
2594 // Hide the custom view.
2595 mCustomView.setVisibility(View.GONE);
2596 // Remove the custom view from its container.
2597 mCustomViewContainer.removeView(mCustomView);
2598 mCustomView = null;
2599 // Reset the old menu state.
2600 mMenuState = mOldMenuState;
2601 mOldMenuState = EMPTY_MENU;
2602 mCustomViewContainer.setVisibility(View.GONE);
2603 mCustomViewCallback.onCustomViewHidden();
2604 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002605 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002606 mContentView.setVisibility(View.VISIBLE);
2607 }
2608
2609 Bitmap getDefaultVideoPoster() {
2610 if (mDefaultVideoPoster == null) {
2611 mDefaultVideoPoster = BitmapFactory.decodeResource(
2612 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002613 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002614 return mDefaultVideoPoster;
2615 }
Patrick Scott3918d442009-08-04 13:22:29 -04002616
Grace Kloba22ac16e2009-10-07 18:00:23 -07002617 View getVideoLoadingProgressView() {
2618 if (mVideoProgressView == null) {
2619 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2620 mVideoProgressView = inflater.inflate(
2621 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002622 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002623 return mVideoProgressView;
2624 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002625
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002626 /*
2627 * The Object used to inform the WebView of the file to upload.
2628 */
2629 private ValueCallback<Uri> mUploadMessage;
2630
Grace Kloba22ac16e2009-10-07 18:00:23 -07002631 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2632 if (mUploadMessage != null) return;
2633 mUploadMessage = uploadMsg;
2634 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2635 i.addCategory(Intent.CATEGORY_OPENABLE);
2636 i.setType("*/*");
2637 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2638 getString(R.string.choose_upload)), FILE_SELECTED);
2639 }
2640
2641 // -------------------------------------------------------------------------
2642 // Implement functions for DownloadListener
2643 // -------------------------------------------------------------------------
2644
The Android Open Source Project0c908882009-03-03 19:32:16 -08002645 /**
2646 * Notify the host application a download should be done, or that
2647 * the data should be streamed if a streaming viewer is available.
2648 * @param url The full url to the content that should be downloaded
2649 * @param contentDisposition Content-disposition http header, if
2650 * present.
2651 * @param mimetype The mimetype of the content reported by the server
2652 * @param contentLength The file size reported by the server
2653 */
2654 public void onDownloadStart(String url, String userAgent,
2655 String contentDisposition, String mimetype, long contentLength) {
2656 // if we're dealing wih A/V content that's not explicitly marked
2657 // for download, check if it's streamable.
2658 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002659 || !contentDisposition.regionMatches(
2660 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002661 // query the package manager to see if there's a registered handler
2662 // that matches.
2663 Intent intent = new Intent(Intent.ACTION_VIEW);
2664 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002665 ResolveInfo info = getPackageManager().resolveActivity(intent,
2666 PackageManager.MATCH_DEFAULT_ONLY);
2667 if (info != null) {
2668 ComponentName myName = getComponentName();
2669 // If we resolved to ourselves, we don't want to attempt to
2670 // load the url only to try and download it again.
2671 if (!myName.getPackageName().equals(
2672 info.activityInfo.packageName)
2673 || !myName.getClassName().equals(
2674 info.activityInfo.name)) {
2675 // someone (other than us) knows how to handle this mime
2676 // type with this scheme, don't download.
2677 try {
2678 startActivity(intent);
2679 return;
2680 } catch (ActivityNotFoundException ex) {
2681 if (LOGD_ENABLED) {
2682 Log.d(LOGTAG, "activity not found for " + mimetype
2683 + " over " + Uri.parse(url).getScheme(),
2684 ex);
2685 }
2686 // Best behavior is to fall back to a download in this
2687 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002688 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002689 }
2690 }
2691 }
2692 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2693 }
2694
2695 /**
2696 * Notify the host application a download should be done, even if there
2697 * is a streaming viewer available for thise type.
2698 * @param url The full url to the content that should be downloaded
2699 * @param contentDisposition Content-disposition http header, if
2700 * present.
2701 * @param mimetype The mimetype of the content reported by the server
2702 * @param contentLength The file size reported by the server
2703 */
2704 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2705 String contentDisposition, String mimetype, long contentLength) {
2706
2707 String filename = URLUtil.guessFileName(url,
2708 contentDisposition, mimetype);
2709
2710 // Check to see if we have an SDCard
2711 String status = Environment.getExternalStorageState();
2712 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2713 int title;
2714 String msg;
2715
2716 // Check to see if the SDCard is busy, same as the music app
2717 if (status.equals(Environment.MEDIA_SHARED)) {
2718 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2719 title = R.string.download_sdcard_busy_dlg_title;
2720 } else {
2721 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2722 title = R.string.download_no_sdcard_dlg_title;
2723 }
2724
2725 new AlertDialog.Builder(this)
2726 .setTitle(title)
2727 .setIcon(android.R.drawable.ic_dialog_alert)
2728 .setMessage(msg)
2729 .setPositiveButton(R.string.ok, null)
2730 .show();
2731 return;
2732 }
2733
2734 // java.net.URI is a lot stricter than KURL so we have to undo
2735 // KURL's percent-encoding and redo the encoding using java.net.URI.
2736 URI uri = null;
2737 try {
2738 // Undo the percent-encoding that KURL may have done.
2739 String newUrl = new String(URLUtil.decode(url.getBytes()));
2740 // Parse the url into pieces
2741 WebAddress w = new WebAddress(newUrl);
2742 String frag = null;
2743 String query = null;
2744 String path = w.mPath;
2745 // Break the path into path, query, and fragment
2746 if (path.length() > 0) {
2747 // Strip the fragment
2748 int idx = path.lastIndexOf('#');
2749 if (idx != -1) {
2750 frag = path.substring(idx + 1);
2751 path = path.substring(0, idx);
2752 }
2753 idx = path.lastIndexOf('?');
2754 if (idx != -1) {
2755 query = path.substring(idx + 1);
2756 path = path.substring(0, idx);
2757 }
2758 }
2759 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2760 query, frag);
2761 } catch (Exception e) {
2762 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2763 return;
2764 }
2765
2766 // XXX: Have to use the old url since the cookies were stored using the
2767 // old percent-encoded url.
2768 String cookies = CookieManager.getInstance().getCookie(url);
2769
2770 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002771 values.put(Downloads.COLUMN_URI, uri.toString());
2772 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
2773 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
2774 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002775 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002776 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002777 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002778 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2779 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
2780 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
2781 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002782 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002783 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002784 }
2785 if (mimetype == null) {
2786 // We must have long pressed on a link or image to download it. We
2787 // are not sure of the mimetype in this case, so do a head request
2788 new FetchUrlMimeType(this).execute(values);
2789 } else {
2790 final Uri contentUri =
2791 getContentResolver().insert(Downloads.CONTENT_URI, values);
2792 viewDownloads(contentUri);
2793 }
2794
2795 }
2796
Grace Kloba22ac16e2009-10-07 18:00:23 -07002797 // -------------------------------------------------------------------------
2798
The Android Open Source Project0c908882009-03-03 19:32:16 -08002799 /**
2800 * Resets the lock icon. This method is called when we start a new load and
2801 * know the url to be loaded.
2802 */
2803 private void resetLockIcon(String url) {
2804 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002805 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002806 updateLockIconImage(LOCK_ICON_UNSECURE);
2807 }
2808
The Android Open Source Project0c908882009-03-03 19:32:16 -08002809 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002810 * Update the lock icon to correspond to our latest state.
2811 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002812 private void updateLockIconToLatest() {
2813 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002814 }
2815
2816 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002817 * Updates the lock-icon image in the title-bar.
2818 */
2819 private void updateLockIconImage(int lockIconType) {
2820 Drawable d = null;
2821 if (lockIconType == LOCK_ICON_SECURE) {
2822 d = mSecLockIcon;
2823 } else if (lockIconType == LOCK_ICON_MIXED) {
2824 d = mMixLockIcon;
2825 }
Leon Scroggins68579392009-09-15 15:31:54 -04002826 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002827 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002828 }
2829
2830 /**
2831 * Displays a page-info dialog.
2832 * @param tab The tab to show info about
2833 * @param fromShowSSLCertificateOnError The flag that indicates whether
2834 * this dialog was opened from the SSL-certificate-on-error dialog or
2835 * not. This is important, since we need to know whether to return to
2836 * the parent dialog or simply dismiss.
2837 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002838 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002839 final boolean fromShowSSLCertificateOnError) {
2840 final LayoutInflater factory = LayoutInflater
2841 .from(this);
2842
2843 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2844
2845 final WebView view = tab.getWebView();
2846
2847 String url = null;
2848 String title = null;
2849
2850 if (view == null) {
2851 url = tab.getUrl();
2852 title = tab.getTitle();
2853 } else if (view == mTabControl.getCurrentWebView()) {
2854 // Use the cached title and url if this is the current WebView
2855 url = mUrl;
2856 title = mTitle;
2857 } else {
2858 url = view.getUrl();
2859 title = view.getTitle();
2860 }
2861
2862 if (url == null) {
2863 url = "";
2864 }
2865 if (title == null) {
2866 title = "";
2867 }
2868
2869 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
2870 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
2871
2872 mPageInfoView = tab;
2873 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
2874
2875 AlertDialog.Builder alertDialogBuilder =
2876 new AlertDialog.Builder(this)
2877 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
2878 .setView(pageInfoView)
2879 .setPositiveButton(
2880 R.string.ok,
2881 new DialogInterface.OnClickListener() {
2882 public void onClick(DialogInterface dialog,
2883 int whichButton) {
2884 mPageInfoDialog = null;
2885 mPageInfoView = null;
2886 mPageInfoFromShowSSLCertificateOnError = null;
2887
2888 // if we came here from the SSL error dialog
2889 if (fromShowSSLCertificateOnError) {
2890 // go back to the SSL error dialog
2891 showSSLCertificateOnError(
2892 mSSLCertificateOnErrorView,
2893 mSSLCertificateOnErrorHandler,
2894 mSSLCertificateOnErrorError);
2895 }
2896 }
2897 })
2898 .setOnCancelListener(
2899 new DialogInterface.OnCancelListener() {
2900 public void onCancel(DialogInterface dialog) {
2901 mPageInfoDialog = null;
2902 mPageInfoView = null;
2903 mPageInfoFromShowSSLCertificateOnError = null;
2904
2905 // if we came here from the SSL error dialog
2906 if (fromShowSSLCertificateOnError) {
2907 // go back to the SSL error dialog
2908 showSSLCertificateOnError(
2909 mSSLCertificateOnErrorView,
2910 mSSLCertificateOnErrorHandler,
2911 mSSLCertificateOnErrorError);
2912 }
2913 }
2914 });
2915
2916 // if we have a main top-level page SSL certificate set or a certificate
2917 // error
2918 if (fromShowSSLCertificateOnError ||
2919 (view != null && view.getCertificate() != null)) {
2920 // add a 'View Certificate' button
2921 alertDialogBuilder.setNeutralButton(
2922 R.string.view_certificate,
2923 new DialogInterface.OnClickListener() {
2924 public void onClick(DialogInterface dialog,
2925 int whichButton) {
2926 mPageInfoDialog = null;
2927 mPageInfoView = null;
2928 mPageInfoFromShowSSLCertificateOnError = null;
2929
2930 // if we came here from the SSL error dialog
2931 if (fromShowSSLCertificateOnError) {
2932 // go back to the SSL error dialog
2933 showSSLCertificateOnError(
2934 mSSLCertificateOnErrorView,
2935 mSSLCertificateOnErrorHandler,
2936 mSSLCertificateOnErrorError);
2937 } else {
2938 // otherwise, display the top-most certificate from
2939 // the chain
2940 if (view.getCertificate() != null) {
2941 showSSLCertificate(tab);
2942 }
2943 }
2944 }
2945 });
2946 }
2947
2948 mPageInfoDialog = alertDialogBuilder.show();
2949 }
2950
2951 /**
2952 * Displays the main top-level page SSL certificate dialog
2953 * (accessible from the Page-Info dialog).
2954 * @param tab The tab to show certificate for.
2955 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002956 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002957 final View certificateView =
2958 inflateCertificateView(tab.getWebView().getCertificate());
2959 if (certificateView == null) {
2960 return;
2961 }
2962
2963 LayoutInflater factory = LayoutInflater.from(this);
2964
2965 final LinearLayout placeholder =
2966 (LinearLayout)certificateView.findViewById(R.id.placeholder);
2967
2968 LinearLayout ll = (LinearLayout) factory.inflate(
2969 R.layout.ssl_success, placeholder);
2970 ((TextView)ll.findViewById(R.id.success))
2971 .setText(R.string.ssl_certificate_is_valid);
2972
2973 mSSLCertificateView = tab;
2974 mSSLCertificateDialog =
2975 new AlertDialog.Builder(this)
2976 .setTitle(R.string.ssl_certificate).setIcon(
2977 R.drawable.ic_dialog_browser_certificate_secure)
2978 .setView(certificateView)
2979 .setPositiveButton(R.string.ok,
2980 new DialogInterface.OnClickListener() {
2981 public void onClick(DialogInterface dialog,
2982 int whichButton) {
2983 mSSLCertificateDialog = null;
2984 mSSLCertificateView = null;
2985
2986 showPageInfo(tab, false);
2987 }
2988 })
2989 .setOnCancelListener(
2990 new DialogInterface.OnCancelListener() {
2991 public void onCancel(DialogInterface dialog) {
2992 mSSLCertificateDialog = null;
2993 mSSLCertificateView = null;
2994
2995 showPageInfo(tab, false);
2996 }
2997 })
2998 .show();
2999 }
3000
3001 /**
3002 * Displays the SSL error certificate dialog.
3003 * @param view The target web-view.
3004 * @param handler The SSL error handler responsible for cancelling the
3005 * connection that resulted in an SSL error or proceeding per user request.
3006 * @param error The SSL error object.
3007 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003008 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003009 final WebView view, final SslErrorHandler handler, final SslError error) {
3010
3011 final View certificateView =
3012 inflateCertificateView(error.getCertificate());
3013 if (certificateView == null) {
3014 return;
3015 }
3016
3017 LayoutInflater factory = LayoutInflater.from(this);
3018
3019 final LinearLayout placeholder =
3020 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3021
3022 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3023 LinearLayout ll = (LinearLayout)factory
3024 .inflate(R.layout.ssl_warning, placeholder);
3025 ((TextView)ll.findViewById(R.id.warning))
3026 .setText(R.string.ssl_untrusted);
3027 }
3028
3029 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3030 LinearLayout ll = (LinearLayout)factory
3031 .inflate(R.layout.ssl_warning, placeholder);
3032 ((TextView)ll.findViewById(R.id.warning))
3033 .setText(R.string.ssl_mismatch);
3034 }
3035
3036 if (error.hasError(SslError.SSL_EXPIRED)) {
3037 LinearLayout ll = (LinearLayout)factory
3038 .inflate(R.layout.ssl_warning, placeholder);
3039 ((TextView)ll.findViewById(R.id.warning))
3040 .setText(R.string.ssl_expired);
3041 }
3042
3043 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3044 LinearLayout ll = (LinearLayout)factory
3045 .inflate(R.layout.ssl_warning, placeholder);
3046 ((TextView)ll.findViewById(R.id.warning))
3047 .setText(R.string.ssl_not_yet_valid);
3048 }
3049
3050 mSSLCertificateOnErrorHandler = handler;
3051 mSSLCertificateOnErrorView = view;
3052 mSSLCertificateOnErrorError = error;
3053 mSSLCertificateOnErrorDialog =
3054 new AlertDialog.Builder(this)
3055 .setTitle(R.string.ssl_certificate).setIcon(
3056 R.drawable.ic_dialog_browser_certificate_partially_secure)
3057 .setView(certificateView)
3058 .setPositiveButton(R.string.ok,
3059 new DialogInterface.OnClickListener() {
3060 public void onClick(DialogInterface dialog,
3061 int whichButton) {
3062 mSSLCertificateOnErrorDialog = null;
3063 mSSLCertificateOnErrorView = null;
3064 mSSLCertificateOnErrorHandler = null;
3065 mSSLCertificateOnErrorError = null;
3066
Grace Kloba22ac16e2009-10-07 18:00:23 -07003067 view.getWebViewClient().onReceivedSslError(
3068 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003069 }
3070 })
3071 .setNeutralButton(R.string.page_info_view,
3072 new DialogInterface.OnClickListener() {
3073 public void onClick(DialogInterface dialog,
3074 int whichButton) {
3075 mSSLCertificateOnErrorDialog = null;
3076
3077 // do not clear the dialog state: we will
3078 // need to show the dialog again once the
3079 // user is done exploring the page-info details
3080
3081 showPageInfo(mTabControl.getTabFromView(view),
3082 true);
3083 }
3084 })
3085 .setOnCancelListener(
3086 new DialogInterface.OnCancelListener() {
3087 public void onCancel(DialogInterface dialog) {
3088 mSSLCertificateOnErrorDialog = null;
3089 mSSLCertificateOnErrorView = null;
3090 mSSLCertificateOnErrorHandler = null;
3091 mSSLCertificateOnErrorError = null;
3092
Grace Kloba22ac16e2009-10-07 18:00:23 -07003093 view.getWebViewClient().onReceivedSslError(
3094 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003095 }
3096 })
3097 .show();
3098 }
3099
3100 /**
3101 * Inflates the SSL certificate view (helper method).
3102 * @param certificate The SSL certificate.
3103 * @return The resultant certificate view with issued-to, issued-by,
3104 * issued-on, expires-on, and possibly other fields set.
3105 * If the input certificate is null, returns null.
3106 */
3107 private View inflateCertificateView(SslCertificate certificate) {
3108 if (certificate == null) {
3109 return null;
3110 }
3111
3112 LayoutInflater factory = LayoutInflater.from(this);
3113
3114 View certificateView = factory.inflate(
3115 R.layout.ssl_certificate, null);
3116
3117 // issued to:
3118 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3119 if (issuedTo != null) {
3120 ((TextView) certificateView.findViewById(R.id.to_common))
3121 .setText(issuedTo.getCName());
3122 ((TextView) certificateView.findViewById(R.id.to_org))
3123 .setText(issuedTo.getOName());
3124 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3125 .setText(issuedTo.getUName());
3126 }
3127
3128 // issued by:
3129 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3130 if (issuedBy != null) {
3131 ((TextView) certificateView.findViewById(R.id.by_common))
3132 .setText(issuedBy.getCName());
3133 ((TextView) certificateView.findViewById(R.id.by_org))
3134 .setText(issuedBy.getOName());
3135 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3136 .setText(issuedBy.getUName());
3137 }
3138
3139 // issued on:
3140 String issuedOn = reformatCertificateDate(
3141 certificate.getValidNotBefore());
3142 ((TextView) certificateView.findViewById(R.id.issued_on))
3143 .setText(issuedOn);
3144
3145 // expires on:
3146 String expiresOn = reformatCertificateDate(
3147 certificate.getValidNotAfter());
3148 ((TextView) certificateView.findViewById(R.id.expires_on))
3149 .setText(expiresOn);
3150
3151 return certificateView;
3152 }
3153
3154 /**
3155 * Re-formats the certificate date (Date.toString()) string to
3156 * a properly localized date string.
3157 * @return Properly localized version of the certificate date string and
3158 * the original certificate date string if fails to localize.
3159 * If the original string is null, returns an empty string "".
3160 */
3161 private String reformatCertificateDate(String certificateDate) {
3162 String reformattedDate = null;
3163
3164 if (certificateDate != null) {
3165 Date date = null;
3166 try {
3167 date = java.text.DateFormat.getInstance().parse(certificateDate);
3168 } catch (ParseException e) {
3169 date = null;
3170 }
3171
3172 if (date != null) {
3173 reformattedDate =
3174 DateFormat.getDateFormat(this).format(date);
3175 }
3176 }
3177
3178 return reformattedDate != null ? reformattedDate :
3179 (certificateDate != null ? certificateDate : "");
3180 }
3181
3182 /**
3183 * Displays an http-authentication dialog.
3184 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003185 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003186 final String host, final String realm, final String title,
3187 final String name, final String password, int focusId) {
3188 LayoutInflater factory = LayoutInflater.from(this);
3189 final View v = factory
3190 .inflate(R.layout.http_authentication, null);
3191 if (name != null) {
3192 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3193 }
3194 if (password != null) {
3195 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3196 }
3197
3198 String titleText = title;
3199 if (titleText == null) {
3200 titleText = getText(R.string.sign_in_to).toString().replace(
3201 "%s1", host).replace("%s2", realm);
3202 }
3203
3204 mHttpAuthHandler = handler;
3205 AlertDialog dialog = new AlertDialog.Builder(this)
3206 .setTitle(titleText)
3207 .setIcon(android.R.drawable.ic_dialog_alert)
3208 .setView(v)
3209 .setPositiveButton(R.string.action,
3210 new DialogInterface.OnClickListener() {
3211 public void onClick(DialogInterface dialog,
3212 int whichButton) {
3213 String nm = ((EditText) v
3214 .findViewById(R.id.username_edit))
3215 .getText().toString();
3216 String pw = ((EditText) v
3217 .findViewById(R.id.password_edit))
3218 .getText().toString();
3219 BrowserActivity.this.setHttpAuthUsernamePassword
3220 (host, realm, nm, pw);
3221 handler.proceed(nm, pw);
3222 mHttpAuthenticationDialog = null;
3223 mHttpAuthHandler = null;
3224 }})
3225 .setNegativeButton(R.string.cancel,
3226 new DialogInterface.OnClickListener() {
3227 public void onClick(DialogInterface dialog,
3228 int whichButton) {
3229 handler.cancel();
3230 BrowserActivity.this.resetTitleAndRevertLockIcon();
3231 mHttpAuthenticationDialog = null;
3232 mHttpAuthHandler = null;
3233 }})
3234 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3235 public void onCancel(DialogInterface dialog) {
3236 handler.cancel();
3237 BrowserActivity.this.resetTitleAndRevertLockIcon();
3238 mHttpAuthenticationDialog = null;
3239 mHttpAuthHandler = null;
3240 }})
3241 .create();
3242 // Make the IME appear when the dialog is displayed if applicable.
3243 dialog.getWindow().setSoftInputMode(
3244 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3245 dialog.show();
3246 if (focusId != 0) {
3247 dialog.findViewById(focusId).requestFocus();
3248 } else {
3249 v.findViewById(R.id.username_edit).requestFocus();
3250 }
3251 mHttpAuthenticationDialog = dialog;
3252 }
3253
3254 public int getProgress() {
3255 WebView w = mTabControl.getCurrentWebView();
3256 if (w != null) {
3257 return w.getProgress();
3258 } else {
3259 return 100;
3260 }
3261 }
3262
3263 /**
3264 * Set HTTP authentication password.
3265 *
3266 * @param host The host for the password
3267 * @param realm The realm for the password
3268 * @param username The username for the password. If it is null, it means
3269 * password can't be saved.
3270 * @param password The password
3271 */
3272 public void setHttpAuthUsernamePassword(String host, String realm,
3273 String username,
3274 String password) {
3275 WebView w = mTabControl.getCurrentWebView();
3276 if (w != null) {
3277 w.setHttpAuthUsernamePassword(host, realm, username, password);
3278 }
3279 }
3280
3281 /**
3282 * connectivity manager says net has come or gone... inform the user
3283 * @param up true if net has come up, false if net has gone down
3284 */
3285 public void onNetworkToggle(boolean up) {
3286 if (up == mIsNetworkUp) {
3287 return;
3288 } else if (up) {
3289 mIsNetworkUp = true;
3290 if (mAlertDialog != null) {
3291 mAlertDialog.cancel();
3292 mAlertDialog = null;
3293 }
3294 } else {
3295 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003296 if (mInLoad) {
3297 createAndShowNetworkDialog();
3298 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003299 }
3300 WebView w = mTabControl.getCurrentWebView();
3301 if (w != null) {
3302 w.setNetworkAvailable(up);
3303 }
3304 }
3305
Grace Kloba22ac16e2009-10-07 18:00:23 -07003306 boolean isNetworkUp() {
3307 return mIsNetworkUp;
3308 }
3309
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003310 // This method shows the network dialog alerting the user that the net is
3311 // down. It will only show the dialog if mAlertDialog is null.
3312 private void createAndShowNetworkDialog() {
3313 if (mAlertDialog == null) {
3314 mAlertDialog = new AlertDialog.Builder(this)
3315 .setTitle(R.string.loadSuspendedTitle)
3316 .setMessage(R.string.loadSuspended)
3317 .setPositiveButton(R.string.ok, null)
3318 .show();
3319 }
3320 }
3321
The Android Open Source Project0c908882009-03-03 19:32:16 -08003322 @Override
3323 protected void onActivityResult(int requestCode, int resultCode,
3324 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003325 if (getTopWindow() == null) return;
3326
The Android Open Source Project0c908882009-03-03 19:32:16 -08003327 switch (requestCode) {
3328 case COMBO_PAGE:
3329 if (resultCode == RESULT_OK && intent != null) {
3330 String data = intent.getAction();
3331 Bundle extras = intent.getExtras();
3332 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003333 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003334 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003335 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003336 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003337 dismissSubWindow(currentTab);
3338 if (data != null && data.length() != 0) {
3339 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003340 }
3341 }
3342 }
3343 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003344 // Choose a file from the file picker.
3345 case FILE_SELECTED:
3346 if (null == mUploadMessage) break;
3347 Uri result = intent == null || resultCode != RESULT_OK ? null
3348 : intent.getData();
3349 mUploadMessage.onReceiveValue(result);
3350 mUploadMessage = null;
3351 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003352 default:
3353 break;
3354 }
Leon Scroggins30444232009-09-04 18:36:20 -04003355 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003356 }
3357
3358 /*
3359 * This method is called as a result of the user selecting the options
3360 * menu to see the download window, or when a download changes state. It
3361 * shows the download window ontop of the current window.
3362 */
3363 /* package */ void viewDownloads(Uri downloadRecord) {
3364 Intent intent = new Intent(this,
3365 BrowserDownloadPage.class);
3366 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003367 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003368
3369 }
3370
Leon Scroggins160a7e72009-08-14 18:28:01 -04003371 /**
3372 * Open the Go page.
3373 * @param startWithHistory If true, open starting on the history tab.
3374 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003375 */
Leon Scroggins30444232009-09-04 18:36:20 -04003376 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003377 WebView current = mTabControl.getCurrentWebView();
3378 if (current == null) {
3379 return;
3380 }
3381 Intent intent = new Intent(this,
3382 CombinedBookmarkHistoryActivity.class);
3383 String title = current.getTitle();
3384 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003385 Bitmap thumbnail = createScreenshot(current);
3386
The Android Open Source Project0c908882009-03-03 19:32:16 -08003387 // Just in case the user opens bookmarks before a page finishes loading
3388 // so the current history item, and therefore the page, is null.
3389 if (null == url) {
3390 url = mLastEnteredUrl;
3391 // This can happen.
3392 if (null == url) {
3393 url = mSettings.getHomePage();
3394 }
3395 }
3396 // In case the web page has not yet received its associated title.
3397 if (title == null) {
3398 title = url;
3399 }
3400 intent.putExtra("title", title);
3401 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003402 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003403 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003404 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003405 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003406 if (startWithHistory) {
3407 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3408 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3409 }
3410 startActivityForResult(intent, COMBO_PAGE);
3411 }
3412
3413 // Called when loading from context menu or LOAD_URL message
3414 private void loadURL(WebView view, String url) {
3415 // In case the user enters nothing.
3416 if (url != null && url.length() != 0 && view != null) {
3417 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003418 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003419 view.loadUrl(url);
3420 }
3421 }
3422 }
3423
The Android Open Source Project0c908882009-03-03 19:32:16 -08003424 private String smartUrlFilter(Uri inUri) {
3425 if (inUri != null) {
3426 return smartUrlFilter(inUri.toString());
3427 }
3428 return null;
3429 }
3430
Feng Qianb34f87a2009-03-24 21:27:26 -07003431 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003432 "(?i)" + // switch on case insensitive matching
3433 "(" + // begin group for schema
3434 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003435 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003436 ")" +
3437 "(.*)" );
3438
3439 /**
3440 * Attempts to determine whether user input is a URL or search
3441 * terms. Anything with a space is passed to search.
3442 *
3443 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3444 * "Http://" converts to "http://"
3445 *
3446 * @return Original or modified URL
3447 *
3448 */
3449 String smartUrlFilter(String url) {
3450
3451 String inUrl = url.trim();
3452 boolean hasSpace = inUrl.indexOf(' ') != -1;
3453
3454 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3455 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003456 // force scheme to lowercase
3457 String scheme = matcher.group(1);
3458 String lcScheme = scheme.toLowerCase();
3459 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003460 inUrl = lcScheme + matcher.group(2);
3461 }
3462 if (hasSpace) {
3463 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003464 }
3465 return inUrl;
3466 }
3467 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003468 // FIXME: Is this the correct place to add to searches?
3469 // what if someone else calls this function?
3470 int shortcut = parseUrlShortcut(inUrl);
3471 if (shortcut != SHORTCUT_INVALID) {
3472 Browser.addSearchUrl(mResolver, inUrl);
3473 String query = inUrl.substring(2);
3474 switch (shortcut) {
3475 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003476 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003477 case SHORTCUT_WIKIPEDIA_SEARCH:
3478 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3479 case SHORTCUT_DICTIONARY_SEARCH:
3480 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3481 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003482 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003483 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003484 }
3485 }
3486 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003487 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003488 return URLUtil.guessUrl(inUrl);
3489 }
3490 }
3491
3492 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003493 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003494 }
3495
Ben Murdochbff2d602009-07-01 20:19:05 +01003496 /* package */ void setShouldShowErrorConsole(boolean flag) {
3497 if (flag == mShouldShowErrorConsole) {
3498 // Nothing to do.
3499 return;
3500 }
3501
3502 mShouldShowErrorConsole = flag;
3503
Grace Kloba22ac16e2009-10-07 18:00:23 -07003504 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3505 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003506
3507 if (flag) {
3508 // Setting the show state of the console will cause it's the layout to be inflated.
3509 if (errorConsole.numberOfErrors() > 0) {
3510 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3511 } else {
3512 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3513 }
3514
3515 // Now we can add it to the main view.
3516 mErrorConsoleContainer.addView(errorConsole,
3517 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
3518 ViewGroup.LayoutParams.WRAP_CONTENT));
3519 } else {
3520 mErrorConsoleContainer.removeView(errorConsole);
3521 }
3522
3523 }
3524
Grace Kloba22ac16e2009-10-07 18:00:23 -07003525 boolean shouldShowErrorConsole() {
3526 return mShouldShowErrorConsole;
3527 }
3528
Andrei Popescu163ab742009-10-20 17:58:23 +01003529 private void setStatusBarVisibility(boolean visible) {
3530 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3531 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3532 }
3533
Grace Klobaeb6eef42009-09-15 17:56:32 -07003534 final static int LOCK_ICON_UNSECURE = 0;
3535 final static int LOCK_ICON_SECURE = 1;
3536 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003537
The Android Open Source Project0c908882009-03-03 19:32:16 -08003538 private BrowserSettings mSettings;
3539 private TabControl mTabControl;
3540 private ContentResolver mResolver;
3541 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003542 private View mCustomView;
3543 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003544 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003545
3546 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3547 // view, we should rewrite this.
3548 private int mCurrentMenuState = 0;
3549 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003550 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003551 private static final int EMPTY_MENU = -1;
3552 private Menu mMenu;
3553
3554 private FindDialog mFindDialog;
3555 // Used to prevent chording to result in firing two shortcuts immediately
3556 // one after another. Fixes bug 1211714.
3557 boolean mCanChord;
3558
3559 private boolean mInLoad;
3560 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003561 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003562
The Android Open Source Project0c908882009-03-03 19:32:16 -08003563 private boolean mActivityInPause = true;
3564
3565 private boolean mMenuIsDown;
3566
The Android Open Source Project0c908882009-03-03 19:32:16 -08003567 private static boolean mInTrace;
3568
3569 // Performance probe
3570 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3571 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3572 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3573 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3574 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3575 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3576 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3577 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3578 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3579 };
3580
3581 private long mStart;
3582 private long mProcessStart;
3583 private long mUserStart;
3584 private long mSystemStart;
3585 private long mIdleStart;
3586 private long mIrqStart;
3587
3588 private long mUiStart;
3589
3590 private Drawable mMixLockIcon;
3591 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003592
3593 /* hold a ref so we can auto-cancel if necessary */
3594 private AlertDialog mAlertDialog;
3595
3596 // Wait for credentials before loading google.com
3597 private ProgressDialog mCredsDlg;
3598
3599 // The up-to-date URL and title (these can be different from those stored
3600 // in WebView, since it takes some time for the information in WebView to
3601 // get updated)
3602 private String mUrl;
3603 private String mTitle;
3604
3605 // As PageInfo has different style for landscape / portrait, we have
3606 // to re-open it when configuration changed
3607 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003608 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003609 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3610 // dialog, we should not just dismiss it, but should get back to the
3611 // SSL-certificate-on-error dialog. This flag is used to store this state
3612 private Boolean mPageInfoFromShowSSLCertificateOnError;
3613
3614 // as SSLCertificateOnError has different style for landscape / portrait,
3615 // we have to re-open it when configuration changed
3616 private AlertDialog mSSLCertificateOnErrorDialog;
3617 private WebView mSSLCertificateOnErrorView;
3618 private SslErrorHandler mSSLCertificateOnErrorHandler;
3619 private SslError mSSLCertificateOnErrorError;
3620
3621 // as SSLCertificate has different style for landscape / portrait, we
3622 // have to re-open it when configuration changed
3623 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003624 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003625
3626 // as HttpAuthentication has different style for landscape / portrait, we
3627 // have to re-open it when configuration changed
3628 private AlertDialog mHttpAuthenticationDialog;
3629 private HttpAuthHandler mHttpAuthHandler;
3630
3631 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3632 new FrameLayout.LayoutParams(
3633 ViewGroup.LayoutParams.FILL_PARENT,
3634 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003635 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3636 new FrameLayout.LayoutParams(
3637 ViewGroup.LayoutParams.FILL_PARENT,
3638 ViewGroup.LayoutParams.FILL_PARENT,
3639 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003640 // Google search
3641 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003642 // Wikipedia search
3643 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3644 // Dictionary search
3645 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3646 // Google Mobile Local search
3647 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3648
3649 final static String QUERY_PLACE_HOLDER = "%s";
3650
3651 // "source" parameter for Google search through search key
3652 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3653 // "source" parameter for Google search through goto menu
3654 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3655 // "source" parameter for Google search through simplily type
3656 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3657 // "source" parameter for Google search suggested by the browser
3658 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3659 // "source" parameter for Google search from unknown source
3660 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3661
3662 private final static String LOGTAG = "browser";
3663
The Android Open Source Project0c908882009-03-03 19:32:16 -08003664 private String mLastEnteredUrl;
3665
3666 private PowerManager.WakeLock mWakeLock;
3667 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3668
3669 private Toast mStopToast;
3670
Leon Scroggins68579392009-09-15 15:31:54 -04003671 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003672
Ben Murdochbff2d602009-07-01 20:19:05 +01003673 private LinearLayout mErrorConsoleContainer = null;
3674 private boolean mShouldShowErrorConsole = false;
3675
The Android Open Source Project0c908882009-03-03 19:32:16 -08003676 // As the ids are dynamically created, we can't guarantee that they will
3677 // be in sequence, so this static array maps ids to a window number.
3678 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3679 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3680 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3681 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3682
3683 // monitor platform changes
3684 private IntentFilter mNetworkStateChangedFilter;
3685 private BroadcastReceiver mNetworkStateIntentReceiver;
3686
Grace Klobab4da0ad2009-05-14 14:45:40 -07003687 private BroadcastReceiver mPackageInstallationReceiver;
3688
The Android Open Source Project0c908882009-03-03 19:32:16 -08003689 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003690 final static int COMBO_PAGE = 1;
3691 final static int DOWNLOAD_PAGE = 2;
3692 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003693 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003694
Andrei Popescu540035d2009-09-18 18:59:20 +01003695 // the default <video> poster
3696 private Bitmap mDefaultVideoPoster;
3697 // the video progress view
3698 private View mVideoProgressView;
3699
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003700 /**
3701 * A UrlData class to abstract how the content will be set to WebView.
3702 * This base class uses loadUrl to show the content.
3703 */
3704 private static class UrlData {
3705 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07003706 byte[] mPostData;
3707
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003708 UrlData(String url) {
3709 this.mUrl = url;
3710 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003711
3712 void setPostData(byte[] postData) {
3713 mPostData = postData;
3714 }
3715
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003716 boolean isEmpty() {
3717 return mUrl == null || mUrl.length() == 0;
3718 }
3719
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003720 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07003721 if (mPostData != null) {
3722 webView.postUrl(mUrl, mPostData);
3723 } else {
3724 webView.loadUrl(mUrl);
3725 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003726 }
3727 };
3728
3729 /**
3730 * A subclass of UrlData class that can display inlined content using
3731 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
3732 */
3733 private static class InlinedUrlData extends UrlData {
3734 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
3735 super(failUrl);
3736 mInlined = inlined;
3737 mMimeType = mimeType;
3738 mEncoding = encoding;
3739 }
3740 String mMimeType;
3741 String mInlined;
3742 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003743 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003744 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01003745 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003746 }
3747
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003748 @Override
3749 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003750 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
3751 }
3752 }
3753
Leon Scroggins1f005d32009-08-10 17:36:42 -04003754 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003755}