blob: 3b117df58018043b7e0ae067819e15b4f6790f96 [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
The Android Open Source Project0c908882009-03-03 19:32:16 -080019import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080020import android.app.AlertDialog;
21import android.app.ProgressDialog;
22import android.app.SearchManager;
23import android.content.ActivityNotFoundException;
24import android.content.BroadcastReceiver;
25import android.content.ComponentName;
26import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040027import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080028import android.content.ContentValues;
29import android.content.Context;
30import android.content.DialogInterface;
31import android.content.Intent;
32import android.content.IntentFilter;
33import android.content.ServiceConnection;
Grace Klobab4da0ad2009-05-14 14:45:40 -070034import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080035import android.content.pm.PackageManager;
36import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080037import android.content.res.Configuration;
38import android.content.res.Resources;
39import android.database.Cursor;
The Android Open Source Project0c908882009-03-03 19:32:16 -080040import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010041import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080042import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080043import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040044import android.graphics.PixelFormat;
45import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080046import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080047import android.net.ConnectivityManager;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -040048import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.net.Uri;
50import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.net.http.SslCertificate;
52import android.net.http.SslError;
53import android.os.AsyncTask;
54import android.os.Bundle;
55import android.os.Debug;
56import android.os.Environment;
57import android.os.Handler;
58import android.os.IBinder;
59import android.os.Message;
60import android.os.PowerManager;
61import android.os.Process;
62import android.os.RemoteException;
63import android.os.ServiceManager;
64import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080065import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040066import android.provider.ContactsContract;
67import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.provider.Downloads;
69import android.provider.MediaStore;
The Android Open Source Project0c908882009-03-03 19:32:16 -080070import android.text.IClipboard;
71import android.text.TextUtils;
72import android.text.format.DateFormat;
Leon Scrogginsb94bf272009-09-25 15:22:08 -040073import android.util.AttributeSet;
The Android Open Source Project0c908882009-03-03 19:32:16 -080074import android.util.Log;
75import android.view.ContextMenu;
76import android.view.Gravity;
77import android.view.KeyEvent;
78import android.view.LayoutInflater;
79import android.view.Menu;
80import android.view.MenuInflater;
81import android.view.MenuItem;
82import android.view.View;
83import android.view.ViewGroup;
84import android.view.Window;
85import android.view.WindowManager;
86import android.view.ContextMenu.ContextMenuInfo;
87import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080088import android.webkit.CookieManager;
89import android.webkit.CookieSyncManager;
90import android.webkit.DownloadListener;
91import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070092import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080093import android.webkit.SslErrorHandler;
94import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010095import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080096import android.webkit.WebChromeClient;
97import android.webkit.WebHistoryItem;
98import android.webkit.WebIconDatabase;
99import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800100import android.widget.EditText;
101import android.widget.FrameLayout;
102import android.widget.LinearLayout;
103import android.widget.TextView;
104import android.widget.Toast;
105
Dan Egnor5ee906c2009-11-18 12:11:49 -0800106import com.android.common.Patterns;
107
108import com.google.android.googleapps.IGoogleLoginService;
109import com.google.android.googlelogin.GoogleLoginServiceConstants;
110
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400111import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800112import java.io.File;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800113import java.net.MalformedURLException;
114import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700115import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800116import java.net.URL;
117import java.net.URLEncoder;
118import java.text.ParseException;
119import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import java.util.HashMap;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800121import java.util.regex.Matcher;
122import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800123
124public class BrowserActivity extends Activity
Grace Kloba5942df02009-09-18 11:48:29 -0700125 implements View.OnCreateContextMenuListener,
The Android Open Source Project0c908882009-03-03 19:32:16 -0800126 DownloadListener {
127
Dave Bort31a6d1c2009-04-13 15:56:49 -0700128 /* Define some aliases to make these debugging flags easier to refer to.
129 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
130 */
131 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
132 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
133 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
134
The Android Open Source Project0c908882009-03-03 19:32:16 -0800135 private IGoogleLoginService mGls = null;
136 private ServiceConnection mGlsConnection = null;
137
Satish Sampath565505b2009-05-29 15:37:27 +0100138 // These are single-character shortcuts for searching popular sources.
139 private static final int SHORTCUT_INVALID = 0;
140 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
141 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
142 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
143 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
144
The Android Open Source Project0c908882009-03-03 19:32:16 -0800145 private void setupHomePage() {
146 final Runnable getAccount = new Runnable() {
147 public void run() {
148 // Lower priority
149 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
150 // get the default home page
151 String homepage = mSettings.getHomePage();
152
153 try {
154 if (mGls == null) return;
155
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700156 if (!homepage.startsWith("http://www.google.")) return;
157 if (homepage.indexOf('?') == -1) return;
158
The Android Open Source Project0c908882009-03-03 19:32:16 -0800159 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
160 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
161
162 // three cases:
163 //
164 // hostedUser == googleUser
165 // The device has only a google account
166 //
167 // hostedUser != googleUser
168 // The device has a hosted account and a google account
169 //
170 // hostedUser != null, googleUser == null
171 // The device has only a hosted account (so far)
172
173 // developers might have no accounts at all
174 if (hostedUser == null) return;
175
176 if (googleUser == null || !hostedUser.equals(googleUser)) {
177 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700178 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800179 }
180 } catch (RemoteException ignore) {
181 // Login service died; carry on
182 } catch (RuntimeException ignore) {
183 // Login service died; carry on
184 } finally {
185 finish(homepage);
186 }
187 }
188
189 private void finish(final String homepage) {
190 mHandler.post(new Runnable() {
191 public void run() {
192 mSettings.setHomePage(BrowserActivity.this, homepage);
193 resumeAfterCredentials();
194
195 // as this is running in a separate thread,
196 // BrowserActivity's onDestroy() may have been called,
197 // which also calls unbindService().
198 if (mGlsConnection != null) {
199 // we no longer need to keep GLS open
200 unbindService(mGlsConnection);
201 mGlsConnection = null;
202 }
203 } });
204 } };
205
206 final boolean[] done = { false };
207
208 // Open a connection to the Google Login Service. The first
209 // time the connection is established, set up the homepage depending on
210 // the account in a background thread.
211 mGlsConnection = new ServiceConnection() {
212 public void onServiceConnected(ComponentName className, IBinder service) {
213 mGls = IGoogleLoginService.Stub.asInterface(service);
214 if (done[0] == false) {
215 done[0] = true;
216 Thread account = new Thread(getAccount);
217 account.setName("GLSAccount");
218 account.start();
219 }
220 }
221 public void onServiceDisconnected(ComponentName className) {
222 mGls = null;
223 }
224 };
225
226 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
227 mGlsConnection, Context.BIND_AUTO_CREATE);
228 }
229
Cary Clarka9771242009-08-11 16:42:26 -0400230 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800231 @Override
232 public Void doInBackground(File... files) {
233 if (files != null) {
234 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400235 if (!f.delete()) {
236 Log.e(LOGTAG, f.getPath() + " was not deleted");
237 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800238 }
239 }
240 return null;
241 }
242 }
243
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400244 /**
245 * This layout holds everything you see below the status bar, including the
246 * error console, the custom view container, and the webviews.
247 */
248 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400249
Grace Kloba22ac16e2009-10-07 18:00:23 -0700250 @Override
251 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700252 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800253 Log.v(LOGTAG, this + " onStart");
254 }
255 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800256 // test the browser in OpenGL
257 // requestWindowFeature(Window.FEATURE_OPENGL);
258
259 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
260
261 mResolver = getContentResolver();
262
Grace Kloba0923d692009-09-23 21:37:25 -0700263 // If this was a web search request, pass it on to the default web
264 // search provider and finish this activity.
265 if (handleWebSearchIntent(getIntent())) {
266 finish();
267 return;
268 }
269
The Android Open Source Project0c908882009-03-03 19:32:16 -0800270 mSecLockIcon = Resources.getSystem().getDrawable(
271 android.R.drawable.ic_secure);
272 mMixLockIcon = Resources.getSystem().getDrawable(
273 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800274
Leon Scroggins81db3662009-06-04 17:45:11 -0400275 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
276 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400277 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
278 .inflate(R.layout.custom_screen, null);
279 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
280 R.id.main_content);
281 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
282 .findViewById(R.id.error_console);
283 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
284 .findViewById(R.id.fullscreen_custom_content);
285 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400286 mTitleBar = new TitleBar(this);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400287 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800288
289 // Create the tab control and our initial tab
290 mTabControl = new TabControl(this);
291
292 // Open the icon database and retain all the bookmark urls for favicons
293 retainIconsOnStartup();
294
295 // Keep a settings instance handy.
296 mSettings = BrowserSettings.getInstance();
297 mSettings.setTabControl(mTabControl);
298 mSettings.loadFromDb(this);
299
300 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
301 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
302
Grace Klobaa34f6862009-07-31 16:28:17 -0700303 /* enables registration for changes in network status from
304 http stack */
305 mNetworkStateChangedFilter = new IntentFilter();
306 mNetworkStateChangedFilter.addAction(
307 ConnectivityManager.CONNECTIVITY_ACTION);
308 mNetworkStateIntentReceiver = new BroadcastReceiver() {
309 @Override
310 public void onReceive(Context context, Intent intent) {
311 if (intent.getAction().equals(
312 ConnectivityManager.CONNECTIVITY_ACTION)) {
Robert Greenwalt7d899d62009-10-23 10:33:48 -0700313 boolean noConnectivity = intent.getBooleanExtra(
314 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
315 onNetworkToggle(!noConnectivity);
Grace Klobaa34f6862009-07-31 16:28:17 -0700316 }
317 }
318 };
319
Grace Kloba615c6c92009-08-03 10:22:44 -0700320 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
321 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
322 filter.addDataScheme("package");
323 mPackageInstallationReceiver = new BroadcastReceiver() {
324 @Override
325 public void onReceive(Context context, Intent intent) {
326 final String action = intent.getAction();
327 final String packageName = intent.getData()
328 .getSchemeSpecificPart();
329 final boolean replacing = intent.getBooleanExtra(
330 Intent.EXTRA_REPLACING, false);
331 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
332 // if it is replacing, refreshPlugins() when adding
333 return;
334 }
335 PackageManager pm = BrowserActivity.this.getPackageManager();
336 PackageInfo pkgInfo = null;
337 try {
338 pkgInfo = pm.getPackageInfo(packageName,
339 PackageManager.GET_PERMISSIONS);
340 } catch (PackageManager.NameNotFoundException e) {
341 return;
342 }
343 if (pkgInfo != null) {
344 String permissions[] = pkgInfo.requestedPermissions;
345 if (permissions == null) {
346 return;
347 }
348 boolean permissionOk = false;
349 for (String permit : permissions) {
350 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
351 permissionOk = true;
352 break;
353 }
354 }
355 if (permissionOk) {
356 PluginManager.getInstance(BrowserActivity.this)
357 .refreshPlugins(
358 Intent.ACTION_PACKAGE_ADDED
359 .equals(action));
360 }
361 }
362 }
363 };
364 registerReceiver(mPackageInstallationReceiver, filter);
365
The Android Open Source Project0c908882009-03-03 19:32:16 -0800366 if (!mTabControl.restoreState(icicle)) {
367 // clear up the thumbnail directory if we can't restore the state as
368 // none of the files in the directory are referenced any more.
369 new ClearThumbnails().execute(
370 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700371 // there is no quit on Android. But if we can't restore the state,
372 // we can treat it as a new Browser, remove the old session cookies.
373 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800374 final Intent intent = getIntent();
375 final Bundle extra = intent.getExtras();
376 // Create an initial tab.
377 // If the intent is ACTION_VIEW and data is not null, the Browser is
378 // invoked to view the content by another application. In this case,
379 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700380 UrlData urlData = getUrlDataFromIntent(intent);
381
Grace Kloba22ac16e2009-10-07 18:00:23 -0700382 final Tab t = mTabControl.createNewTab(
The Android Open Source Project0c908882009-03-03 19:32:16 -0800383 Intent.ACTION_VIEW.equals(intent.getAction()) &&
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700384 intent.getData() != null,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700385 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800386 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800387 attachTabToContentView(t);
388 WebView webView = t.getWebView();
389 if (extra != null) {
390 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
391 if (scale > 0 && scale <= 1000) {
392 webView.setInitialScale(scale);
393 }
394 }
395 // If we are not restoring from an icicle, then there is a high
396 // likely hood this is the first run. So, check to see if the
397 // homepage needs to be configured and copy any plugins from our
398 // asset directory to the data partition.
399 if ((extra == null || !extra.getBoolean("testing"))
400 && !mSettings.isLoginInitialized()) {
401 setupHomePage();
402 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800403
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700404 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400405 if (mSettings.isLoginInitialized()) {
406 webView.loadUrl(mSettings.getHomePage());
407 } else {
408 waitForCredentials();
409 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800410 } else {
Grace Kloba81678d92009-06-30 07:09:56 -0700411 if (extra != null) {
412 urlData.setPostData(extra
413 .getByteArray(Browser.EXTRA_POST_DATA));
414 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700415 urlData.loadIn(webView);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800416 }
417 } else {
418 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400419 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800420 attachTabToContentView(mTabControl.getCurrentTab());
421 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700422
Feng Qianb3c02da2009-06-29 15:58:08 -0700423 // Read JavaScript flags if it exists.
424 String jsFlags = mSettings.getJsFlags();
425 if (jsFlags.trim().length() != 0) {
426 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
427 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800428 }
429
430 @Override
431 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700432 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800433 // When a tab is closed on exit, the current tab index is set to -1.
434 // Reset before proceed as Browser requires the current tab to be set.
435 if (current == null) {
436 // Try to reset the tab in case the index was incorrect.
437 current = mTabControl.getTab(0);
438 if (current == null) {
439 // No tabs at all so just ignore this intent.
440 return;
441 }
442 mTabControl.setCurrentTab(current);
443 attachTabToContentView(current);
444 resetTitleAndIcon(current.getWebView());
445 }
446 final String action = intent.getAction();
447 final int flags = intent.getFlags();
448 if (Intent.ACTION_MAIN.equals(action) ||
449 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
450 // just resume the browser
451 return;
452 }
453 if (Intent.ACTION_VIEW.equals(action)
454 || Intent.ACTION_SEARCH.equals(action)
455 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
456 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100457 // If this was a search request (e.g. search query directly typed into the address bar),
458 // pass it on to the default web search provider.
459 if (handleWebSearchIntent(intent)) {
460 return;
461 }
462
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700463 UrlData urlData = getUrlDataFromIntent(intent);
464 if (urlData.isEmpty()) {
465 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800466 }
Grace Kloba81678d92009-06-30 07:09:56 -0700467 urlData.setPostData(intent
468 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700469
Grace Klobacc634032009-07-28 15:58:19 -0700470 final String appId = intent
471 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
472 if (Intent.ACTION_VIEW.equals(action)
473 && !getPackageName().equals(appId)
474 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700475 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700476 if (appTab != null) {
477 Log.i(LOGTAG, "Reusing tab for " + appId);
478 // Dismiss the subwindow if applicable.
479 dismissSubWindow(appTab);
480 // Since we might kill the WebView, remove it from the
481 // content view first.
482 removeTabFromContentView(appTab);
483 // Recreate the main WebView after destroying the old one.
484 // If the WebView has the same original url and is on that
485 // page, it can be reused.
486 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700487 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100488
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700489 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400490 switchToTab(mTabControl.getTabIndex(appTab));
491 if (needsLoad) {
492 urlData.loadIn(appTab.getWebView());
493 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700494 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400495 // If the tab was the current tab, we have to attach
496 // it to the view system again.
497 attachTabToContentView(appTab);
498 if (needsLoad) {
499 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700500 }
501 }
502 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400503 } else {
504 // No matching application tab, try to find a regular tab
505 // with a matching url.
506 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400507 if (appTab != null) {
508 if (current != appTab) {
509 switchToTab(mTabControl.getTabIndex(appTab));
510 }
511 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400512 } else {
513 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
514 // will be opened in a new tab unless we have reached
515 // MAX_TABS. Then the url will be opened in the current
516 // tab. If a new tab is created, it will have "true" for
517 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400518 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400519 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700520 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800521 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800522 if (!urlData.isEmpty()
523 && urlData.mUrl.startsWith("about:debug")) {
524 if ("about:debug.dom".equals(urlData.mUrl)) {
525 current.getWebView().dumpDomTree(false);
526 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
527 current.getWebView().dumpDomTree(true);
528 } else if ("about:debug.render".equals(urlData.mUrl)) {
529 current.getWebView().dumpRenderTree(false);
530 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
531 current.getWebView().dumpRenderTree(true);
532 } else if ("about:debug.display".equals(urlData.mUrl)) {
533 current.getWebView().dumpDisplayTree();
534 } else {
535 mSettings.toggleDebugSettings();
536 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800537 return;
538 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400539 // Get rid of the subwindow if it exists
540 dismissSubWindow(current);
541 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800542 }
543 }
544 }
545
Satish Sampath565505b2009-05-29 15:37:27 +0100546 private int parseUrlShortcut(String url) {
547 if (url == null) return SHORTCUT_INVALID;
548
549 // FIXME: quick search, need to be customized by setting
550 if (url.length() > 2 && url.charAt(1) == ' ') {
551 switch (url.charAt(0)) {
552 case 'g': return SHORTCUT_GOOGLE_SEARCH;
553 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
554 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
555 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
556 }
557 }
558 return SHORTCUT_INVALID;
559 }
560
561 /**
562 * Launches the default web search activity with the query parameters if the given intent's data
563 * are identified as plain search terms and not URLs/shortcuts.
564 * @return true if the intent was handled and web search activity was launched, false if not.
565 */
566 private boolean handleWebSearchIntent(Intent intent) {
567 if (intent == null) return false;
568
569 String url = null;
570 final String action = intent.getAction();
571 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700572 Uri data = intent.getData();
573 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100574 } else if (Intent.ACTION_SEARCH.equals(action)
575 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
576 || Intent.ACTION_WEB_SEARCH.equals(action)) {
577 url = intent.getStringExtra(SearchManager.QUERY);
578 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100579 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
580 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100581 }
582
583 /**
584 * Launches the default web search activity with the query parameters if the given url string
585 * was identified as plain search terms and not URL/shortcut.
586 * @return true if the request was handled and web search activity was launched, false if not.
587 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100588 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100589 if (inUrl == null) return false;
590
591 // In general, we shouldn't modify URL from Intent.
592 // But currently, we get the user-typed URL from search box as well.
593 String url = fixUrl(inUrl).trim();
594
595 // URLs and site specific search shortcuts are handled by the regular flow of control, so
596 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800597 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100598 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100599 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
600 return false;
601 }
602
603 Browser.updateVisitedHistory(mResolver, url, false);
604 Browser.addSearchUrl(mResolver, url);
605
606 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
607 intent.addCategory(Intent.CATEGORY_DEFAULT);
608 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100609 if (appData != null) {
610 intent.putExtra(SearchManager.APP_DATA, appData);
611 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100612 if (extraData != null) {
613 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
614 }
Grace Klobacc634032009-07-28 15:58:19 -0700615 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100616 startActivity(intent);
617
618 return true;
619 }
620
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700621 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800622 String url = null;
623 if (intent != null) {
624 final String action = intent.getAction();
625 if (Intent.ACTION_VIEW.equals(action)) {
626 url = smartUrlFilter(intent.getData());
627 if (url != null && url.startsWith("content:")) {
628 /* Append mimetype so webview knows how to display */
629 String mimeType = intent.resolveType(getContentResolver());
630 if (mimeType != null) {
631 url += "?" + mimeType;
632 }
633 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700634 if ("inline:".equals(url)) {
635 return new InlinedUrlData(
636 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
637 intent.getType(),
638 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
639 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
640 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800641 } else if (Intent.ACTION_SEARCH.equals(action)
642 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
643 || Intent.ACTION_WEB_SEARCH.equals(action)) {
644 url = intent.getStringExtra(SearchManager.QUERY);
645 if (url != null) {
646 mLastEnteredUrl = url;
647 // Don't add Urls, just search terms.
648 // Urls will get added when the page is loaded.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800649 if (!Patterns.WEB_URL.matcher(url).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800650 Browser.updateVisitedHistory(mResolver, url, false);
651 }
652 // In general, we shouldn't modify URL from Intent.
653 // But currently, we get the user-typed URL from search box as well.
654 url = fixUrl(url);
655 url = smartUrlFilter(url);
656 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
657 if (url.contains(searchSource)) {
658 String source = null;
659 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
660 if (appData != null) {
661 source = appData.getString(SearchManager.SOURCE);
662 }
663 if (TextUtils.isEmpty(source)) {
664 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
665 }
666 url = url.replace(searchSource, "&source=android-"+source+"&");
667 }
668 }
669 }
670 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700671 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800672 }
673
674 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400675 // FIXME: Converting the url to lower case
676 // duplicates functionality in smartUrlFilter().
677 // However, changing all current callers of fixUrl to
678 // call smartUrlFilter in addition may have unwanted
679 // consequences, and is deferred for now.
680 int colon = inUrl.indexOf(':');
681 boolean allLower = true;
682 for (int index = 0; index < colon; index++) {
683 char ch = inUrl.charAt(index);
684 if (!Character.isLetter(ch)) {
685 break;
686 }
687 allLower &= Character.isLowerCase(ch);
688 if (index == colon - 1 && !allLower) {
689 inUrl = inUrl.substring(0, colon).toLowerCase()
690 + inUrl.substring(colon);
691 }
692 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800693 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
694 return inUrl;
695 if (inUrl.startsWith("http:") ||
696 inUrl.startsWith("https:")) {
697 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
698 inUrl = inUrl.replaceFirst("/", "//");
699 } else inUrl = inUrl.replaceFirst(":", "://");
700 }
701 return inUrl;
702 }
703
Grace Kloba22ac16e2009-10-07 18:00:23 -0700704 @Override
705 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800706 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700707 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800708 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
709 }
710
711 if (!mActivityInPause) {
712 Log.e(LOGTAG, "BrowserActivity is already resumed.");
713 return;
714 }
715
Mike Reed7bfa63b2009-05-28 11:08:32 -0400716 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800717 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400718 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800719
720 if (mWakeLock.isHeld()) {
721 mHandler.removeMessages(RELEASE_WAKELOCK);
722 mWakeLock.release();
723 }
724
725 if (mCredsDlg != null) {
726 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
727 // In case credential request never comes back
728 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
729 }
730 }
731
732 registerReceiver(mNetworkStateIntentReceiver,
733 mNetworkStateChangedFilter);
734 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800735 }
736
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400737 /**
738 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400739 * would change its appearance, use a different TitleBar to show overlayed
740 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400741 */
742 private TitleBar mFakeTitleBar;
743
744 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400745 * Holder for the fake title bar. It will have a foreground shadow, as well
746 * as a white background, so the fake title bar looks like the real one.
747 */
748 private ViewGroup mFakeTitleBarHolder;
749
750 /**
751 * Layout parameters for the fake title bar within mFakeTitleBarHolder
752 */
753 private FrameLayout.LayoutParams mFakeTitleBarParams
754 = new FrameLayout.LayoutParams(
Leon Scrogginsc01e4a82009-09-16 14:41:00 -0400755 ViewGroup.LayoutParams.FILL_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400756 ViewGroup.LayoutParams.WRAP_CONTENT);
757 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400758 * Keeps track of whether the options menu is open. This is important in
759 * determining whether to show or hide the title bar overlay.
760 */
761 private boolean mOptionsMenuOpen;
762
763 /**
764 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
765 * of whether the configuration has changed. The first onMenuOpened call
766 * after a configuration change is simply a reopening of the same menu
767 * (i.e. mIconView did not change).
768 */
769 private boolean mConfigChanged;
770
771 /**
772 * Whether or not the options menu is in its smaller, icon menu form. When
773 * true, we want the title bar overlay to be up. When false, we do not.
774 * Only meaningful if mOptionsMenuOpen is true.
775 */
776 private boolean mIconView;
777
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400778 @Override
779 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400780 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
781 if (mOptionsMenuOpen) {
782 if (mConfigChanged) {
783 // We do not need to make any changes to the state of the
784 // title bar, since the only thing that happened was a
785 // change in orientation
786 mConfigChanged = false;
787 } else {
788 if (mIconView) {
789 // Switching the menu to expanded view, so hide the
790 // title bar.
791 hideFakeTitleBar();
792 mIconView = false;
793 } else {
794 // Switching the menu back to icon view, so show the
795 // title bar once again.
796 showFakeTitleBar();
797 mIconView = true;
798 }
799 }
800 } else {
801 // The options menu is closed, so open it, and show the title
802 showFakeTitleBar();
803 mOptionsMenuOpen = true;
804 mConfigChanged = false;
805 mIconView = true;
806 }
807 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400808 return true;
809 }
810
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400811 /**
812 * Special class used exclusively for the shadow drawn underneath the fake
813 * title bar. The shadow does not need to be drawn if the WebView
814 * underneath is scrolled to the top, because it will draw directly on top
815 * of the embedded shadow.
816 */
817 private static class Shadow extends View {
818 private WebView mWebView;
819
820 public Shadow(Context context, AttributeSet attrs) {
821 super(context, attrs);
822 }
823
824 public void setWebView(WebView view) {
825 mWebView = view;
826 }
827
828 @Override
829 public void draw(Canvas canvas) {
830 // In general onDraw is the method to override, but we care about
831 // whether or not the background gets drawn, which happens in draw()
832 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
833 super.draw(canvas);
834 }
835 // Need to invalidate so that if the scroll position changes, we
836 // still draw as appropriate.
837 invalidate();
838 }
839 }
840
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400841 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400842 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400843 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400844 && !mActivityInPause && decor != null
845 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400846 Rect visRect = new Rect();
847 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
848 if (LOGD_ENABLED) {
849 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
850 }
851 return;
852 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400853
854 WindowManager manager
855 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
856
857 // Add the title bar to the window manager so it can receive touches
858 // while the menu is up
859 WindowManager.LayoutParams params
860 = new WindowManager.LayoutParams(
861 ViewGroup.LayoutParams.FILL_PARENT,
862 ViewGroup.LayoutParams.WRAP_CONTENT,
863 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
864 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400865 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400866 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400867 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400868 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400869 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400870 // XXX : Without providing an offset, the fake title bar will be
871 // placed underneath the status bar. Use the global visible rect
872 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400873 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400874 // Add a holder for the title bar. It also holds a shadow to show
875 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400876 if (mFakeTitleBarHolder == null) {
877 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
878 .inflate(R.layout.title_bar_bg, null);
879 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400880 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
881 R.id.shadow);
882 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400883 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400884 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400885 }
886 }
887
888 @Override
889 public void onOptionsMenuClosed(Menu menu) {
890 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400891 if (!mInLoad) {
892 hideFakeTitleBar();
893 } else if (!mIconView) {
894 // The page is currently loading, and we are in expanded mode, so
895 // we were not showing the menu. Show it once again. It will be
896 // removed when the page finishes.
897 showFakeTitleBar();
898 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400899 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700900
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400901 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400902 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400903 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
904 mFakeTitleBarHolder.getLayoutParams();
905 WebView mainView = mTabControl.getCurrentWebView();
906 // Although we decided whether or not to animate based on the current
907 // scroll position, the scroll position may have changed since the
908 // fake title bar was displayed. Make sure it has the appropriate
909 // animation/lack thereof before removing.
910 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400911 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400912 WindowManager manager
913 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -0400914 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400915 mFakeTitleBarHolder.removeView(mFakeTitleBar);
916 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400917 }
918
The Android Open Source Project0c908882009-03-03 19:32:16 -0800919 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400920 * Special method for the fake title bar to call when displaying its context
921 * menu, since it is in its own Window, and its parent does not show a
922 * context menu.
923 */
924 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400925 if (null == mTitleBar.getParent()) {
926 return;
927 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400928 openContextMenu(mTitleBar);
929 }
930
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400931 @Override
932 public void onContextMenuClosed(Menu menu) {
933 super.onContextMenuClosed(menu);
934 if (mInLoad) {
935 showFakeTitleBar();
936 }
937 }
938
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400939 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800940 * onSaveInstanceState(Bundle map)
941 * onSaveInstanceState is called right before onStop(). The map contains
942 * the saved state.
943 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700944 @Override
945 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700946 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800947 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
948 }
949 // the default implementation requires each view to have an id. As the
950 // browser handles the state itself and it doesn't use id for the views,
951 // don't call the default implementation. Otherwise it will trigger the
952 // warning like this, "couldn't save which view has focus because the
953 // focused view XXX has no id".
954
955 // Save all the tabs
956 mTabControl.saveState(outState);
957 }
958
Grace Kloba22ac16e2009-10-07 18:00:23 -0700959 @Override
960 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800961 super.onPause();
962
963 if (mActivityInPause) {
964 Log.e(LOGTAG, "BrowserActivity is already paused.");
965 return;
966 }
967
Mike Reed7bfa63b2009-05-28 11:08:32 -0400968 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800969 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400970 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800971 mWakeLock.acquire();
972 mHandler.sendMessageDelayed(mHandler
973 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
974 }
975
976 // Clear the credentials toast if it is up
977 if (mCredsDlg != null && mCredsDlg.isShowing()) {
978 mCredsDlg.dismiss();
979 }
980 mCredsDlg = null;
981
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400982 // FIXME: This removes the active tabs page and resets the menu to
983 // MAIN_MENU. A better solution might be to do this work in onNewIntent
984 // but then we would need to save it in onSaveInstanceState and restore
985 // it in onCreate/onRestoreInstanceState
986 if (mActiveTabsPage != null) {
987 removeActiveTabPage(true);
988 }
989
The Android Open Source Project0c908882009-03-03 19:32:16 -0800990 cancelStopToast();
991
992 // unregister network state listener
993 unregisterReceiver(mNetworkStateIntentReceiver);
994 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800995 }
996
Grace Kloba22ac16e2009-10-07 18:00:23 -0700997 @Override
998 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700999 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001000 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1001 }
1002 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001003
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001004 if (mUploadMessage != null) {
1005 mUploadMessage.onReceiveValue(null);
1006 mUploadMessage = null;
1007 }
1008
Grace Kloba0923d692009-09-23 21:37:25 -07001009 if (mTabControl == null) return;
1010
Grace Kloba1fc98a32009-10-21 13:23:08 -07001011 // Remove the fake title bar if it is there
1012 hideFakeTitleBar();
1013
The Android Open Source Project0c908882009-03-03 19:32:16 -08001014 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001015 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001016 if (t != null) {
1017 dismissSubWindow(t);
1018 removeTabFromContentView(t);
1019 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001020 // Destroy all the tabs
1021 mTabControl.destroy();
1022 WebIconDatabase.getInstance().close();
1023 if (mGlsConnection != null) {
1024 unbindService(mGlsConnection);
1025 mGlsConnection = null;
1026 }
1027
Grace Klobab4da0ad2009-05-14 14:45:40 -07001028 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001029 }
1030
1031 @Override
1032 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001033 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001034 super.onConfigurationChanged(newConfig);
1035
1036 if (mPageInfoDialog != null) {
1037 mPageInfoDialog.dismiss();
1038 showPageInfo(
1039 mPageInfoView,
1040 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1041 }
1042 if (mSSLCertificateDialog != null) {
1043 mSSLCertificateDialog.dismiss();
1044 showSSLCertificate(
1045 mSSLCertificateView);
1046 }
1047 if (mSSLCertificateOnErrorDialog != null) {
1048 mSSLCertificateOnErrorDialog.dismiss();
1049 showSSLCertificateOnError(
1050 mSSLCertificateOnErrorView,
1051 mSSLCertificateOnErrorHandler,
1052 mSSLCertificateOnErrorError);
1053 }
1054 if (mHttpAuthenticationDialog != null) {
1055 String title = ((TextView) mHttpAuthenticationDialog
1056 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1057 .toString();
1058 String name = ((TextView) mHttpAuthenticationDialog
1059 .findViewById(R.id.username_edit)).getText().toString();
1060 String password = ((TextView) mHttpAuthenticationDialog
1061 .findViewById(R.id.password_edit)).getText().toString();
1062 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1063 .getId();
1064 mHttpAuthenticationDialog.dismiss();
1065 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1066 name, password, focusId);
1067 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001068 }
1069
Grace Kloba22ac16e2009-10-07 18:00:23 -07001070 @Override
1071 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001072 super.onLowMemory();
1073 mTabControl.freeMemory();
1074 }
1075
Mike Reed7bfa63b2009-05-28 11:08:32 -04001076 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001077 Tab tab = mTabControl.getCurrentTab();
1078 boolean inLoad = tab.inLoad();
1079 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001080 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001081 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001082 if (w != null) {
1083 w.resumeTimers();
1084 }
1085 return true;
1086 } else {
1087 return false;
1088 }
1089 }
1090
Mike Reed7bfa63b2009-05-28 11:08:32 -04001091 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001092 Tab tab = mTabControl.getCurrentTab();
1093 boolean inLoad = tab.inLoad();
1094 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001095 CookieSyncManager.getInstance().stopSync();
1096 WebView w = mTabControl.getCurrentWebView();
1097 if (w != null) {
1098 w.pauseTimers();
1099 }
1100 return true;
1101 } else {
1102 return false;
1103 }
1104 }
1105
Leon Scroggins1f005d32009-08-10 17:36:42 -04001106 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001107 /*
1108 * This function is called when we are launching for the first time. We
1109 * are waiting for the login credentials before loading Google home
1110 * pages. This way the user will be logged in straight away.
1111 */
1112 private void waitForCredentials() {
1113 // Show a toast
1114 mCredsDlg = new ProgressDialog(this);
1115 mCredsDlg.setIndeterminate(true);
1116 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1117 // If the user cancels the operation, then cancel the Google
1118 // Credentials request.
1119 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1120 mCredsDlg.show();
1121
1122 // We set a timeout for the retrieval of credentials in onResume()
1123 // as that is when we have freed up some CPU time to get
1124 // the login credentials.
1125 }
1126
1127 /*
1128 * If we have received the credentials or we have timed out and we are
1129 * showing the credentials dialog, then it is time to move on.
1130 */
1131 private void resumeAfterCredentials() {
1132 if (mCredsDlg == null) {
1133 return;
1134 }
1135
1136 // Clear the toast
1137 if (mCredsDlg.isShowing()) {
1138 mCredsDlg.dismiss();
1139 }
1140 mCredsDlg = null;
1141
1142 // Clear any pending timeout
1143 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1144
1145 // Load the page
1146 WebView w = mTabControl.getCurrentWebView();
1147 if (w != null) {
1148 w.loadUrl(mSettings.getHomePage());
1149 }
1150
1151 // Update the settings, need to do this last as it can take a moment
1152 // to persist the settings. In the mean time we could be loading
1153 // content.
1154 mSettings.setLoginInitialized(this);
1155 }
1156
1157 // Open the icon database and retain all the icons for visited sites.
1158 private void retainIconsOnStartup() {
1159 final WebIconDatabase db = WebIconDatabase.getInstance();
1160 db.open(getDir("icons", 0).getPath());
1161 try {
1162 Cursor c = Browser.getAllBookmarks(mResolver);
1163 if (!c.moveToFirst()) {
1164 c.deactivate();
1165 return;
1166 }
1167 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1168 do {
1169 String url = c.getString(urlIndex);
1170 db.retainIconForPageUrl(url);
1171 } while (c.moveToNext());
1172 c.deactivate();
1173 } catch (IllegalStateException e) {
1174 Log.e(LOGTAG, "retainIconsOnStartup", e);
1175 }
1176 }
1177
1178 // Helper method for getting the top window.
1179 WebView getTopWindow() {
1180 return mTabControl.getCurrentTopWebView();
1181 }
1182
Grace Kloba22ac16e2009-10-07 18:00:23 -07001183 TabControl getTabControl() {
1184 return mTabControl;
1185 }
1186
The Android Open Source Project0c908882009-03-03 19:32:16 -08001187 @Override
1188 public boolean onCreateOptionsMenu(Menu menu) {
1189 super.onCreateOptionsMenu(menu);
1190
1191 MenuInflater inflater = getMenuInflater();
1192 inflater.inflate(R.menu.browser, menu);
1193 mMenu = menu;
1194 updateInLoadMenuItems();
1195 return true;
1196 }
1197
1198 /**
1199 * As the menu can be open when loading state changes
1200 * we must manually update the state of the stop/reload menu
1201 * item
1202 */
1203 private void updateInLoadMenuItems() {
1204 if (mMenu == null) {
1205 return;
1206 }
1207 MenuItem src = mInLoad ?
1208 mMenu.findItem(R.id.stop_menu_id):
1209 mMenu.findItem(R.id.reload_menu_id);
1210 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1211 dest.setIcon(src.getIcon());
1212 dest.setTitle(src.getTitle());
1213 }
1214
1215 @Override
1216 public boolean onContextItemSelected(MenuItem item) {
1217 // chording is not an issue with context menus, but we use the same
1218 // options selector, so set mCanChord to true so we can access them.
1219 mCanChord = true;
1220 int id = item.getItemId();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001221 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001222 // For the context menu from the title bar
1223 case R.id.title_bar_share_page_url:
1224 case R.id.title_bar_copy_page_url:
1225 WebView mainView = mTabControl.getCurrentWebView();
1226 if (null == mainView) {
1227 return false;
1228 }
1229 if (id == R.id.title_bar_share_page_url) {
1230 Browser.sendString(this, mainView.getUrl());
1231 } else {
1232 copy(mainView.getUrl());
1233 }
1234 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001235 // -- Browser context menu
1236 case R.id.open_context_menu_id:
1237 case R.id.open_newtab_context_menu_id:
1238 case R.id.bookmark_context_menu_id:
1239 case R.id.save_link_context_menu_id:
1240 case R.id.share_link_context_menu_id:
1241 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001242 final WebView webView = getTopWindow();
1243 if (null == webView) {
1244 return false;
1245 }
1246 final HashMap hrefMap = new HashMap();
1247 hrefMap.put("webview", webView);
1248 final Message msg = mHandler.obtainMessage(
1249 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001250 webView.requestFocusNodeHref(msg);
1251 break;
1252
1253 default:
1254 // For other context menus
1255 return onOptionsItemSelected(item);
1256 }
1257 mCanChord = false;
1258 return true;
1259 }
1260
1261 private Bundle createGoogleSearchSourceBundle(String source) {
1262 Bundle bundle = new Bundle();
1263 bundle.putString(SearchManager.SOURCE, source);
1264 return bundle;
1265 }
1266
1267 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001268 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001269 */
1270 @Override
1271 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001272 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001273 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001274 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001275 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001276 return true;
1277 }
1278
1279 @Override
1280 public void startSearch(String initialQuery, boolean selectInitialQuery,
1281 Bundle appSearchData, boolean globalSearch) {
1282 if (appSearchData == null) {
1283 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1284 }
1285 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1286 }
1287
Leon Scroggins1f005d32009-08-10 17:36:42 -04001288 /**
1289 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1290 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001291 * @param index Index of the tab to change to, as defined by
1292 * mTabControl.getTabIndex(Tab t).
1293 * @return boolean True if we successfully switched to a different tab. If
1294 * the indexth tab is null, or if that tab is the same as
1295 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001296 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001297 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001298 Tab tab = mTabControl.getTab(index);
1299 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001300 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001301 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001302 }
1303 if (currentTab != null) {
1304 // currentTab may be null if it was just removed. In that case,
1305 // we do not need to remove it
1306 removeTabFromContentView(currentTab);
1307 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001308 mTabControl.setCurrentTab(tab);
1309 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001310 resetTitleIconAndProgress();
1311 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001312 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001313 }
1314
Grace Kloba22ac16e2009-10-07 18:00:23 -07001315 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001316 return openTabAndShow(mSettings.getHomePage(), false, null);
1317 }
1318
Leon Scroggins1f005d32009-08-10 17:36:42 -04001319 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001320 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001321 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001322 // This is the last tab. Open a new one, with the home
1323 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001324 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001325 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001326 return;
1327 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001328 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001329 int indexToShow = -1;
1330 if (parent != null) {
1331 indexToShow = mTabControl.getTabIndex(parent);
1332 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001333 final int currentIndex = mTabControl.getCurrentIndex();
1334 // Try to move to the tab to the right
1335 indexToShow = currentIndex + 1;
1336 if (indexToShow > mTabControl.getTabCount() - 1) {
1337 // Try to move to the tab to the left
1338 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001339 }
1340 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001341 if (switchToTab(indexToShow)) {
1342 // Close window
1343 closeTab(current);
1344 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001345 }
1346
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001347 private ActiveTabsPage mActiveTabsPage;
1348
1349 /**
1350 * Remove the active tabs page.
1351 * @param needToAttach If true, the active tabs page did not attach a tab
1352 * to the content view, so we need to do that here.
1353 */
1354 /* package */ void removeActiveTabPage(boolean needToAttach) {
1355 mContentView.removeView(mActiveTabsPage);
1356 mActiveTabsPage = null;
1357 mMenuState = R.id.MAIN_MENU;
1358 if (needToAttach) {
1359 attachTabToContentView(mTabControl.getCurrentTab());
1360 }
1361 getTopWindow().requestFocus();
1362 }
1363
The Android Open Source Project0c908882009-03-03 19:32:16 -08001364 @Override
1365 public boolean onOptionsItemSelected(MenuItem item) {
1366 if (!mCanChord) {
1367 // The user has already fired a shortcut with this hold down of the
1368 // menu key.
1369 return false;
1370 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001371 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001372 return false;
1373 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001374 if (mMenuIsDown) {
1375 // The shortcut action consumes the MENU. Even if it is still down,
1376 // it won't trigger the next shortcut action. In the case of the
1377 // shortcut action triggering a new activity, like Bookmarks, we
1378 // won't get onKeyUp for MENU. So it is important to reset it here.
1379 mMenuIsDown = false;
1380 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001381 switch (item.getItemId()) {
1382 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001383 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001384 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001385 break;
1386
Leon Scroggins64b80f32009-08-07 12:03:34 -04001387 case R.id.goto_menu_id:
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001388 onSearchRequested();
1389 break;
1390
1391 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001392 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001393 break;
1394
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001395 case R.id.active_tabs_menu_id:
1396 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1397 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001398 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001399 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1400 mActiveTabsPage.requestFocus();
1401 mMenuState = EMPTY_MENU;
1402 break;
1403
Leon Scroggins1f005d32009-08-10 17:36:42 -04001404 case R.id.add_bookmark_menu_id:
1405 Intent i = new Intent(BrowserActivity.this,
1406 AddBookmarkPage.class);
1407 WebView w = getTopWindow();
1408 i.putExtra("url", w.getUrl());
1409 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001410 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001411 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001412 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001413 break;
1414
1415 case R.id.stop_reload_menu_id:
1416 if (mInLoad) {
1417 stopLoading();
1418 } else {
1419 getTopWindow().reload();
1420 }
1421 break;
1422
1423 case R.id.back_menu_id:
1424 getTopWindow().goBack();
1425 break;
1426
1427 case R.id.forward_menu_id:
1428 getTopWindow().goForward();
1429 break;
1430
1431 case R.id.close_menu_id:
1432 // Close the subwindow if it exists.
1433 if (mTabControl.getCurrentSubWindow() != null) {
1434 dismissSubWindow(mTabControl.getCurrentTab());
1435 break;
1436 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001437 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001438 break;
1439
1440 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001441 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001442 if (current != null) {
1443 dismissSubWindow(current);
1444 current.getWebView().loadUrl(mSettings.getHomePage());
1445 }
1446 break;
1447
1448 case R.id.preferences_menu_id:
1449 Intent intent = new Intent(this,
1450 BrowserPreferencesPage.class);
1451 startActivityForResult(intent, PREFERENCES_PAGE);
1452 break;
1453
1454 case R.id.find_menu_id:
1455 if (null == mFindDialog) {
1456 mFindDialog = new FindDialog(this);
1457 }
1458 mFindDialog.setWebView(getTopWindow());
1459 mFindDialog.show();
1460 mMenuState = EMPTY_MENU;
1461 break;
1462
1463 case R.id.select_text_id:
1464 getTopWindow().emulateShiftHeld();
1465 break;
1466 case R.id.page_info_menu_id:
1467 showPageInfo(mTabControl.getCurrentTab(), false);
1468 break;
1469
1470 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001471 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001472 break;
1473
1474 case R.id.share_page_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01001475 Browser.sendString(this, getTopWindow().getUrl(),
1476 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001477 break;
1478
1479 case R.id.dump_nav_menu_id:
1480 getTopWindow().debugDump();
1481 break;
1482
1483 case R.id.zoom_in_menu_id:
1484 getTopWindow().zoomIn();
1485 break;
1486
1487 case R.id.zoom_out_menu_id:
1488 getTopWindow().zoomOut();
1489 break;
1490
1491 case R.id.view_downloads_menu_id:
1492 viewDownloads(null);
1493 break;
1494
The Android Open Source Project0c908882009-03-03 19:32:16 -08001495 case R.id.window_one_menu_id:
1496 case R.id.window_two_menu_id:
1497 case R.id.window_three_menu_id:
1498 case R.id.window_four_menu_id:
1499 case R.id.window_five_menu_id:
1500 case R.id.window_six_menu_id:
1501 case R.id.window_seven_menu_id:
1502 case R.id.window_eight_menu_id:
1503 {
1504 int menuid = item.getItemId();
1505 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1506 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001507 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001508 if (desiredTab != null &&
1509 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001510 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001511 }
1512 break;
1513 }
1514 }
1515 }
1516 break;
1517
1518 default:
1519 if (!super.onOptionsItemSelected(item)) {
1520 return false;
1521 }
1522 // Otherwise fall through.
1523 }
1524 mCanChord = false;
1525 return true;
1526 }
1527
1528 public void closeFind() {
1529 mMenuState = R.id.MAIN_MENU;
1530 }
1531
Grace Kloba22ac16e2009-10-07 18:00:23 -07001532 @Override
1533 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001534 // This happens when the user begins to hold down the menu key, so
1535 // allow them to chord to get a shortcut.
1536 mCanChord = true;
1537 // Note: setVisible will decide whether an item is visible; while
1538 // setEnabled() will decide whether an item is enabled, which also means
1539 // whether the matching shortcut key will function.
1540 super.onPrepareOptionsMenu(menu);
1541 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001542 case EMPTY_MENU:
1543 if (mCurrentMenuState != mMenuState) {
1544 menu.setGroupVisible(R.id.MAIN_MENU, false);
1545 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1546 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001547 }
1548 break;
1549 default:
1550 if (mCurrentMenuState != mMenuState) {
1551 menu.setGroupVisible(R.id.MAIN_MENU, true);
1552 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1553 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001554 }
1555 final WebView w = getTopWindow();
1556 boolean canGoBack = false;
1557 boolean canGoForward = false;
1558 boolean isHome = false;
1559 if (w != null) {
1560 canGoBack = w.canGoBack();
1561 canGoForward = w.canGoForward();
1562 isHome = mSettings.getHomePage().equals(w.getUrl());
1563 }
1564 final MenuItem back = menu.findItem(R.id.back_menu_id);
1565 back.setEnabled(canGoBack);
1566
1567 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1568 home.setEnabled(!isHome);
1569
1570 menu.findItem(R.id.forward_menu_id)
1571 .setEnabled(canGoForward);
1572
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001573 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001574 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001575
The Android Open Source Project0c908882009-03-03 19:32:16 -08001576 // decide whether to show the share link option
1577 PackageManager pm = getPackageManager();
1578 Intent send = new Intent(Intent.ACTION_SEND);
1579 send.setType("text/plain");
1580 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1581 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1582
The Android Open Source Project0c908882009-03-03 19:32:16 -08001583 boolean isNavDump = mSettings.isNavDump();
1584 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1585 nav.setVisible(isNavDump);
1586 nav.setEnabled(isNavDump);
1587 break;
1588 }
1589 mCurrentMenuState = mMenuState;
1590 return true;
1591 }
1592
1593 @Override
1594 public void onCreateContextMenu(ContextMenu menu, View v,
1595 ContextMenuInfo menuInfo) {
1596 WebView webview = (WebView) v;
1597 WebView.HitTestResult result = webview.getHitTestResult();
1598 if (result == null) {
1599 return;
1600 }
1601
1602 int type = result.getType();
1603 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1604 Log.w(LOGTAG,
1605 "We should not show context menu when nothing is touched");
1606 return;
1607 }
1608 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1609 // let TextView handles context menu
1610 return;
1611 }
1612
1613 // Note, http://b/issue?id=1106666 is requesting that
1614 // an inflated menu can be used again. This is not available
1615 // yet, so inflate each time (yuk!)
1616 MenuInflater inflater = getMenuInflater();
1617 inflater.inflate(R.menu.browsercontext, menu);
1618
1619 // Show the correct menu group
1620 String extra = result.getExtra();
1621 menu.setGroupVisible(R.id.PHONE_MENU,
1622 type == WebView.HitTestResult.PHONE_TYPE);
1623 menu.setGroupVisible(R.id.EMAIL_MENU,
1624 type == WebView.HitTestResult.EMAIL_TYPE);
1625 menu.setGroupVisible(R.id.GEO_MENU,
1626 type == WebView.HitTestResult.GEO_TYPE);
1627 menu.setGroupVisible(R.id.IMAGE_MENU,
1628 type == WebView.HitTestResult.IMAGE_TYPE
1629 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1630 menu.setGroupVisible(R.id.ANCHOR_MENU,
1631 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1632 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1633
1634 // Setup custom handling depending on the type
1635 switch (type) {
1636 case WebView.HitTestResult.PHONE_TYPE:
1637 menu.setHeaderTitle(Uri.decode(extra));
1638 menu.findItem(R.id.dial_context_menu_id).setIntent(
1639 new Intent(Intent.ACTION_VIEW, Uri
1640 .parse(WebView.SCHEME_TEL + extra)));
1641 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1642 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001643 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001644 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1645 addIntent);
1646 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1647 new Copy(extra));
1648 break;
1649
1650 case WebView.HitTestResult.EMAIL_TYPE:
1651 menu.setHeaderTitle(extra);
1652 menu.findItem(R.id.email_context_menu_id).setIntent(
1653 new Intent(Intent.ACTION_VIEW, Uri
1654 .parse(WebView.SCHEME_MAILTO + extra)));
1655 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1656 new Copy(extra));
1657 break;
1658
1659 case WebView.HitTestResult.GEO_TYPE:
1660 menu.setHeaderTitle(extra);
1661 menu.findItem(R.id.map_context_menu_id).setIntent(
1662 new Intent(Intent.ACTION_VIEW, Uri
1663 .parse(WebView.SCHEME_GEO
1664 + URLEncoder.encode(extra))));
1665 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1666 new Copy(extra));
1667 break;
1668
1669 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1670 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1671 TextView titleView = (TextView) LayoutInflater.from(this)
1672 .inflate(android.R.layout.browser_link_context_header,
1673 null);
1674 titleView.setText(extra);
1675 menu.setHeaderView(titleView);
1676 // decide whether to show the open link in new tab option
1677 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001678 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001679 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1680 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001681 PackageManager pm = getPackageManager();
1682 Intent send = new Intent(Intent.ACTION_SEND);
1683 send.setType("text/plain");
1684 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1685 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1686 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1687 break;
1688 }
1689 // otherwise fall through to handle image part
1690 case WebView.HitTestResult.IMAGE_TYPE:
1691 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1692 menu.setHeaderTitle(extra);
1693 }
1694 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1695 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1696 menu.findItem(R.id.download_context_menu_id).
1697 setOnMenuItemClickListener(new Download(extra));
1698 break;
1699
1700 default:
1701 Log.w(LOGTAG, "We should not get here.");
1702 break;
1703 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001704 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001705 }
1706
The Android Open Source Project0c908882009-03-03 19:32:16 -08001707 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001708 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001709 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001710 // Attach the container that contains the main WebView and any other UI
1711 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001712 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001713
1714 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001715 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001716 if (errorConsole.numberOfErrors() == 0) {
1717 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1718 } else {
1719 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1720 }
1721
1722 mErrorConsoleContainer.addView(errorConsole,
1723 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1724 ViewGroup.LayoutParams.WRAP_CONTENT));
1725 }
1726
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001727 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001728 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001729 // Request focus on the top window.
1730 t.getTopWindow().requestFocus();
1731 }
1732
1733 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001734 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001735 t.attachSubWindow(mContentView);
1736 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001737 }
1738
1739 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001740 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001741 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001742 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001743
Grace Kloba22ac16e2009-10-07 18:00:23 -07001744 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1745 if (errorConsole != null) {
1746 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001747 }
1748
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001749 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001750 if (view != null) {
1751 view.setEmbeddedTitleBar(null);
1752 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001753 }
1754
1755 // Remove the sub window if it exists. Also called by TabControl when the
1756 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001757 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001758 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001759 // dismiss the subwindow. This will destroy the WebView.
1760 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001761 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001762 }
1763
Leon Scroggins1f005d32009-08-10 17:36:42 -04001764 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001765 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001766 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001767 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001768 }
1769
1770 // This method does a ton of stuff. It will attempt to create a new tab
1771 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001772 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001773 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1774 String appId) {
1775 final Tab currentTab = mTabControl.getCurrentTab();
1776 if (mTabControl.canCreateNewTab()) {
1777 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1778 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001779 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001780 // If the last tab was removed from the active tabs page, currentTab
1781 // will be null.
1782 if (currentTab != null) {
1783 removeTabFromContentView(currentTab);
1784 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001785 // We must set the new tab as the current tab to reflect the old
1786 // animation behavior.
1787 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001788 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001789 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001790 urlData.loadIn(webview);
1791 }
1792 return tab;
1793 } else {
1794 // Get rid of the subwindow if it exists
1795 dismissSubWindow(currentTab);
1796 if (!urlData.isEmpty()) {
1797 // Load the given url.
1798 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001799 }
1800 }
Grace Klobac9181842009-04-14 08:53:22 -07001801 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001802 }
1803
Grace Kloba22ac16e2009-10-07 18:00:23 -07001804 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001805 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001806 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001807 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001808 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001809 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001810 }
Grace Klobac9181842009-04-14 08:53:22 -07001811 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001812 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001813 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001814 }
1815 }
1816
1817 private class Copy implements OnMenuItemClickListener {
1818 private CharSequence mText;
1819
1820 public boolean onMenuItemClick(MenuItem item) {
1821 copy(mText);
1822 return true;
1823 }
1824
1825 public Copy(CharSequence toCopy) {
1826 mText = toCopy;
1827 }
1828 }
1829
1830 private class Download implements OnMenuItemClickListener {
1831 private String mText;
1832
1833 public boolean onMenuItemClick(MenuItem item) {
1834 onDownloadStartNoStream(mText, null, null, null, -1);
1835 return true;
1836 }
1837
1838 public Download(String toDownload) {
1839 mText = toDownload;
1840 }
1841 }
1842
1843 private void copy(CharSequence text) {
1844 try {
1845 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1846 if (clip != null) {
1847 clip.setClipboardText(text);
1848 }
1849 } catch (android.os.RemoteException e) {
1850 Log.e(LOGTAG, "Copy failed", e);
1851 }
1852 }
1853
1854 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001855 * Resets the browser title-view to whatever it must be
1856 * (for example, if we had a loading error)
1857 * When we have a new page, we call resetTitle, when we
1858 * have to reset the titlebar to whatever it used to be
1859 * (for example, if the user chose to stop loading), we
1860 * call resetTitleAndRevertLockIcon.
1861 */
1862 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001863 mTabControl.getCurrentTab().revertLockIcon();
1864 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001865 resetTitleIconAndProgress();
1866 }
1867
1868 /**
1869 * Reset the title, favicon, and progress.
1870 */
1871 private void resetTitleIconAndProgress() {
1872 WebView current = mTabControl.getCurrentWebView();
1873 if (current == null) {
1874 return;
1875 }
1876 resetTitleAndIcon(current);
1877 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001878 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001879 }
1880
1881 // Reset the title and the icon based on the given item.
1882 private void resetTitleAndIcon(WebView view) {
1883 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1884 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001885 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001886 setFavicon(item.getFavicon());
1887 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001888 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001889 setFavicon(null);
1890 }
1891 }
1892
1893 /**
1894 * Sets a title composed of the URL and the title string.
1895 * @param url The URL of the site being loaded.
1896 * @param title The title of the site being loaded.
1897 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001898 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001899 mUrl = url;
1900 mTitle = title;
1901
Leon Scroggins68579392009-09-15 15:31:54 -04001902 mTitleBar.setTitleAndUrl(title, url);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001903 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001904 }
1905
1906 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001907 * @param url The URL to build a title version of the URL from.
1908 * @return The title version of the URL or null if fails.
1909 * The title version of the URL can be either the URL hostname,
1910 * or the hostname with an "https://" prefix (for secure URLs),
1911 * or an empty string if, for example, the URL in question is a
1912 * file:// URL with no hostname.
1913 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001914 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001915 String titleUrl = null;
1916
1917 if (url != null) {
1918 try {
1919 // parse the url string
1920 URL urlObj = new URL(url);
1921 if (urlObj != null) {
1922 titleUrl = "";
1923
1924 String protocol = urlObj.getProtocol();
1925 String host = urlObj.getHost();
1926
1927 if (host != null && 0 < host.length()) {
1928 titleUrl = host;
1929 if (protocol != null) {
1930 // if a secure site, add an "https://" prefix!
1931 if (protocol.equalsIgnoreCase("https")) {
1932 titleUrl = protocol + "://" + host;
1933 }
1934 }
1935 }
1936 }
1937 } catch (MalformedURLException e) {}
1938 }
1939
1940 return titleUrl;
1941 }
1942
1943 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001944 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04001945 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001946 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001947 }
1948
1949 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001950 * Close the tab, remove its associated title bar, and adjust mTabControl's
1951 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001952 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001953 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001954 int currentIndex = mTabControl.getCurrentIndex();
1955 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001956 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001957 if (currentIndex >= removeIndex && currentIndex != 0) {
1958 currentIndex--;
1959 }
1960 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01001961 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001962 }
1963
1964 private void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001965 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001966 if (current == null) {
1967 /*
1968 * Instead of finishing the activity, simply push this to the back
1969 * of the stack and let ActivityManager to choose the foreground
1970 * activity. As BrowserActivity is singleTask, it will be always the
1971 * root of the task. So we can use either true or false for
1972 * moveTaskToBack().
1973 */
1974 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07001975 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001976 }
1977 WebView w = current.getWebView();
1978 if (w.canGoBack()) {
1979 w.goBack();
1980 } else {
1981 // Check to see if we are closing a window that was created by
1982 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001983 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001984 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001985 switchToTab(mTabControl.getTabIndex(parent));
1986 // Now we close the other tab
1987 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001988 } else {
1989 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001990 // force the tab's inLoad() to be false as we are going to
1991 // either finish the activity or remove the tab. This will
1992 // ensure pauseWebViewTimers() taking action.
1993 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001994 if (mTabControl.getTabCount() == 1) {
1995 finish();
1996 return;
1997 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04001998 // call pauseWebViewTimers() now, we won't be able to call
1999 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002000 // Temporarily change mActivityInPause to be true as
2001 // pauseWebViewTimers() will do nothing if mActivityInPause
2002 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002003 boolean savedState = mActivityInPause;
2004 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002005 Log.e(LOGTAG, "BrowserActivity is already paused "
2006 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002007 }
2008 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002009 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002010 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002011 removeTabFromContentView(current);
2012 mTabControl.removeTab(current);
2013 }
2014 /*
2015 * Instead of finishing the activity, simply push this to the back
2016 * of the stack and let ActivityManager to choose the foreground
2017 * activity. As BrowserActivity is singleTask, it will be always the
2018 * root of the task. So we can use either true or false for
2019 * moveTaskToBack().
2020 */
2021 moveTaskToBack(true);
2022 }
2023 }
2024 }
2025
Grace Kloba22ac16e2009-10-07 18:00:23 -07002026 boolean isMenuDown() {
2027 return mMenuIsDown;
2028 }
2029
Grace Kloba5942df02009-09-18 11:48:29 -07002030 @Override
2031 public boolean onKeyDown(int keyCode, KeyEvent event) {
2032 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2033 // still down, we don't want to trigger the search. Pretend to consume
2034 // the key and do nothing.
2035 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002036
Grace Kloba5942df02009-09-18 11:48:29 -07002037 switch(keyCode) {
2038 case KeyEvent.KEYCODE_MENU:
2039 mMenuIsDown = true;
2040 break;
2041 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002042 // WebView/WebTextView handle the keys in the KeyDown. As
2043 // the Activity's shortcut keys are only handled when WebView
2044 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2045 if (event.isShiftPressed()) {
2046 getTopWindow().pageUp(false);
2047 } else {
2048 getTopWindow().pageDown(false);
2049 }
Grace Kloba5942df02009-09-18 11:48:29 -07002050 return true;
2051 case KeyEvent.KEYCODE_BACK:
2052 if (event.getRepeatCount() == 0) {
2053 event.startTracking();
2054 return true;
2055 } else if (mCustomView == null && mActiveTabsPage == null
2056 && event.isLongPress()) {
2057 bookmarksOrHistoryPicker(true);
2058 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002059 }
Grace Kloba5942df02009-09-18 11:48:29 -07002060 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002061 }
Grace Kloba5942df02009-09-18 11:48:29 -07002062 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002063 }
2064
Grace Kloba5942df02009-09-18 11:48:29 -07002065 @Override
2066 public boolean onKeyUp(int keyCode, KeyEvent event) {
2067 switch(keyCode) {
2068 case KeyEvent.KEYCODE_MENU:
2069 mMenuIsDown = false;
2070 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002071 case KeyEvent.KEYCODE_BACK:
2072 if (event.isTracking() && !event.isCanceled()) {
2073 if (mCustomView != null) {
2074 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002075 mTabControl.getCurrentWebView().getWebChromeClient()
2076 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002077 } else if (mActiveTabsPage != null) {
2078 // if tab page is showing, hide it
2079 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002080 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002081 WebView subwindow = mTabControl.getCurrentSubWindow();
2082 if (subwindow != null) {
2083 if (subwindow.canGoBack()) {
2084 subwindow.goBack();
2085 } else {
2086 dismissSubWindow(mTabControl.getCurrentTab());
2087 }
2088 } else {
2089 goBackOnePageOrQuit();
2090 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002091 }
Grace Kloba5942df02009-09-18 11:48:29 -07002092 return true;
2093 }
2094 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002095 }
Grace Kloba5942df02009-09-18 11:48:29 -07002096 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002097 }
2098
Leon Scroggins68579392009-09-15 15:31:54 -04002099 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002100 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002101 resetTitleAndRevertLockIcon();
2102 WebView w = getTopWindow();
2103 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002104 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2105 // same logic here. But for subwindow case, should we call into the main
2106 // WebView's onPageFinished as we never call its onPageStarted and if
2107 // the page finishes itself, we don't call onPageFinished.
2108 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2109 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002110
2111 cancelStopToast();
2112 mStopToast = Toast
2113 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2114 mStopToast.show();
2115 }
2116
Grace Kloba22ac16e2009-10-07 18:00:23 -07002117 boolean didUserStopLoading() {
2118 return mDidStopLoad;
2119 }
2120
The Android Open Source Project0c908882009-03-03 19:32:16 -08002121 private void cancelStopToast() {
2122 if (mStopToast != null) {
2123 mStopToast.cancel();
2124 mStopToast = null;
2125 }
2126 }
2127
Grace Kloba22ac16e2009-10-07 18:00:23 -07002128 // called by a UI or non-UI thread to post the message
2129 public void postMessage(int what, int arg1, int arg2, Object obj,
2130 long delayMillis) {
2131 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2132 obj), delayMillis);
2133 }
2134
2135 // called by a UI or non-UI thread to remove the message
2136 void removeMessages(int what, Object object) {
2137 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002138 }
2139
2140 // public message ids
2141 public final static int LOAD_URL = 1001;
2142 public final static int STOP_LOAD = 1002;
2143
2144 // Message Ids
2145 private static final int FOCUS_NODE_HREF = 102;
2146 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002147 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002148
Grace Kloba22ac16e2009-10-07 18:00:23 -07002149 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002150
The Android Open Source Project0c908882009-03-03 19:32:16 -08002151 // Private handler for handling javascript and saving passwords
2152 private Handler mHandler = new Handler() {
2153
2154 public void handleMessage(Message msg) {
2155 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002156 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002157 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002158 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002159 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002160 if (url == null || url.length() == 0) {
2161 break;
2162 }
2163 HashMap focusNodeMap = (HashMap) msg.obj;
2164 WebView view = (WebView) focusNodeMap.get("webview");
2165 // Only apply the action if the top window did not change.
2166 if (getTopWindow() != view) {
2167 break;
2168 }
2169 switch (msg.arg1) {
2170 case R.id.open_context_menu_id:
2171 case R.id.view_image_context_menu_id:
2172 loadURL(getTopWindow(), url);
2173 break;
2174 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002175 final Tab parent = mTabControl.getCurrentTab();
2176 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002177 if (newTab != parent) {
2178 parent.addChildTab(newTab);
2179 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002180 break;
2181 case R.id.bookmark_context_menu_id:
2182 Intent intent = new Intent(BrowserActivity.this,
2183 AddBookmarkPage.class);
2184 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002185 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002186 startActivity(intent);
2187 break;
2188 case R.id.share_link_context_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01002189 Browser.sendString(BrowserActivity.this, url,
2190 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002191 break;
2192 case R.id.copy_link_context_menu_id:
2193 copy(url);
2194 break;
2195 case R.id.save_link_context_menu_id:
2196 case R.id.download_context_menu_id:
2197 onDownloadStartNoStream(url, null, null, null, -1);
2198 break;
2199 }
2200 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002201 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002202
2203 case LOAD_URL:
2204 loadURL(getTopWindow(), (String) msg.obj);
2205 break;
2206
2207 case STOP_LOAD:
2208 stopLoading();
2209 break;
2210
2211 case CANCEL_CREDS_REQUEST:
2212 resumeAfterCredentials();
2213 break;
2214
The Android Open Source Project0c908882009-03-03 19:32:16 -08002215 case RELEASE_WAKELOCK:
2216 if (mWakeLock.isHeld()) {
2217 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002218 // if we reach here, Browser should be still in the
2219 // background loading after WAKELOCK_TIMEOUT (5-min).
2220 // To avoid burning the battery, stop loading.
2221 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002222 }
2223 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002224
2225 case UPDATE_BOOKMARK_THUMBNAIL:
2226 WebView view = (WebView) msg.obj;
2227 if (view != null) {
2228 updateScreenshot(view);
2229 }
2230 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002231 }
2232 }
2233 };
2234
Leon Scroggins89c6d362009-07-15 16:54:37 -04002235 private void updateScreenshot(WebView view) {
2236 // If this is a bookmarked site, add a screenshot to the database.
2237 // FIXME: When should we update? Every time?
2238 // FIXME: Would like to make sure there is actually something to
2239 // draw, but the API for that (WebViewCore.pictureReady()) is not
2240 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002241
Patrick Scott3918d442009-08-04 13:22:29 -04002242 ContentResolver cr = getContentResolver();
2243 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002244 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002245 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002246 boolean succeed = c.moveToFirst();
2247 ContentValues values = null;
2248 while (succeed) {
2249 if (values == null) {
2250 final ByteArrayOutputStream os
2251 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002252 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002253 if (bm == null) {
2254 c.close();
2255 return;
2256 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002257 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2258 values = new ContentValues();
2259 values.put(Browser.BookmarkColumns.THUMBNAIL,
2260 os.toByteArray());
2261 }
2262 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2263 c.getInt(0)), values, null, null);
2264 succeed = c.moveToNext();
2265 }
2266 c.close();
2267 }
2268 }
2269
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002270 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002271 * Values for the size of the thumbnail created when taking a screenshot.
2272 * Lazily initialized. Instead of using these directly, use
2273 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002274 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002275 private static int THUMBNAIL_WIDTH = 0;
2276 private static int THUMBNAIL_HEIGHT = 0;
2277
2278 /**
2279 * Return the desired width for thumbnail screenshots, which are stored in
2280 * the database, and used on the bookmarks screen.
2281 * @param context Context for finding out the density of the screen.
2282 * @return int desired width for thumbnail screenshot.
2283 */
2284 /* package */ static int getDesiredThumbnailWidth(Context context) {
2285 if (THUMBNAIL_WIDTH == 0) {
2286 float density = context.getResources().getDisplayMetrics().density;
2287 THUMBNAIL_WIDTH = (int) (90 * density);
2288 THUMBNAIL_HEIGHT = (int) (80 * density);
2289 }
2290 return THUMBNAIL_WIDTH;
2291 }
2292
2293 /**
2294 * Return the desired height for thumbnail screenshots, which are stored in
2295 * the database, and used on the bookmarks screen.
2296 * @param context Context for finding out the density of the screen.
2297 * @return int desired height for thumbnail screenshot.
2298 */
2299 /* package */ static int getDesiredThumbnailHeight(Context context) {
2300 // To ensure that they are both initialized.
2301 getDesiredThumbnailWidth(context);
2302 return THUMBNAIL_HEIGHT;
2303 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002304
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002305 private Bitmap createScreenshot(WebView view) {
2306 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002307 if (thumbnail == null) {
2308 return null;
2309 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002310 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2311 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002312 Canvas canvas = new Canvas(bm);
2313 // May need to tweak these values to determine what is the
2314 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002315 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002316 int thumbnailHeight = thumbnail.getHeight();
2317 float scaleFactorX = 1.0f;
2318 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002319 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002320 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002321 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002322 } else {
2323 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002324 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002325
2326 if (view.getWidth() > view.getHeight() &&
2327 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2328 // If the device is in landscape and the page is shorter
2329 // than the height of the view, stretch the thumbnail to fill the
2330 // space.
2331 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2332 (float)thumbnailHeight;
2333 } else {
2334 // In the portrait case, this looks nice.
2335 scaleFactorY = scaleFactorX;
2336 }
2337
2338 canvas.scale(scaleFactorX, scaleFactorY);
2339
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002340 thumbnail.draw(canvas);
2341 return bm;
2342 }
2343
The Android Open Source Project0c908882009-03-03 19:32:16 -08002344 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002345 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002346 //-------------------------------------------------------------------------
2347
2348 // Use in overrideUrlLoading
2349 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2350 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2351 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2352 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2353
Grace Kloba22ac16e2009-10-07 18:00:23 -07002354 void onPageStarted(WebView view, String url, Bitmap favicon) {
2355 // when BrowserActivity just starts, onPageStarted may be called before
2356 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2357 // to start the timer. As we won't switch tabs while an activity is in
2358 // pause state, we can ensure calling resume and pause in pair.
2359 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002360
Grace Kloba22ac16e2009-10-07 18:00:23 -07002361 resetLockIcon(url);
2362 setUrlTitle(url, null);
2363 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002364 // Keep this initial progress in sync with initialProgressValue (* 100)
2365 // in ProgressTracker.cpp
2366 // Show some progress so that the user knows the page is beginning to
2367 // load
2368 onProgressChanged(view, 10);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002369 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002370 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002371
Grace Kloba22ac16e2009-10-07 18:00:23 -07002372 if (mSettings.isTracing()) {
2373 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002374 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002375 WebAddress uri = new WebAddress(url);
2376 host = uri.mHost;
2377 } catch (android.net.ParseException ex) {
2378 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002379 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002380 host = host.replace('.', '_');
2381 host += ".trace";
2382 mInTrace = true;
2383 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2384 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002385
Grace Kloba22ac16e2009-10-07 18:00:23 -07002386 // Performance probe
2387 if (false) {
2388 mStart = SystemClock.uptimeMillis();
2389 mProcessStart = Process.getElapsedCpuTime();
2390 long[] sysCpu = new long[7];
2391 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2392 sysCpu, null)) {
2393 mUserStart = sysCpu[0] + sysCpu[1];
2394 mSystemStart = sysCpu[2];
2395 mIdleStart = sysCpu[3];
2396 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2397 }
2398 mUiStart = SystemClock.currentThreadTimeMillis();
2399 }
2400 }
2401
2402 void onPageFinished(WebView view, String url) {
2403 // Reset the title and icon in case we stopped a provisional load.
2404 resetTitleAndIcon(view);
2405 // Update the lock icon image only once we are done loading
2406 updateLockIconToLatest();
2407 // pause the WebView timer and release the wake lock if it is finished
2408 // while BrowserActivity is in pause state.
2409 if (mActivityInPause && pauseWebViewTimers()) {
2410 if (mWakeLock.isHeld()) {
2411 mHandler.removeMessages(RELEASE_WAKELOCK);
2412 mWakeLock.release();
2413 }
2414 }
2415
2416 // Performance probe
2417 if (false) {
2418 long[] sysCpu = new long[7];
2419 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2420 sysCpu, null)) {
2421 String uiInfo = "UI thread used "
2422 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2423 + " ms";
2424 if (LOGD_ENABLED) {
2425 Log.d(LOGTAG, uiInfo);
2426 }
2427 //The string that gets written to the log
2428 String performanceString = "It took total "
2429 + (SystemClock.uptimeMillis() - mStart)
2430 + " ms clock time to load the page."
2431 + "\nbrowser process used "
2432 + (Process.getElapsedCpuTime() - mProcessStart)
2433 + " ms, user processes used "
2434 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2435 + " ms, kernel used "
2436 + (sysCpu[2] - mSystemStart) * 10
2437 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2438 + " ms and irq took "
2439 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2440 * 10 + " ms, " + uiInfo;
2441 if (LOGD_ENABLED) {
2442 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2443 }
2444 if (url != null) {
2445 // strip the url to maintain consistency
2446 String newUrl = new String(url);
2447 if (newUrl.startsWith("http://www.")) {
2448 newUrl = newUrl.substring(11);
2449 } else if (newUrl.startsWith("http://")) {
2450 newUrl = newUrl.substring(7);
2451 } else if (newUrl.startsWith("https://www.")) {
2452 newUrl = newUrl.substring(12);
2453 } else if (newUrl.startsWith("https://")) {
2454 newUrl = newUrl.substring(8);
2455 }
2456 if (LOGD_ENABLED) {
2457 Log.d(LOGTAG, newUrl + " loaded");
2458 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002459 }
2460 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002461 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002462
Grace Kloba22ac16e2009-10-07 18:00:23 -07002463 if (mInTrace) {
2464 mInTrace = false;
2465 Debug.stopMethodTracing();
2466 }
2467 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002468
Grace Kloba22ac16e2009-10-07 18:00:23 -07002469 boolean shouldOverrideUrlLoading(WebView view, String url) {
2470 if (url.startsWith(SCHEME_WTAI)) {
2471 // wtai://wp/mc;number
2472 // number=string(phone-number)
2473 if (url.startsWith(SCHEME_WTAI_MC)) {
2474 Intent intent = new Intent(Intent.ACTION_VIEW,
2475 Uri.parse(WebView.SCHEME_TEL +
2476 url.substring(SCHEME_WTAI_MC.length())));
2477 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002478 return true;
2479 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002480 // wtai://wp/sd;dtmf
2481 // dtmf=string(dialstring)
2482 if (url.startsWith(SCHEME_WTAI_SD)) {
2483 // TODO: only send when there is active voice connection
2484 return false;
2485 }
2486 // wtai://wp/ap;number;name
2487 // number=string(phone-number)
2488 // name=string
2489 if (url.startsWith(SCHEME_WTAI_AP)) {
2490 // TODO
2491 return false;
2492 }
2493 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002494
Grace Kloba22ac16e2009-10-07 18:00:23 -07002495 // The "about:" schemes are internal to the browser; don't want these to
2496 // be dispatched to other apps.
2497 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002498 return false;
2499 }
2500
Grace Kloba22ac16e2009-10-07 18:00:23 -07002501 Intent intent;
2502 // perform generic parsing of the URI to turn it into an Intent.
2503 try {
2504 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2505 } catch (URISyntaxException ex) {
2506 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2507 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002508 }
2509
Grace Kloba22ac16e2009-10-07 18:00:23 -07002510 // check whether the intent can be resolved. If not, we will see
2511 // whether we can download it from the Market.
2512 if (getPackageManager().resolveActivity(intent, 0) == null) {
2513 String packagename = intent.getPackage();
2514 if (packagename != null) {
2515 intent = new Intent(Intent.ACTION_VIEW, Uri
2516 .parse("market://search?q=pname:" + packagename));
2517 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2518 startActivity(intent);
2519 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002520 } else {
2521 return false;
2522 }
2523 }
2524
Grace Kloba22ac16e2009-10-07 18:00:23 -07002525 // sanitize the Intent, ensuring web pages can not bypass browser
2526 // security (only access to BROWSABLE activities).
2527 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2528 intent.setComponent(null);
2529 try {
2530 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002531 return true;
2532 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002533 } catch (ActivityNotFoundException ex) {
2534 // ignore the error. If no application can handle the URL,
2535 // eg about:blank, assume the browser can handle it.
2536 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002537
Grace Kloba22ac16e2009-10-07 18:00:23 -07002538 if (mMenuIsDown) {
2539 openTab(url);
2540 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002541 return true;
2542 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002543 return false;
2544 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002545
Grace Kloba22ac16e2009-10-07 18:00:23 -07002546 // -------------------------------------------------------------------------
2547 // Helper function for WebChromeClient
2548 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002549
Grace Kloba22ac16e2009-10-07 18:00:23 -07002550 void onProgressChanged(WebView view, int newProgress) {
2551 mTitleBar.setProgress(newProgress);
2552 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002553
Grace Kloba22ac16e2009-10-07 18:00:23 -07002554 if (newProgress == 100) {
2555 // onProgressChanged() may continue to be called after the main
2556 // frame has finished loading, as any remaining sub frames continue
2557 // to load. We'll only get called once though with newProgress as
2558 // 100 when everything is loaded. (onPageFinished is called once
2559 // when the main frame completes loading regardless of the state of
2560 // any sub frames so calls to onProgressChanges may continue after
2561 // onPageFinished has executed)
2562 if (mInLoad) {
2563 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002564 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002565 // If the options menu is open, leave the title bar
2566 if (!mOptionsMenuOpen || !mIconView) {
2567 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002568 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002569 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002570 } else if (!mInLoad) {
2571 // onPageFinished may have already been called but a subframe is
2572 // still loading and updating the progress. Reset mInLoad and update
2573 // the menu items.
2574 mInLoad = true;
2575 updateInLoadMenuItems();
2576 if (!mOptionsMenuOpen || mIconView) {
2577 // This page has begun to load, so show the title bar
2578 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002579 }
2580 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002581 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002582
Grace Kloba22ac16e2009-10-07 18:00:23 -07002583 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2584 if (mCustomView != null)
2585 return;
2586
2587 // Add the custom view to its container.
2588 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2589 mCustomView = view;
2590 mCustomViewCallback = callback;
2591 // Save the menu state and set it to empty while the custom
2592 // view is showing.
2593 mOldMenuState = mMenuState;
2594 mMenuState = EMPTY_MENU;
2595 // Hide the content view.
2596 mContentView.setVisibility(View.GONE);
2597 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002598 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002599 mCustomViewContainer.setVisibility(View.VISIBLE);
2600 mCustomViewContainer.bringToFront();
2601 }
2602
2603 void onHideCustomView() {
2604 if (mCustomView == null)
2605 return;
2606
2607 // Hide the custom view.
2608 mCustomView.setVisibility(View.GONE);
2609 // Remove the custom view from its container.
2610 mCustomViewContainer.removeView(mCustomView);
2611 mCustomView = null;
2612 // Reset the old menu state.
2613 mMenuState = mOldMenuState;
2614 mOldMenuState = EMPTY_MENU;
2615 mCustomViewContainer.setVisibility(View.GONE);
2616 mCustomViewCallback.onCustomViewHidden();
2617 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002618 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002619 mContentView.setVisibility(View.VISIBLE);
2620 }
2621
2622 Bitmap getDefaultVideoPoster() {
2623 if (mDefaultVideoPoster == null) {
2624 mDefaultVideoPoster = BitmapFactory.decodeResource(
2625 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002626 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002627 return mDefaultVideoPoster;
2628 }
Patrick Scott3918d442009-08-04 13:22:29 -04002629
Grace Kloba22ac16e2009-10-07 18:00:23 -07002630 View getVideoLoadingProgressView() {
2631 if (mVideoProgressView == null) {
2632 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2633 mVideoProgressView = inflater.inflate(
2634 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002635 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002636 return mVideoProgressView;
2637 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002638
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002639 /*
2640 * The Object used to inform the WebView of the file to upload.
2641 */
2642 private ValueCallback<Uri> mUploadMessage;
2643
Grace Kloba22ac16e2009-10-07 18:00:23 -07002644 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2645 if (mUploadMessage != null) return;
2646 mUploadMessage = uploadMsg;
2647 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2648 i.addCategory(Intent.CATEGORY_OPENABLE);
2649 i.setType("*/*");
2650 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2651 getString(R.string.choose_upload)), FILE_SELECTED);
2652 }
2653
2654 // -------------------------------------------------------------------------
2655 // Implement functions for DownloadListener
2656 // -------------------------------------------------------------------------
2657
The Android Open Source Project0c908882009-03-03 19:32:16 -08002658 /**
2659 * Notify the host application a download should be done, or that
2660 * the data should be streamed if a streaming viewer is available.
2661 * @param url The full url to the content that should be downloaded
2662 * @param contentDisposition Content-disposition http header, if
2663 * present.
2664 * @param mimetype The mimetype of the content reported by the server
2665 * @param contentLength The file size reported by the server
2666 */
2667 public void onDownloadStart(String url, String userAgent,
2668 String contentDisposition, String mimetype, long contentLength) {
2669 // if we're dealing wih A/V content that's not explicitly marked
2670 // for download, check if it's streamable.
2671 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002672 || !contentDisposition.regionMatches(
2673 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002674 // query the package manager to see if there's a registered handler
2675 // that matches.
2676 Intent intent = new Intent(Intent.ACTION_VIEW);
2677 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002678 ResolveInfo info = getPackageManager().resolveActivity(intent,
2679 PackageManager.MATCH_DEFAULT_ONLY);
2680 if (info != null) {
2681 ComponentName myName = getComponentName();
2682 // If we resolved to ourselves, we don't want to attempt to
2683 // load the url only to try and download it again.
2684 if (!myName.getPackageName().equals(
2685 info.activityInfo.packageName)
2686 || !myName.getClassName().equals(
2687 info.activityInfo.name)) {
2688 // someone (other than us) knows how to handle this mime
2689 // type with this scheme, don't download.
2690 try {
2691 startActivity(intent);
2692 return;
2693 } catch (ActivityNotFoundException ex) {
2694 if (LOGD_ENABLED) {
2695 Log.d(LOGTAG, "activity not found for " + mimetype
2696 + " over " + Uri.parse(url).getScheme(),
2697 ex);
2698 }
2699 // Best behavior is to fall back to a download in this
2700 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002701 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002702 }
2703 }
2704 }
2705 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2706 }
2707
2708 /**
2709 * Notify the host application a download should be done, even if there
2710 * is a streaming viewer available for thise type.
2711 * @param url The full url to the content that should be downloaded
2712 * @param contentDisposition Content-disposition http header, if
2713 * present.
2714 * @param mimetype The mimetype of the content reported by the server
2715 * @param contentLength The file size reported by the server
2716 */
2717 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2718 String contentDisposition, String mimetype, long contentLength) {
2719
2720 String filename = URLUtil.guessFileName(url,
2721 contentDisposition, mimetype);
2722
2723 // Check to see if we have an SDCard
2724 String status = Environment.getExternalStorageState();
2725 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2726 int title;
2727 String msg;
2728
2729 // Check to see if the SDCard is busy, same as the music app
2730 if (status.equals(Environment.MEDIA_SHARED)) {
2731 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2732 title = R.string.download_sdcard_busy_dlg_title;
2733 } else {
2734 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2735 title = R.string.download_no_sdcard_dlg_title;
2736 }
2737
2738 new AlertDialog.Builder(this)
2739 .setTitle(title)
2740 .setIcon(android.R.drawable.ic_dialog_alert)
2741 .setMessage(msg)
2742 .setPositiveButton(R.string.ok, null)
2743 .show();
2744 return;
2745 }
2746
2747 // java.net.URI is a lot stricter than KURL so we have to undo
2748 // KURL's percent-encoding and redo the encoding using java.net.URI.
2749 URI uri = null;
2750 try {
2751 // Undo the percent-encoding that KURL may have done.
2752 String newUrl = new String(URLUtil.decode(url.getBytes()));
2753 // Parse the url into pieces
2754 WebAddress w = new WebAddress(newUrl);
2755 String frag = null;
2756 String query = null;
2757 String path = w.mPath;
2758 // Break the path into path, query, and fragment
2759 if (path.length() > 0) {
2760 // Strip the fragment
2761 int idx = path.lastIndexOf('#');
2762 if (idx != -1) {
2763 frag = path.substring(idx + 1);
2764 path = path.substring(0, idx);
2765 }
2766 idx = path.lastIndexOf('?');
2767 if (idx != -1) {
2768 query = path.substring(idx + 1);
2769 path = path.substring(0, idx);
2770 }
2771 }
2772 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2773 query, frag);
2774 } catch (Exception e) {
2775 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2776 return;
2777 }
2778
2779 // XXX: Have to use the old url since the cookies were stored using the
2780 // old percent-encoded url.
2781 String cookies = CookieManager.getInstance().getCookie(url);
2782
2783 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002784 values.put(Downloads.COLUMN_URI, uri.toString());
2785 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
2786 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
2787 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002788 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002789 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002790 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002791 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2792 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
2793 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
2794 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002795 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002796 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002797 }
2798 if (mimetype == null) {
2799 // We must have long pressed on a link or image to download it. We
2800 // are not sure of the mimetype in this case, so do a head request
2801 new FetchUrlMimeType(this).execute(values);
2802 } else {
2803 final Uri contentUri =
2804 getContentResolver().insert(Downloads.CONTENT_URI, values);
2805 viewDownloads(contentUri);
2806 }
2807
2808 }
2809
Grace Kloba22ac16e2009-10-07 18:00:23 -07002810 // -------------------------------------------------------------------------
2811
The Android Open Source Project0c908882009-03-03 19:32:16 -08002812 /**
2813 * Resets the lock icon. This method is called when we start a new load and
2814 * know the url to be loaded.
2815 */
2816 private void resetLockIcon(String url) {
2817 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002818 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002819 updateLockIconImage(LOCK_ICON_UNSECURE);
2820 }
2821
The Android Open Source Project0c908882009-03-03 19:32:16 -08002822 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002823 * Update the lock icon to correspond to our latest state.
2824 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002825 private void updateLockIconToLatest() {
2826 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002827 }
2828
2829 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002830 * Updates the lock-icon image in the title-bar.
2831 */
2832 private void updateLockIconImage(int lockIconType) {
2833 Drawable d = null;
2834 if (lockIconType == LOCK_ICON_SECURE) {
2835 d = mSecLockIcon;
2836 } else if (lockIconType == LOCK_ICON_MIXED) {
2837 d = mMixLockIcon;
2838 }
Leon Scroggins68579392009-09-15 15:31:54 -04002839 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002840 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002841 }
2842
2843 /**
2844 * Displays a page-info dialog.
2845 * @param tab The tab to show info about
2846 * @param fromShowSSLCertificateOnError The flag that indicates whether
2847 * this dialog was opened from the SSL-certificate-on-error dialog or
2848 * not. This is important, since we need to know whether to return to
2849 * the parent dialog or simply dismiss.
2850 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002851 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002852 final boolean fromShowSSLCertificateOnError) {
2853 final LayoutInflater factory = LayoutInflater
2854 .from(this);
2855
2856 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2857
2858 final WebView view = tab.getWebView();
2859
2860 String url = null;
2861 String title = null;
2862
2863 if (view == null) {
2864 url = tab.getUrl();
2865 title = tab.getTitle();
2866 } else if (view == mTabControl.getCurrentWebView()) {
2867 // Use the cached title and url if this is the current WebView
2868 url = mUrl;
2869 title = mTitle;
2870 } else {
2871 url = view.getUrl();
2872 title = view.getTitle();
2873 }
2874
2875 if (url == null) {
2876 url = "";
2877 }
2878 if (title == null) {
2879 title = "";
2880 }
2881
2882 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
2883 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
2884
2885 mPageInfoView = tab;
2886 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
2887
2888 AlertDialog.Builder alertDialogBuilder =
2889 new AlertDialog.Builder(this)
2890 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
2891 .setView(pageInfoView)
2892 .setPositiveButton(
2893 R.string.ok,
2894 new DialogInterface.OnClickListener() {
2895 public void onClick(DialogInterface dialog,
2896 int whichButton) {
2897 mPageInfoDialog = null;
2898 mPageInfoView = null;
2899 mPageInfoFromShowSSLCertificateOnError = null;
2900
2901 // if we came here from the SSL error dialog
2902 if (fromShowSSLCertificateOnError) {
2903 // go back to the SSL error dialog
2904 showSSLCertificateOnError(
2905 mSSLCertificateOnErrorView,
2906 mSSLCertificateOnErrorHandler,
2907 mSSLCertificateOnErrorError);
2908 }
2909 }
2910 })
2911 .setOnCancelListener(
2912 new DialogInterface.OnCancelListener() {
2913 public void onCancel(DialogInterface dialog) {
2914 mPageInfoDialog = null;
2915 mPageInfoView = null;
2916 mPageInfoFromShowSSLCertificateOnError = null;
2917
2918 // if we came here from the SSL error dialog
2919 if (fromShowSSLCertificateOnError) {
2920 // go back to the SSL error dialog
2921 showSSLCertificateOnError(
2922 mSSLCertificateOnErrorView,
2923 mSSLCertificateOnErrorHandler,
2924 mSSLCertificateOnErrorError);
2925 }
2926 }
2927 });
2928
2929 // if we have a main top-level page SSL certificate set or a certificate
2930 // error
2931 if (fromShowSSLCertificateOnError ||
2932 (view != null && view.getCertificate() != null)) {
2933 // add a 'View Certificate' button
2934 alertDialogBuilder.setNeutralButton(
2935 R.string.view_certificate,
2936 new DialogInterface.OnClickListener() {
2937 public void onClick(DialogInterface dialog,
2938 int whichButton) {
2939 mPageInfoDialog = null;
2940 mPageInfoView = null;
2941 mPageInfoFromShowSSLCertificateOnError = null;
2942
2943 // if we came here from the SSL error dialog
2944 if (fromShowSSLCertificateOnError) {
2945 // go back to the SSL error dialog
2946 showSSLCertificateOnError(
2947 mSSLCertificateOnErrorView,
2948 mSSLCertificateOnErrorHandler,
2949 mSSLCertificateOnErrorError);
2950 } else {
2951 // otherwise, display the top-most certificate from
2952 // the chain
2953 if (view.getCertificate() != null) {
2954 showSSLCertificate(tab);
2955 }
2956 }
2957 }
2958 });
2959 }
2960
2961 mPageInfoDialog = alertDialogBuilder.show();
2962 }
2963
2964 /**
2965 * Displays the main top-level page SSL certificate dialog
2966 * (accessible from the Page-Info dialog).
2967 * @param tab The tab to show certificate for.
2968 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002969 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002970 final View certificateView =
2971 inflateCertificateView(tab.getWebView().getCertificate());
2972 if (certificateView == null) {
2973 return;
2974 }
2975
2976 LayoutInflater factory = LayoutInflater.from(this);
2977
2978 final LinearLayout placeholder =
2979 (LinearLayout)certificateView.findViewById(R.id.placeholder);
2980
2981 LinearLayout ll = (LinearLayout) factory.inflate(
2982 R.layout.ssl_success, placeholder);
2983 ((TextView)ll.findViewById(R.id.success))
2984 .setText(R.string.ssl_certificate_is_valid);
2985
2986 mSSLCertificateView = tab;
2987 mSSLCertificateDialog =
2988 new AlertDialog.Builder(this)
2989 .setTitle(R.string.ssl_certificate).setIcon(
2990 R.drawable.ic_dialog_browser_certificate_secure)
2991 .setView(certificateView)
2992 .setPositiveButton(R.string.ok,
2993 new DialogInterface.OnClickListener() {
2994 public void onClick(DialogInterface dialog,
2995 int whichButton) {
2996 mSSLCertificateDialog = null;
2997 mSSLCertificateView = null;
2998
2999 showPageInfo(tab, false);
3000 }
3001 })
3002 .setOnCancelListener(
3003 new DialogInterface.OnCancelListener() {
3004 public void onCancel(DialogInterface dialog) {
3005 mSSLCertificateDialog = null;
3006 mSSLCertificateView = null;
3007
3008 showPageInfo(tab, false);
3009 }
3010 })
3011 .show();
3012 }
3013
3014 /**
3015 * Displays the SSL error certificate dialog.
3016 * @param view The target web-view.
3017 * @param handler The SSL error handler responsible for cancelling the
3018 * connection that resulted in an SSL error or proceeding per user request.
3019 * @param error The SSL error object.
3020 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003021 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003022 final WebView view, final SslErrorHandler handler, final SslError error) {
3023
3024 final View certificateView =
3025 inflateCertificateView(error.getCertificate());
3026 if (certificateView == null) {
3027 return;
3028 }
3029
3030 LayoutInflater factory = LayoutInflater.from(this);
3031
3032 final LinearLayout placeholder =
3033 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3034
3035 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3036 LinearLayout ll = (LinearLayout)factory
3037 .inflate(R.layout.ssl_warning, placeholder);
3038 ((TextView)ll.findViewById(R.id.warning))
3039 .setText(R.string.ssl_untrusted);
3040 }
3041
3042 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3043 LinearLayout ll = (LinearLayout)factory
3044 .inflate(R.layout.ssl_warning, placeholder);
3045 ((TextView)ll.findViewById(R.id.warning))
3046 .setText(R.string.ssl_mismatch);
3047 }
3048
3049 if (error.hasError(SslError.SSL_EXPIRED)) {
3050 LinearLayout ll = (LinearLayout)factory
3051 .inflate(R.layout.ssl_warning, placeholder);
3052 ((TextView)ll.findViewById(R.id.warning))
3053 .setText(R.string.ssl_expired);
3054 }
3055
3056 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3057 LinearLayout ll = (LinearLayout)factory
3058 .inflate(R.layout.ssl_warning, placeholder);
3059 ((TextView)ll.findViewById(R.id.warning))
3060 .setText(R.string.ssl_not_yet_valid);
3061 }
3062
3063 mSSLCertificateOnErrorHandler = handler;
3064 mSSLCertificateOnErrorView = view;
3065 mSSLCertificateOnErrorError = error;
3066 mSSLCertificateOnErrorDialog =
3067 new AlertDialog.Builder(this)
3068 .setTitle(R.string.ssl_certificate).setIcon(
3069 R.drawable.ic_dialog_browser_certificate_partially_secure)
3070 .setView(certificateView)
3071 .setPositiveButton(R.string.ok,
3072 new DialogInterface.OnClickListener() {
3073 public void onClick(DialogInterface dialog,
3074 int whichButton) {
3075 mSSLCertificateOnErrorDialog = null;
3076 mSSLCertificateOnErrorView = null;
3077 mSSLCertificateOnErrorHandler = null;
3078 mSSLCertificateOnErrorError = null;
3079
Grace Kloba22ac16e2009-10-07 18:00:23 -07003080 view.getWebViewClient().onReceivedSslError(
3081 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003082 }
3083 })
3084 .setNeutralButton(R.string.page_info_view,
3085 new DialogInterface.OnClickListener() {
3086 public void onClick(DialogInterface dialog,
3087 int whichButton) {
3088 mSSLCertificateOnErrorDialog = null;
3089
3090 // do not clear the dialog state: we will
3091 // need to show the dialog again once the
3092 // user is done exploring the page-info details
3093
3094 showPageInfo(mTabControl.getTabFromView(view),
3095 true);
3096 }
3097 })
3098 .setOnCancelListener(
3099 new DialogInterface.OnCancelListener() {
3100 public void onCancel(DialogInterface dialog) {
3101 mSSLCertificateOnErrorDialog = null;
3102 mSSLCertificateOnErrorView = null;
3103 mSSLCertificateOnErrorHandler = null;
3104 mSSLCertificateOnErrorError = null;
3105
Grace Kloba22ac16e2009-10-07 18:00:23 -07003106 view.getWebViewClient().onReceivedSslError(
3107 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003108 }
3109 })
3110 .show();
3111 }
3112
3113 /**
3114 * Inflates the SSL certificate view (helper method).
3115 * @param certificate The SSL certificate.
3116 * @return The resultant certificate view with issued-to, issued-by,
3117 * issued-on, expires-on, and possibly other fields set.
3118 * If the input certificate is null, returns null.
3119 */
3120 private View inflateCertificateView(SslCertificate certificate) {
3121 if (certificate == null) {
3122 return null;
3123 }
3124
3125 LayoutInflater factory = LayoutInflater.from(this);
3126
3127 View certificateView = factory.inflate(
3128 R.layout.ssl_certificate, null);
3129
3130 // issued to:
3131 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3132 if (issuedTo != null) {
3133 ((TextView) certificateView.findViewById(R.id.to_common))
3134 .setText(issuedTo.getCName());
3135 ((TextView) certificateView.findViewById(R.id.to_org))
3136 .setText(issuedTo.getOName());
3137 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3138 .setText(issuedTo.getUName());
3139 }
3140
3141 // issued by:
3142 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3143 if (issuedBy != null) {
3144 ((TextView) certificateView.findViewById(R.id.by_common))
3145 .setText(issuedBy.getCName());
3146 ((TextView) certificateView.findViewById(R.id.by_org))
3147 .setText(issuedBy.getOName());
3148 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3149 .setText(issuedBy.getUName());
3150 }
3151
3152 // issued on:
3153 String issuedOn = reformatCertificateDate(
3154 certificate.getValidNotBefore());
3155 ((TextView) certificateView.findViewById(R.id.issued_on))
3156 .setText(issuedOn);
3157
3158 // expires on:
3159 String expiresOn = reformatCertificateDate(
3160 certificate.getValidNotAfter());
3161 ((TextView) certificateView.findViewById(R.id.expires_on))
3162 .setText(expiresOn);
3163
3164 return certificateView;
3165 }
3166
3167 /**
3168 * Re-formats the certificate date (Date.toString()) string to
3169 * a properly localized date string.
3170 * @return Properly localized version of the certificate date string and
3171 * the original certificate date string if fails to localize.
3172 * If the original string is null, returns an empty string "".
3173 */
3174 private String reformatCertificateDate(String certificateDate) {
3175 String reformattedDate = null;
3176
3177 if (certificateDate != null) {
3178 Date date = null;
3179 try {
3180 date = java.text.DateFormat.getInstance().parse(certificateDate);
3181 } catch (ParseException e) {
3182 date = null;
3183 }
3184
3185 if (date != null) {
3186 reformattedDate =
3187 DateFormat.getDateFormat(this).format(date);
3188 }
3189 }
3190
3191 return reformattedDate != null ? reformattedDate :
3192 (certificateDate != null ? certificateDate : "");
3193 }
3194
3195 /**
3196 * Displays an http-authentication dialog.
3197 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003198 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003199 final String host, final String realm, final String title,
3200 final String name, final String password, int focusId) {
3201 LayoutInflater factory = LayoutInflater.from(this);
3202 final View v = factory
3203 .inflate(R.layout.http_authentication, null);
3204 if (name != null) {
3205 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3206 }
3207 if (password != null) {
3208 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3209 }
3210
3211 String titleText = title;
3212 if (titleText == null) {
3213 titleText = getText(R.string.sign_in_to).toString().replace(
3214 "%s1", host).replace("%s2", realm);
3215 }
3216
3217 mHttpAuthHandler = handler;
3218 AlertDialog dialog = new AlertDialog.Builder(this)
3219 .setTitle(titleText)
3220 .setIcon(android.R.drawable.ic_dialog_alert)
3221 .setView(v)
3222 .setPositiveButton(R.string.action,
3223 new DialogInterface.OnClickListener() {
3224 public void onClick(DialogInterface dialog,
3225 int whichButton) {
3226 String nm = ((EditText) v
3227 .findViewById(R.id.username_edit))
3228 .getText().toString();
3229 String pw = ((EditText) v
3230 .findViewById(R.id.password_edit))
3231 .getText().toString();
3232 BrowserActivity.this.setHttpAuthUsernamePassword
3233 (host, realm, nm, pw);
3234 handler.proceed(nm, pw);
3235 mHttpAuthenticationDialog = null;
3236 mHttpAuthHandler = null;
3237 }})
3238 .setNegativeButton(R.string.cancel,
3239 new DialogInterface.OnClickListener() {
3240 public void onClick(DialogInterface dialog,
3241 int whichButton) {
3242 handler.cancel();
3243 BrowserActivity.this.resetTitleAndRevertLockIcon();
3244 mHttpAuthenticationDialog = null;
3245 mHttpAuthHandler = null;
3246 }})
3247 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3248 public void onCancel(DialogInterface dialog) {
3249 handler.cancel();
3250 BrowserActivity.this.resetTitleAndRevertLockIcon();
3251 mHttpAuthenticationDialog = null;
3252 mHttpAuthHandler = null;
3253 }})
3254 .create();
3255 // Make the IME appear when the dialog is displayed if applicable.
3256 dialog.getWindow().setSoftInputMode(
3257 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3258 dialog.show();
3259 if (focusId != 0) {
3260 dialog.findViewById(focusId).requestFocus();
3261 } else {
3262 v.findViewById(R.id.username_edit).requestFocus();
3263 }
3264 mHttpAuthenticationDialog = dialog;
3265 }
3266
3267 public int getProgress() {
3268 WebView w = mTabControl.getCurrentWebView();
3269 if (w != null) {
3270 return w.getProgress();
3271 } else {
3272 return 100;
3273 }
3274 }
3275
3276 /**
3277 * Set HTTP authentication password.
3278 *
3279 * @param host The host for the password
3280 * @param realm The realm for the password
3281 * @param username The username for the password. If it is null, it means
3282 * password can't be saved.
3283 * @param password The password
3284 */
3285 public void setHttpAuthUsernamePassword(String host, String realm,
3286 String username,
3287 String password) {
3288 WebView w = mTabControl.getCurrentWebView();
3289 if (w != null) {
3290 w.setHttpAuthUsernamePassword(host, realm, username, password);
3291 }
3292 }
3293
3294 /**
3295 * connectivity manager says net has come or gone... inform the user
3296 * @param up true if net has come up, false if net has gone down
3297 */
3298 public void onNetworkToggle(boolean up) {
3299 if (up == mIsNetworkUp) {
3300 return;
3301 } else if (up) {
3302 mIsNetworkUp = true;
3303 if (mAlertDialog != null) {
3304 mAlertDialog.cancel();
3305 mAlertDialog = null;
3306 }
3307 } else {
3308 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003309 if (mInLoad) {
3310 createAndShowNetworkDialog();
3311 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003312 }
3313 WebView w = mTabControl.getCurrentWebView();
3314 if (w != null) {
3315 w.setNetworkAvailable(up);
3316 }
3317 }
3318
Grace Kloba22ac16e2009-10-07 18:00:23 -07003319 boolean isNetworkUp() {
3320 return mIsNetworkUp;
3321 }
3322
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003323 // This method shows the network dialog alerting the user that the net is
3324 // down. It will only show the dialog if mAlertDialog is null.
3325 private void createAndShowNetworkDialog() {
3326 if (mAlertDialog == null) {
3327 mAlertDialog = new AlertDialog.Builder(this)
3328 .setTitle(R.string.loadSuspendedTitle)
3329 .setMessage(R.string.loadSuspended)
3330 .setPositiveButton(R.string.ok, null)
3331 .show();
3332 }
3333 }
3334
The Android Open Source Project0c908882009-03-03 19:32:16 -08003335 @Override
3336 protected void onActivityResult(int requestCode, int resultCode,
3337 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003338 if (getTopWindow() == null) return;
3339
The Android Open Source Project0c908882009-03-03 19:32:16 -08003340 switch (requestCode) {
3341 case COMBO_PAGE:
3342 if (resultCode == RESULT_OK && intent != null) {
3343 String data = intent.getAction();
3344 Bundle extras = intent.getExtras();
3345 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003346 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003347 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003348 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003349 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003350 dismissSubWindow(currentTab);
3351 if (data != null && data.length() != 0) {
3352 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003353 }
3354 }
3355 }
3356 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003357 // Choose a file from the file picker.
3358 case FILE_SELECTED:
3359 if (null == mUploadMessage) break;
3360 Uri result = intent == null || resultCode != RESULT_OK ? null
3361 : intent.getData();
3362 mUploadMessage.onReceiveValue(result);
3363 mUploadMessage = null;
3364 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003365 default:
3366 break;
3367 }
Leon Scroggins30444232009-09-04 18:36:20 -04003368 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003369 }
3370
3371 /*
3372 * This method is called as a result of the user selecting the options
3373 * menu to see the download window, or when a download changes state. It
3374 * shows the download window ontop of the current window.
3375 */
3376 /* package */ void viewDownloads(Uri downloadRecord) {
3377 Intent intent = new Intent(this,
3378 BrowserDownloadPage.class);
3379 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003380 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003381
3382 }
3383
Leon Scroggins160a7e72009-08-14 18:28:01 -04003384 /**
3385 * Open the Go page.
3386 * @param startWithHistory If true, open starting on the history tab.
3387 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003388 */
Leon Scroggins30444232009-09-04 18:36:20 -04003389 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003390 WebView current = mTabControl.getCurrentWebView();
3391 if (current == null) {
3392 return;
3393 }
3394 Intent intent = new Intent(this,
3395 CombinedBookmarkHistoryActivity.class);
3396 String title = current.getTitle();
3397 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003398 Bitmap thumbnail = createScreenshot(current);
3399
The Android Open Source Project0c908882009-03-03 19:32:16 -08003400 // Just in case the user opens bookmarks before a page finishes loading
3401 // so the current history item, and therefore the page, is null.
3402 if (null == url) {
3403 url = mLastEnteredUrl;
3404 // This can happen.
3405 if (null == url) {
3406 url = mSettings.getHomePage();
3407 }
3408 }
3409 // In case the web page has not yet received its associated title.
3410 if (title == null) {
3411 title = url;
3412 }
3413 intent.putExtra("title", title);
3414 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003415 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003416 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003417 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003418 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003419 if (startWithHistory) {
3420 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3421 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3422 }
3423 startActivityForResult(intent, COMBO_PAGE);
3424 }
3425
3426 // Called when loading from context menu or LOAD_URL message
3427 private void loadURL(WebView view, String url) {
3428 // In case the user enters nothing.
3429 if (url != null && url.length() != 0 && view != null) {
3430 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003431 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003432 view.loadUrl(url);
3433 }
3434 }
3435 }
3436
The Android Open Source Project0c908882009-03-03 19:32:16 -08003437 private String smartUrlFilter(Uri inUri) {
3438 if (inUri != null) {
3439 return smartUrlFilter(inUri.toString());
3440 }
3441 return null;
3442 }
3443
Feng Qianb34f87a2009-03-24 21:27:26 -07003444 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003445 "(?i)" + // switch on case insensitive matching
3446 "(" + // begin group for schema
3447 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003448 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003449 ")" +
3450 "(.*)" );
3451
3452 /**
3453 * Attempts to determine whether user input is a URL or search
3454 * terms. Anything with a space is passed to search.
3455 *
3456 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3457 * "Http://" converts to "http://"
3458 *
3459 * @return Original or modified URL
3460 *
3461 */
3462 String smartUrlFilter(String url) {
3463
3464 String inUrl = url.trim();
3465 boolean hasSpace = inUrl.indexOf(' ') != -1;
3466
3467 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3468 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003469 // force scheme to lowercase
3470 String scheme = matcher.group(1);
3471 String lcScheme = scheme.toLowerCase();
3472 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003473 inUrl = lcScheme + matcher.group(2);
3474 }
3475 if (hasSpace) {
3476 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003477 }
3478 return inUrl;
3479 }
3480 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003481 // FIXME: Is this the correct place to add to searches?
3482 // what if someone else calls this function?
3483 int shortcut = parseUrlShortcut(inUrl);
3484 if (shortcut != SHORTCUT_INVALID) {
3485 Browser.addSearchUrl(mResolver, inUrl);
3486 String query = inUrl.substring(2);
3487 switch (shortcut) {
3488 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003489 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003490 case SHORTCUT_WIKIPEDIA_SEARCH:
3491 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3492 case SHORTCUT_DICTIONARY_SEARCH:
3493 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3494 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003495 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003496 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003497 }
3498 }
3499 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003500 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003501 return URLUtil.guessUrl(inUrl);
3502 }
3503 }
3504
3505 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003506 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003507 }
3508
Ben Murdochbff2d602009-07-01 20:19:05 +01003509 /* package */ void setShouldShowErrorConsole(boolean flag) {
3510 if (flag == mShouldShowErrorConsole) {
3511 // Nothing to do.
3512 return;
3513 }
3514
3515 mShouldShowErrorConsole = flag;
3516
Grace Kloba22ac16e2009-10-07 18:00:23 -07003517 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3518 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003519
3520 if (flag) {
3521 // Setting the show state of the console will cause it's the layout to be inflated.
3522 if (errorConsole.numberOfErrors() > 0) {
3523 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3524 } else {
3525 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3526 }
3527
3528 // Now we can add it to the main view.
3529 mErrorConsoleContainer.addView(errorConsole,
3530 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
3531 ViewGroup.LayoutParams.WRAP_CONTENT));
3532 } else {
3533 mErrorConsoleContainer.removeView(errorConsole);
3534 }
3535
3536 }
3537
Grace Kloba22ac16e2009-10-07 18:00:23 -07003538 boolean shouldShowErrorConsole() {
3539 return mShouldShowErrorConsole;
3540 }
3541
Andrei Popescu163ab742009-10-20 17:58:23 +01003542 private void setStatusBarVisibility(boolean visible) {
3543 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3544 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3545 }
3546
Grace Klobaeb6eef42009-09-15 17:56:32 -07003547 final static int LOCK_ICON_UNSECURE = 0;
3548 final static int LOCK_ICON_SECURE = 1;
3549 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003550
The Android Open Source Project0c908882009-03-03 19:32:16 -08003551 private BrowserSettings mSettings;
3552 private TabControl mTabControl;
3553 private ContentResolver mResolver;
3554 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003555 private View mCustomView;
3556 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003557 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003558
3559 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3560 // view, we should rewrite this.
3561 private int mCurrentMenuState = 0;
3562 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003563 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003564 private static final int EMPTY_MENU = -1;
3565 private Menu mMenu;
3566
3567 private FindDialog mFindDialog;
3568 // Used to prevent chording to result in firing two shortcuts immediately
3569 // one after another. Fixes bug 1211714.
3570 boolean mCanChord;
3571
3572 private boolean mInLoad;
3573 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003574 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003575
The Android Open Source Project0c908882009-03-03 19:32:16 -08003576 private boolean mActivityInPause = true;
3577
3578 private boolean mMenuIsDown;
3579
The Android Open Source Project0c908882009-03-03 19:32:16 -08003580 private static boolean mInTrace;
3581
3582 // Performance probe
3583 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3584 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3585 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3586 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3587 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3588 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3589 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3590 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3591 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3592 };
3593
3594 private long mStart;
3595 private long mProcessStart;
3596 private long mUserStart;
3597 private long mSystemStart;
3598 private long mIdleStart;
3599 private long mIrqStart;
3600
3601 private long mUiStart;
3602
3603 private Drawable mMixLockIcon;
3604 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003605
3606 /* hold a ref so we can auto-cancel if necessary */
3607 private AlertDialog mAlertDialog;
3608
3609 // Wait for credentials before loading google.com
3610 private ProgressDialog mCredsDlg;
3611
3612 // The up-to-date URL and title (these can be different from those stored
3613 // in WebView, since it takes some time for the information in WebView to
3614 // get updated)
3615 private String mUrl;
3616 private String mTitle;
3617
3618 // As PageInfo has different style for landscape / portrait, we have
3619 // to re-open it when configuration changed
3620 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003621 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003622 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3623 // dialog, we should not just dismiss it, but should get back to the
3624 // SSL-certificate-on-error dialog. This flag is used to store this state
3625 private Boolean mPageInfoFromShowSSLCertificateOnError;
3626
3627 // as SSLCertificateOnError has different style for landscape / portrait,
3628 // we have to re-open it when configuration changed
3629 private AlertDialog mSSLCertificateOnErrorDialog;
3630 private WebView mSSLCertificateOnErrorView;
3631 private SslErrorHandler mSSLCertificateOnErrorHandler;
3632 private SslError mSSLCertificateOnErrorError;
3633
3634 // as SSLCertificate has different style for landscape / portrait, we
3635 // have to re-open it when configuration changed
3636 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003637 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003638
3639 // as HttpAuthentication has different style for landscape / portrait, we
3640 // have to re-open it when configuration changed
3641 private AlertDialog mHttpAuthenticationDialog;
3642 private HttpAuthHandler mHttpAuthHandler;
3643
3644 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3645 new FrameLayout.LayoutParams(
3646 ViewGroup.LayoutParams.FILL_PARENT,
3647 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003648 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3649 new FrameLayout.LayoutParams(
3650 ViewGroup.LayoutParams.FILL_PARENT,
3651 ViewGroup.LayoutParams.FILL_PARENT,
3652 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003653 // Google search
3654 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003655 // Wikipedia search
3656 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3657 // Dictionary search
3658 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3659 // Google Mobile Local search
3660 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3661
3662 final static String QUERY_PLACE_HOLDER = "%s";
3663
3664 // "source" parameter for Google search through search key
3665 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3666 // "source" parameter for Google search through goto menu
3667 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3668 // "source" parameter for Google search through simplily type
3669 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3670 // "source" parameter for Google search suggested by the browser
3671 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3672 // "source" parameter for Google search from unknown source
3673 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3674
3675 private final static String LOGTAG = "browser";
3676
The Android Open Source Project0c908882009-03-03 19:32:16 -08003677 private String mLastEnteredUrl;
3678
3679 private PowerManager.WakeLock mWakeLock;
3680 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3681
3682 private Toast mStopToast;
3683
Leon Scroggins68579392009-09-15 15:31:54 -04003684 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003685
Ben Murdochbff2d602009-07-01 20:19:05 +01003686 private LinearLayout mErrorConsoleContainer = null;
3687 private boolean mShouldShowErrorConsole = false;
3688
The Android Open Source Project0c908882009-03-03 19:32:16 -08003689 // As the ids are dynamically created, we can't guarantee that they will
3690 // be in sequence, so this static array maps ids to a window number.
3691 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3692 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3693 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3694 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3695
3696 // monitor platform changes
3697 private IntentFilter mNetworkStateChangedFilter;
3698 private BroadcastReceiver mNetworkStateIntentReceiver;
3699
Grace Klobab4da0ad2009-05-14 14:45:40 -07003700 private BroadcastReceiver mPackageInstallationReceiver;
3701
The Android Open Source Project0c908882009-03-03 19:32:16 -08003702 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003703 final static int COMBO_PAGE = 1;
3704 final static int DOWNLOAD_PAGE = 2;
3705 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003706 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003707
Andrei Popescu540035d2009-09-18 18:59:20 +01003708 // the default <video> poster
3709 private Bitmap mDefaultVideoPoster;
3710 // the video progress view
3711 private View mVideoProgressView;
3712
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003713 /**
3714 * A UrlData class to abstract how the content will be set to WebView.
3715 * This base class uses loadUrl to show the content.
3716 */
3717 private static class UrlData {
3718 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07003719 byte[] mPostData;
3720
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003721 UrlData(String url) {
3722 this.mUrl = url;
3723 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003724
3725 void setPostData(byte[] postData) {
3726 mPostData = postData;
3727 }
3728
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003729 boolean isEmpty() {
3730 return mUrl == null || mUrl.length() == 0;
3731 }
3732
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003733 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07003734 if (mPostData != null) {
3735 webView.postUrl(mUrl, mPostData);
3736 } else {
3737 webView.loadUrl(mUrl);
3738 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003739 }
3740 };
3741
3742 /**
3743 * A subclass of UrlData class that can display inlined content using
3744 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
3745 */
3746 private static class InlinedUrlData extends UrlData {
3747 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
3748 super(failUrl);
3749 mInlined = inlined;
3750 mMimeType = mimeType;
3751 mEncoding = encoding;
3752 }
3753 String mMimeType;
3754 String mInlined;
3755 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003756 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003757 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01003758 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003759 }
3760
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003761 @Override
3762 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003763 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
3764 }
3765 }
3766
Leon Scroggins1f005d32009-08-10 17:36:42 -04003767 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003768}