blob: c659fdd8fd190913bda7bdad97be0296dbea56a0 [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
The Android Open Source Project0c908882009-03-03 19:32:16 -080019import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080020import android.app.AlertDialog;
21import android.app.ProgressDialog;
22import android.app.SearchManager;
23import android.content.ActivityNotFoundException;
24import android.content.BroadcastReceiver;
25import android.content.ComponentName;
26import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040027import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080028import android.content.ContentValues;
29import android.content.Context;
30import android.content.DialogInterface;
31import android.content.Intent;
32import android.content.IntentFilter;
33import android.content.ServiceConnection;
Grace Klobab4da0ad2009-05-14 14:45:40 -070034import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080035import android.content.pm.PackageManager;
36import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080037import android.content.res.Configuration;
38import android.content.res.Resources;
39import android.database.Cursor;
The Android Open Source Project0c908882009-03-03 19:32:16 -080040import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010041import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080042import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080043import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040044import android.graphics.PixelFormat;
45import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080046import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080047import android.net.ConnectivityManager;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -040048import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.net.Uri;
50import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.net.http.SslCertificate;
52import android.net.http.SslError;
53import android.os.AsyncTask;
54import android.os.Bundle;
55import android.os.Debug;
56import android.os.Environment;
57import android.os.Handler;
58import android.os.IBinder;
59import android.os.Message;
60import android.os.PowerManager;
61import android.os.Process;
62import android.os.RemoteException;
63import android.os.ServiceManager;
64import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080065import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040066import android.provider.ContactsContract;
67import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.provider.Downloads;
69import android.provider.MediaStore;
The Android Open Source Project0c908882009-03-03 19:32:16 -080070import android.text.IClipboard;
71import android.text.TextUtils;
72import android.text.format.DateFormat;
Leon Scrogginsb94bf272009-09-25 15:22:08 -040073import android.util.AttributeSet;
The Android Open Source Project0c908882009-03-03 19:32:16 -080074import android.util.Log;
75import android.view.ContextMenu;
76import android.view.Gravity;
77import android.view.KeyEvent;
78import android.view.LayoutInflater;
79import android.view.Menu;
80import android.view.MenuInflater;
81import android.view.MenuItem;
82import android.view.View;
83import android.view.ViewGroup;
84import android.view.Window;
85import android.view.WindowManager;
86import android.view.ContextMenu.ContextMenuInfo;
87import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080088import android.webkit.CookieManager;
89import android.webkit.CookieSyncManager;
90import android.webkit.DownloadListener;
91import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070092import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080093import android.webkit.SslErrorHandler;
94import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010095import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080096import android.webkit.WebChromeClient;
97import android.webkit.WebHistoryItem;
98import android.webkit.WebIconDatabase;
99import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800100import android.widget.EditText;
101import android.widget.FrameLayout;
102import android.widget.LinearLayout;
103import android.widget.TextView;
104import android.widget.Toast;
105
Dan Egnor5ee906c2009-11-18 12:11:49 -0800106import com.android.common.Patterns;
107
108import com.google.android.googleapps.IGoogleLoginService;
109import com.google.android.googlelogin.GoogleLoginServiceConstants;
110
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400111import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800112import java.io.File;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800113import java.net.MalformedURLException;
114import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700115import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800116import java.net.URL;
117import java.net.URLEncoder;
118import java.text.ParseException;
119import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import java.util.HashMap;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800121import java.util.regex.Matcher;
122import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800123
124public class BrowserActivity extends Activity
Grace Kloba5942df02009-09-18 11:48:29 -0700125 implements View.OnCreateContextMenuListener,
The Android Open Source Project0c908882009-03-03 19:32:16 -0800126 DownloadListener {
127
Dave Bort31a6d1c2009-04-13 15:56:49 -0700128 /* Define some aliases to make these debugging flags easier to refer to.
129 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
130 */
131 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
132 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
133 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
134
The Android Open Source Project0c908882009-03-03 19:32:16 -0800135 private IGoogleLoginService mGls = null;
136 private ServiceConnection mGlsConnection = null;
137
Satish Sampath565505b2009-05-29 15:37:27 +0100138 // These are single-character shortcuts for searching popular sources.
139 private static final int SHORTCUT_INVALID = 0;
140 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
141 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
142 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
143 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
144
The Android Open Source Project0c908882009-03-03 19:32:16 -0800145 private void setupHomePage() {
146 final Runnable getAccount = new Runnable() {
147 public void run() {
148 // Lower priority
149 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
150 // get the default home page
151 String homepage = mSettings.getHomePage();
152
153 try {
154 if (mGls == null) return;
155
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700156 if (!homepage.startsWith("http://www.google.")) return;
157 if (homepage.indexOf('?') == -1) return;
158
The Android Open Source Project0c908882009-03-03 19:32:16 -0800159 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
160 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
161
162 // three cases:
163 //
164 // hostedUser == googleUser
165 // The device has only a google account
166 //
167 // hostedUser != googleUser
168 // The device has a hosted account and a google account
169 //
170 // hostedUser != null, googleUser == null
171 // The device has only a hosted account (so far)
172
173 // developers might have no accounts at all
174 if (hostedUser == null) return;
175
176 if (googleUser == null || !hostedUser.equals(googleUser)) {
177 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700178 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800179 }
180 } catch (RemoteException ignore) {
181 // Login service died; carry on
182 } catch (RuntimeException ignore) {
183 // Login service died; carry on
184 } finally {
185 finish(homepage);
186 }
187 }
188
189 private void finish(final String homepage) {
190 mHandler.post(new Runnable() {
191 public void run() {
192 mSettings.setHomePage(BrowserActivity.this, homepage);
193 resumeAfterCredentials();
194
195 // as this is running in a separate thread,
196 // BrowserActivity's onDestroy() may have been called,
197 // which also calls unbindService().
198 if (mGlsConnection != null) {
199 // we no longer need to keep GLS open
200 unbindService(mGlsConnection);
201 mGlsConnection = null;
202 }
203 } });
204 } };
205
206 final boolean[] done = { false };
207
208 // Open a connection to the Google Login Service. The first
209 // time the connection is established, set up the homepage depending on
210 // the account in a background thread.
211 mGlsConnection = new ServiceConnection() {
212 public void onServiceConnected(ComponentName className, IBinder service) {
213 mGls = IGoogleLoginService.Stub.asInterface(service);
214 if (done[0] == false) {
215 done[0] = true;
216 Thread account = new Thread(getAccount);
217 account.setName("GLSAccount");
218 account.start();
219 }
220 }
221 public void onServiceDisconnected(ComponentName className) {
222 mGls = null;
223 }
224 };
225
226 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
227 mGlsConnection, Context.BIND_AUTO_CREATE);
228 }
229
Cary Clarka9771242009-08-11 16:42:26 -0400230 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800231 @Override
232 public Void doInBackground(File... files) {
233 if (files != null) {
234 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400235 if (!f.delete()) {
236 Log.e(LOGTAG, f.getPath() + " was not deleted");
237 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800238 }
239 }
240 return null;
241 }
242 }
243
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400244 /**
245 * This layout holds everything you see below the status bar, including the
246 * error console, the custom view container, and the webviews.
247 */
248 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400249
Grace Kloba22ac16e2009-10-07 18:00:23 -0700250 @Override
251 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700252 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800253 Log.v(LOGTAG, this + " onStart");
254 }
255 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800256 // test the browser in OpenGL
257 // requestWindowFeature(Window.FEATURE_OPENGL);
258
259 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
260
261 mResolver = getContentResolver();
262
Grace Kloba0923d692009-09-23 21:37:25 -0700263 // If this was a web search request, pass it on to the default web
264 // search provider and finish this activity.
265 if (handleWebSearchIntent(getIntent())) {
266 finish();
267 return;
268 }
269
The Android Open Source Project0c908882009-03-03 19:32:16 -0800270 mSecLockIcon = Resources.getSystem().getDrawable(
271 android.R.drawable.ic_secure);
272 mMixLockIcon = Resources.getSystem().getDrawable(
273 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800274
Leon Scroggins81db3662009-06-04 17:45:11 -0400275 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
276 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400277 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
278 .inflate(R.layout.custom_screen, null);
279 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
280 R.id.main_content);
281 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
282 .findViewById(R.id.error_console);
283 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
284 .findViewById(R.id.fullscreen_custom_content);
285 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400286 mTitleBar = new TitleBar(this);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400287 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800288
289 // Create the tab control and our initial tab
290 mTabControl = new TabControl(this);
291
292 // Open the icon database and retain all the bookmark urls for favicons
293 retainIconsOnStartup();
294
295 // Keep a settings instance handy.
296 mSettings = BrowserSettings.getInstance();
297 mSettings.setTabControl(mTabControl);
298 mSettings.loadFromDb(this);
299
300 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
301 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
302
Grace Klobaa34f6862009-07-31 16:28:17 -0700303 /* enables registration for changes in network status from
304 http stack */
305 mNetworkStateChangedFilter = new IntentFilter();
306 mNetworkStateChangedFilter.addAction(
307 ConnectivityManager.CONNECTIVITY_ACTION);
308 mNetworkStateIntentReceiver = new BroadcastReceiver() {
309 @Override
310 public void onReceive(Context context, Intent intent) {
311 if (intent.getAction().equals(
312 ConnectivityManager.CONNECTIVITY_ACTION)) {
Robert Greenwalt7d899d62009-10-23 10:33:48 -0700313 boolean noConnectivity = intent.getBooleanExtra(
314 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
315 onNetworkToggle(!noConnectivity);
Grace Klobaa34f6862009-07-31 16:28:17 -0700316 }
317 }
318 };
319
Grace Kloba615c6c92009-08-03 10:22:44 -0700320 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
321 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
322 filter.addDataScheme("package");
323 mPackageInstallationReceiver = new BroadcastReceiver() {
324 @Override
325 public void onReceive(Context context, Intent intent) {
326 final String action = intent.getAction();
327 final String packageName = intent.getData()
328 .getSchemeSpecificPart();
329 final boolean replacing = intent.getBooleanExtra(
330 Intent.EXTRA_REPLACING, false);
331 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
332 // if it is replacing, refreshPlugins() when adding
333 return;
334 }
335 PackageManager pm = BrowserActivity.this.getPackageManager();
336 PackageInfo pkgInfo = null;
337 try {
338 pkgInfo = pm.getPackageInfo(packageName,
339 PackageManager.GET_PERMISSIONS);
340 } catch (PackageManager.NameNotFoundException e) {
341 return;
342 }
343 if (pkgInfo != null) {
344 String permissions[] = pkgInfo.requestedPermissions;
345 if (permissions == null) {
346 return;
347 }
348 boolean permissionOk = false;
349 for (String permit : permissions) {
350 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
351 permissionOk = true;
352 break;
353 }
354 }
355 if (permissionOk) {
356 PluginManager.getInstance(BrowserActivity.this)
357 .refreshPlugins(
358 Intent.ACTION_PACKAGE_ADDED
359 .equals(action));
360 }
361 }
362 }
363 };
364 registerReceiver(mPackageInstallationReceiver, filter);
365
The Android Open Source Project0c908882009-03-03 19:32:16 -0800366 if (!mTabControl.restoreState(icicle)) {
367 // clear up the thumbnail directory if we can't restore the state as
368 // none of the files in the directory are referenced any more.
369 new ClearThumbnails().execute(
370 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700371 // there is no quit on Android. But if we can't restore the state,
372 // we can treat it as a new Browser, remove the old session cookies.
373 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800374 final Intent intent = getIntent();
375 final Bundle extra = intent.getExtras();
376 // Create an initial tab.
377 // If the intent is ACTION_VIEW and data is not null, the Browser is
378 // invoked to view the content by another application. In this case,
379 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700380 UrlData urlData = getUrlDataFromIntent(intent);
381
Grace Kloba22ac16e2009-10-07 18:00:23 -0700382 final Tab t = mTabControl.createNewTab(
The Android Open Source Project0c908882009-03-03 19:32:16 -0800383 Intent.ACTION_VIEW.equals(intent.getAction()) &&
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700384 intent.getData() != null,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700385 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800386 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800387 attachTabToContentView(t);
388 WebView webView = t.getWebView();
389 if (extra != null) {
390 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
391 if (scale > 0 && scale <= 1000) {
392 webView.setInitialScale(scale);
393 }
394 }
395 // If we are not restoring from an icicle, then there is a high
396 // likely hood this is the first run. So, check to see if the
397 // homepage needs to be configured and copy any plugins from our
398 // asset directory to the data partition.
399 if ((extra == null || !extra.getBoolean("testing"))
400 && !mSettings.isLoginInitialized()) {
401 setupHomePage();
402 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800403
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700404 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400405 if (mSettings.isLoginInitialized()) {
406 webView.loadUrl(mSettings.getHomePage());
407 } else {
408 waitForCredentials();
409 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800410 } else {
Grace Kloba81678d92009-06-30 07:09:56 -0700411 if (extra != null) {
412 urlData.setPostData(extra
413 .getByteArray(Browser.EXTRA_POST_DATA));
414 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700415 urlData.loadIn(webView);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800416 }
417 } else {
418 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400419 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800420 attachTabToContentView(mTabControl.getCurrentTab());
421 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700422
Feng Qianb3c02da2009-06-29 15:58:08 -0700423 // Read JavaScript flags if it exists.
424 String jsFlags = mSettings.getJsFlags();
425 if (jsFlags.trim().length() != 0) {
426 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
427 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800428 }
429
430 @Override
431 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700432 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800433 // When a tab is closed on exit, the current tab index is set to -1.
434 // Reset before proceed as Browser requires the current tab to be set.
435 if (current == null) {
436 // Try to reset the tab in case the index was incorrect.
437 current = mTabControl.getTab(0);
438 if (current == null) {
439 // No tabs at all so just ignore this intent.
440 return;
441 }
442 mTabControl.setCurrentTab(current);
443 attachTabToContentView(current);
444 resetTitleAndIcon(current.getWebView());
445 }
446 final String action = intent.getAction();
447 final int flags = intent.getFlags();
448 if (Intent.ACTION_MAIN.equals(action) ||
449 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
450 // just resume the browser
451 return;
452 }
453 if (Intent.ACTION_VIEW.equals(action)
454 || Intent.ACTION_SEARCH.equals(action)
455 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
456 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100457 // If this was a search request (e.g. search query directly typed into the address bar),
458 // pass it on to the default web search provider.
459 if (handleWebSearchIntent(intent)) {
460 return;
461 }
462
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700463 UrlData urlData = getUrlDataFromIntent(intent);
464 if (urlData.isEmpty()) {
465 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800466 }
Grace Kloba81678d92009-06-30 07:09:56 -0700467 urlData.setPostData(intent
468 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700469
Grace Klobacc634032009-07-28 15:58:19 -0700470 final String appId = intent
471 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
472 if (Intent.ACTION_VIEW.equals(action)
473 && !getPackageName().equals(appId)
474 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700475 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700476 if (appTab != null) {
477 Log.i(LOGTAG, "Reusing tab for " + appId);
478 // Dismiss the subwindow if applicable.
479 dismissSubWindow(appTab);
480 // Since we might kill the WebView, remove it from the
481 // content view first.
482 removeTabFromContentView(appTab);
483 // Recreate the main WebView after destroying the old one.
484 // If the WebView has the same original url and is on that
485 // page, it can be reused.
486 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700487 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100488
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700489 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400490 switchToTab(mTabControl.getTabIndex(appTab));
491 if (needsLoad) {
492 urlData.loadIn(appTab.getWebView());
493 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700494 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400495 // If the tab was the current tab, we have to attach
496 // it to the view system again.
497 attachTabToContentView(appTab);
498 if (needsLoad) {
499 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700500 }
501 }
502 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400503 } else {
504 // No matching application tab, try to find a regular tab
505 // with a matching url.
506 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400507 if (appTab != null) {
508 if (current != appTab) {
509 switchToTab(mTabControl.getTabIndex(appTab));
510 }
511 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400512 } else {
513 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
514 // will be opened in a new tab unless we have reached
515 // MAX_TABS. Then the url will be opened in the current
516 // tab. If a new tab is created, it will have "true" for
517 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400518 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400519 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700520 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800521 } else {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700522 if ("about:debug".equals(urlData.mUrl)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800523 mSettings.toggleDebugSettings();
524 return;
525 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400526 // Get rid of the subwindow if it exists
527 dismissSubWindow(current);
528 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800529 }
530 }
531 }
532
Satish Sampath565505b2009-05-29 15:37:27 +0100533 private int parseUrlShortcut(String url) {
534 if (url == null) return SHORTCUT_INVALID;
535
536 // FIXME: quick search, need to be customized by setting
537 if (url.length() > 2 && url.charAt(1) == ' ') {
538 switch (url.charAt(0)) {
539 case 'g': return SHORTCUT_GOOGLE_SEARCH;
540 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
541 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
542 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
543 }
544 }
545 return SHORTCUT_INVALID;
546 }
547
548 /**
549 * Launches the default web search activity with the query parameters if the given intent's data
550 * are identified as plain search terms and not URLs/shortcuts.
551 * @return true if the intent was handled and web search activity was launched, false if not.
552 */
553 private boolean handleWebSearchIntent(Intent intent) {
554 if (intent == null) return false;
555
556 String url = null;
557 final String action = intent.getAction();
558 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700559 Uri data = intent.getData();
560 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100561 } else if (Intent.ACTION_SEARCH.equals(action)
562 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
563 || Intent.ACTION_WEB_SEARCH.equals(action)) {
564 url = intent.getStringExtra(SearchManager.QUERY);
565 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100566 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
567 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100568 }
569
570 /**
571 * Launches the default web search activity with the query parameters if the given url string
572 * was identified as plain search terms and not URL/shortcut.
573 * @return true if the request was handled and web search activity was launched, false if not.
574 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100575 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100576 if (inUrl == null) return false;
577
578 // In general, we shouldn't modify URL from Intent.
579 // But currently, we get the user-typed URL from search box as well.
580 String url = fixUrl(inUrl).trim();
581
582 // URLs and site specific search shortcuts are handled by the regular flow of control, so
583 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800584 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100585 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100586 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
587 return false;
588 }
589
590 Browser.updateVisitedHistory(mResolver, url, false);
591 Browser.addSearchUrl(mResolver, url);
592
593 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
594 intent.addCategory(Intent.CATEGORY_DEFAULT);
595 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100596 if (appData != null) {
597 intent.putExtra(SearchManager.APP_DATA, appData);
598 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100599 if (extraData != null) {
600 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
601 }
Grace Klobacc634032009-07-28 15:58:19 -0700602 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100603 startActivity(intent);
604
605 return true;
606 }
607
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700608 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800609 String url = null;
610 if (intent != null) {
611 final String action = intent.getAction();
612 if (Intent.ACTION_VIEW.equals(action)) {
613 url = smartUrlFilter(intent.getData());
614 if (url != null && url.startsWith("content:")) {
615 /* Append mimetype so webview knows how to display */
616 String mimeType = intent.resolveType(getContentResolver());
617 if (mimeType != null) {
618 url += "?" + mimeType;
619 }
620 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700621 if ("inline:".equals(url)) {
622 return new InlinedUrlData(
623 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
624 intent.getType(),
625 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
626 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
627 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800628 } else if (Intent.ACTION_SEARCH.equals(action)
629 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
630 || Intent.ACTION_WEB_SEARCH.equals(action)) {
631 url = intent.getStringExtra(SearchManager.QUERY);
632 if (url != null) {
633 mLastEnteredUrl = url;
634 // Don't add Urls, just search terms.
635 // Urls will get added when the page is loaded.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800636 if (!Patterns.WEB_URL.matcher(url).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800637 Browser.updateVisitedHistory(mResolver, url, false);
638 }
639 // In general, we shouldn't modify URL from Intent.
640 // But currently, we get the user-typed URL from search box as well.
641 url = fixUrl(url);
642 url = smartUrlFilter(url);
643 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
644 if (url.contains(searchSource)) {
645 String source = null;
646 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
647 if (appData != null) {
648 source = appData.getString(SearchManager.SOURCE);
649 }
650 if (TextUtils.isEmpty(source)) {
651 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
652 }
653 url = url.replace(searchSource, "&source=android-"+source+"&");
654 }
655 }
656 }
657 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700658 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800659 }
660
661 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400662 // FIXME: Converting the url to lower case
663 // duplicates functionality in smartUrlFilter().
664 // However, changing all current callers of fixUrl to
665 // call smartUrlFilter in addition may have unwanted
666 // consequences, and is deferred for now.
667 int colon = inUrl.indexOf(':');
668 boolean allLower = true;
669 for (int index = 0; index < colon; index++) {
670 char ch = inUrl.charAt(index);
671 if (!Character.isLetter(ch)) {
672 break;
673 }
674 allLower &= Character.isLowerCase(ch);
675 if (index == colon - 1 && !allLower) {
676 inUrl = inUrl.substring(0, colon).toLowerCase()
677 + inUrl.substring(colon);
678 }
679 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800680 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
681 return inUrl;
682 if (inUrl.startsWith("http:") ||
683 inUrl.startsWith("https:")) {
684 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
685 inUrl = inUrl.replaceFirst("/", "//");
686 } else inUrl = inUrl.replaceFirst(":", "://");
687 }
688 return inUrl;
689 }
690
Grace Kloba22ac16e2009-10-07 18:00:23 -0700691 @Override
692 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800693 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700694 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800695 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
696 }
697
698 if (!mActivityInPause) {
699 Log.e(LOGTAG, "BrowserActivity is already resumed.");
700 return;
701 }
702
Mike Reed7bfa63b2009-05-28 11:08:32 -0400703 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800704 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400705 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800706
707 if (mWakeLock.isHeld()) {
708 mHandler.removeMessages(RELEASE_WAKELOCK);
709 mWakeLock.release();
710 }
711
712 if (mCredsDlg != null) {
713 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
714 // In case credential request never comes back
715 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
716 }
717 }
718
719 registerReceiver(mNetworkStateIntentReceiver,
720 mNetworkStateChangedFilter);
721 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800722 }
723
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400724 /**
725 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400726 * would change its appearance, use a different TitleBar to show overlayed
727 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400728 */
729 private TitleBar mFakeTitleBar;
730
731 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400732 * Holder for the fake title bar. It will have a foreground shadow, as well
733 * as a white background, so the fake title bar looks like the real one.
734 */
735 private ViewGroup mFakeTitleBarHolder;
736
737 /**
738 * Layout parameters for the fake title bar within mFakeTitleBarHolder
739 */
740 private FrameLayout.LayoutParams mFakeTitleBarParams
741 = new FrameLayout.LayoutParams(
Leon Scrogginsc01e4a82009-09-16 14:41:00 -0400742 ViewGroup.LayoutParams.FILL_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400743 ViewGroup.LayoutParams.WRAP_CONTENT);
744 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400745 * Keeps track of whether the options menu is open. This is important in
746 * determining whether to show or hide the title bar overlay.
747 */
748 private boolean mOptionsMenuOpen;
749
750 /**
751 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
752 * of whether the configuration has changed. The first onMenuOpened call
753 * after a configuration change is simply a reopening of the same menu
754 * (i.e. mIconView did not change).
755 */
756 private boolean mConfigChanged;
757
758 /**
759 * Whether or not the options menu is in its smaller, icon menu form. When
760 * true, we want the title bar overlay to be up. When false, we do not.
761 * Only meaningful if mOptionsMenuOpen is true.
762 */
763 private boolean mIconView;
764
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400765 @Override
766 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400767 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
768 if (mOptionsMenuOpen) {
769 if (mConfigChanged) {
770 // We do not need to make any changes to the state of the
771 // title bar, since the only thing that happened was a
772 // change in orientation
773 mConfigChanged = false;
774 } else {
775 if (mIconView) {
776 // Switching the menu to expanded view, so hide the
777 // title bar.
778 hideFakeTitleBar();
779 mIconView = false;
780 } else {
781 // Switching the menu back to icon view, so show the
782 // title bar once again.
783 showFakeTitleBar();
784 mIconView = true;
785 }
786 }
787 } else {
788 // The options menu is closed, so open it, and show the title
789 showFakeTitleBar();
790 mOptionsMenuOpen = true;
791 mConfigChanged = false;
792 mIconView = true;
793 }
794 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400795 return true;
796 }
797
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400798 /**
799 * Special class used exclusively for the shadow drawn underneath the fake
800 * title bar. The shadow does not need to be drawn if the WebView
801 * underneath is scrolled to the top, because it will draw directly on top
802 * of the embedded shadow.
803 */
804 private static class Shadow extends View {
805 private WebView mWebView;
806
807 public Shadow(Context context, AttributeSet attrs) {
808 super(context, attrs);
809 }
810
811 public void setWebView(WebView view) {
812 mWebView = view;
813 }
814
815 @Override
816 public void draw(Canvas canvas) {
817 // In general onDraw is the method to override, but we care about
818 // whether or not the background gets drawn, which happens in draw()
819 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
820 super.draw(canvas);
821 }
822 // Need to invalidate so that if the scroll position changes, we
823 // still draw as appropriate.
824 invalidate();
825 }
826 }
827
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400828 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400829 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400830 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400831 && !mActivityInPause && decor != null
832 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400833 Rect visRect = new Rect();
834 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
835 if (LOGD_ENABLED) {
836 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
837 }
838 return;
839 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400840
841 WindowManager manager
842 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
843
844 // Add the title bar to the window manager so it can receive touches
845 // while the menu is up
846 WindowManager.LayoutParams params
847 = new WindowManager.LayoutParams(
848 ViewGroup.LayoutParams.FILL_PARENT,
849 ViewGroup.LayoutParams.WRAP_CONTENT,
850 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
851 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400852 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400853 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400854 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400855 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400856 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400857 // XXX : Without providing an offset, the fake title bar will be
858 // placed underneath the status bar. Use the global visible rect
859 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400860 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400861 // Add a holder for the title bar. It also holds a shadow to show
862 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400863 if (mFakeTitleBarHolder == null) {
864 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
865 .inflate(R.layout.title_bar_bg, null);
866 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400867 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
868 R.id.shadow);
869 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400870 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400871 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400872 }
873 }
874
875 @Override
876 public void onOptionsMenuClosed(Menu menu) {
877 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400878 if (!mInLoad) {
879 hideFakeTitleBar();
880 } else if (!mIconView) {
881 // The page is currently loading, and we are in expanded mode, so
882 // we were not showing the menu. Show it once again. It will be
883 // removed when the page finishes.
884 showFakeTitleBar();
885 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400886 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700887
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400888 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400889 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400890 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
891 mFakeTitleBarHolder.getLayoutParams();
892 WebView mainView = mTabControl.getCurrentWebView();
893 // Although we decided whether or not to animate based on the current
894 // scroll position, the scroll position may have changed since the
895 // fake title bar was displayed. Make sure it has the appropriate
896 // animation/lack thereof before removing.
897 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400898 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400899 WindowManager manager
900 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -0400901 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400902 mFakeTitleBarHolder.removeView(mFakeTitleBar);
903 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400904 }
905
The Android Open Source Project0c908882009-03-03 19:32:16 -0800906 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400907 * Special method for the fake title bar to call when displaying its context
908 * menu, since it is in its own Window, and its parent does not show a
909 * context menu.
910 */
911 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400912 if (null == mTitleBar.getParent()) {
913 return;
914 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400915 openContextMenu(mTitleBar);
916 }
917
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400918 @Override
919 public void onContextMenuClosed(Menu menu) {
920 super.onContextMenuClosed(menu);
921 if (mInLoad) {
922 showFakeTitleBar();
923 }
924 }
925
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400926 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800927 * onSaveInstanceState(Bundle map)
928 * onSaveInstanceState is called right before onStop(). The map contains
929 * the saved state.
930 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700931 @Override
932 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700933 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800934 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
935 }
936 // the default implementation requires each view to have an id. As the
937 // browser handles the state itself and it doesn't use id for the views,
938 // don't call the default implementation. Otherwise it will trigger the
939 // warning like this, "couldn't save which view has focus because the
940 // focused view XXX has no id".
941
942 // Save all the tabs
943 mTabControl.saveState(outState);
944 }
945
Grace Kloba22ac16e2009-10-07 18:00:23 -0700946 @Override
947 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800948 super.onPause();
949
950 if (mActivityInPause) {
951 Log.e(LOGTAG, "BrowserActivity is already paused.");
952 return;
953 }
954
Mike Reed7bfa63b2009-05-28 11:08:32 -0400955 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800956 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400957 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800958 mWakeLock.acquire();
959 mHandler.sendMessageDelayed(mHandler
960 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
961 }
962
963 // Clear the credentials toast if it is up
964 if (mCredsDlg != null && mCredsDlg.isShowing()) {
965 mCredsDlg.dismiss();
966 }
967 mCredsDlg = null;
968
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400969 // FIXME: This removes the active tabs page and resets the menu to
970 // MAIN_MENU. A better solution might be to do this work in onNewIntent
971 // but then we would need to save it in onSaveInstanceState and restore
972 // it in onCreate/onRestoreInstanceState
973 if (mActiveTabsPage != null) {
974 removeActiveTabPage(true);
975 }
976
The Android Open Source Project0c908882009-03-03 19:32:16 -0800977 cancelStopToast();
978
979 // unregister network state listener
980 unregisterReceiver(mNetworkStateIntentReceiver);
981 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800982 }
983
Grace Kloba22ac16e2009-10-07 18:00:23 -0700984 @Override
985 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700986 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800987 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
988 }
989 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700990
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400991 if (mUploadMessage != null) {
992 mUploadMessage.onReceiveValue(null);
993 mUploadMessage = null;
994 }
995
Grace Kloba0923d692009-09-23 21:37:25 -0700996 if (mTabControl == null) return;
997
Grace Kloba1fc98a32009-10-21 13:23:08 -0700998 // Remove the fake title bar if it is there
999 hideFakeTitleBar();
1000
The Android Open Source Project0c908882009-03-03 19:32:16 -08001001 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001002 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001003 if (t != null) {
1004 dismissSubWindow(t);
1005 removeTabFromContentView(t);
1006 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001007 // Destroy all the tabs
1008 mTabControl.destroy();
1009 WebIconDatabase.getInstance().close();
1010 if (mGlsConnection != null) {
1011 unbindService(mGlsConnection);
1012 mGlsConnection = null;
1013 }
1014
Grace Klobab4da0ad2009-05-14 14:45:40 -07001015 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001016 }
1017
1018 @Override
1019 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001020 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001021 super.onConfigurationChanged(newConfig);
1022
1023 if (mPageInfoDialog != null) {
1024 mPageInfoDialog.dismiss();
1025 showPageInfo(
1026 mPageInfoView,
1027 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1028 }
1029 if (mSSLCertificateDialog != null) {
1030 mSSLCertificateDialog.dismiss();
1031 showSSLCertificate(
1032 mSSLCertificateView);
1033 }
1034 if (mSSLCertificateOnErrorDialog != null) {
1035 mSSLCertificateOnErrorDialog.dismiss();
1036 showSSLCertificateOnError(
1037 mSSLCertificateOnErrorView,
1038 mSSLCertificateOnErrorHandler,
1039 mSSLCertificateOnErrorError);
1040 }
1041 if (mHttpAuthenticationDialog != null) {
1042 String title = ((TextView) mHttpAuthenticationDialog
1043 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1044 .toString();
1045 String name = ((TextView) mHttpAuthenticationDialog
1046 .findViewById(R.id.username_edit)).getText().toString();
1047 String password = ((TextView) mHttpAuthenticationDialog
1048 .findViewById(R.id.password_edit)).getText().toString();
1049 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1050 .getId();
1051 mHttpAuthenticationDialog.dismiss();
1052 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1053 name, password, focusId);
1054 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001055 }
1056
Grace Kloba22ac16e2009-10-07 18:00:23 -07001057 @Override
1058 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001059 super.onLowMemory();
1060 mTabControl.freeMemory();
1061 }
1062
Mike Reed7bfa63b2009-05-28 11:08:32 -04001063 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001064 Tab tab = mTabControl.getCurrentTab();
1065 boolean inLoad = tab.inLoad();
1066 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001067 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001068 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001069 if (w != null) {
1070 w.resumeTimers();
1071 }
1072 return true;
1073 } else {
1074 return false;
1075 }
1076 }
1077
Mike Reed7bfa63b2009-05-28 11:08:32 -04001078 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001079 Tab tab = mTabControl.getCurrentTab();
1080 boolean inLoad = tab.inLoad();
1081 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001082 CookieSyncManager.getInstance().stopSync();
1083 WebView w = mTabControl.getCurrentWebView();
1084 if (w != null) {
1085 w.pauseTimers();
1086 }
1087 return true;
1088 } else {
1089 return false;
1090 }
1091 }
1092
Leon Scroggins1f005d32009-08-10 17:36:42 -04001093 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001094 /*
1095 * This function is called when we are launching for the first time. We
1096 * are waiting for the login credentials before loading Google home
1097 * pages. This way the user will be logged in straight away.
1098 */
1099 private void waitForCredentials() {
1100 // Show a toast
1101 mCredsDlg = new ProgressDialog(this);
1102 mCredsDlg.setIndeterminate(true);
1103 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1104 // If the user cancels the operation, then cancel the Google
1105 // Credentials request.
1106 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1107 mCredsDlg.show();
1108
1109 // We set a timeout for the retrieval of credentials in onResume()
1110 // as that is when we have freed up some CPU time to get
1111 // the login credentials.
1112 }
1113
1114 /*
1115 * If we have received the credentials or we have timed out and we are
1116 * showing the credentials dialog, then it is time to move on.
1117 */
1118 private void resumeAfterCredentials() {
1119 if (mCredsDlg == null) {
1120 return;
1121 }
1122
1123 // Clear the toast
1124 if (mCredsDlg.isShowing()) {
1125 mCredsDlg.dismiss();
1126 }
1127 mCredsDlg = null;
1128
1129 // Clear any pending timeout
1130 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1131
1132 // Load the page
1133 WebView w = mTabControl.getCurrentWebView();
1134 if (w != null) {
1135 w.loadUrl(mSettings.getHomePage());
1136 }
1137
1138 // Update the settings, need to do this last as it can take a moment
1139 // to persist the settings. In the mean time we could be loading
1140 // content.
1141 mSettings.setLoginInitialized(this);
1142 }
1143
1144 // Open the icon database and retain all the icons for visited sites.
1145 private void retainIconsOnStartup() {
1146 final WebIconDatabase db = WebIconDatabase.getInstance();
1147 db.open(getDir("icons", 0).getPath());
1148 try {
1149 Cursor c = Browser.getAllBookmarks(mResolver);
1150 if (!c.moveToFirst()) {
1151 c.deactivate();
1152 return;
1153 }
1154 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1155 do {
1156 String url = c.getString(urlIndex);
1157 db.retainIconForPageUrl(url);
1158 } while (c.moveToNext());
1159 c.deactivate();
1160 } catch (IllegalStateException e) {
1161 Log.e(LOGTAG, "retainIconsOnStartup", e);
1162 }
1163 }
1164
1165 // Helper method for getting the top window.
1166 WebView getTopWindow() {
1167 return mTabControl.getCurrentTopWebView();
1168 }
1169
Grace Kloba22ac16e2009-10-07 18:00:23 -07001170 TabControl getTabControl() {
1171 return mTabControl;
1172 }
1173
The Android Open Source Project0c908882009-03-03 19:32:16 -08001174 @Override
1175 public boolean onCreateOptionsMenu(Menu menu) {
1176 super.onCreateOptionsMenu(menu);
1177
1178 MenuInflater inflater = getMenuInflater();
1179 inflater.inflate(R.menu.browser, menu);
1180 mMenu = menu;
1181 updateInLoadMenuItems();
1182 return true;
1183 }
1184
1185 /**
1186 * As the menu can be open when loading state changes
1187 * we must manually update the state of the stop/reload menu
1188 * item
1189 */
1190 private void updateInLoadMenuItems() {
1191 if (mMenu == null) {
1192 return;
1193 }
1194 MenuItem src = mInLoad ?
1195 mMenu.findItem(R.id.stop_menu_id):
1196 mMenu.findItem(R.id.reload_menu_id);
1197 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1198 dest.setIcon(src.getIcon());
1199 dest.setTitle(src.getTitle());
1200 }
1201
1202 @Override
1203 public boolean onContextItemSelected(MenuItem item) {
1204 // chording is not an issue with context menus, but we use the same
1205 // options selector, so set mCanChord to true so we can access them.
1206 mCanChord = true;
1207 int id = item.getItemId();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001208 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001209 // For the context menu from the title bar
1210 case R.id.title_bar_share_page_url:
1211 case R.id.title_bar_copy_page_url:
1212 WebView mainView = mTabControl.getCurrentWebView();
1213 if (null == mainView) {
1214 return false;
1215 }
1216 if (id == R.id.title_bar_share_page_url) {
1217 Browser.sendString(this, mainView.getUrl());
1218 } else {
1219 copy(mainView.getUrl());
1220 }
1221 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001222 // -- Browser context menu
1223 case R.id.open_context_menu_id:
1224 case R.id.open_newtab_context_menu_id:
1225 case R.id.bookmark_context_menu_id:
1226 case R.id.save_link_context_menu_id:
1227 case R.id.share_link_context_menu_id:
1228 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001229 final WebView webView = getTopWindow();
1230 if (null == webView) {
1231 return false;
1232 }
1233 final HashMap hrefMap = new HashMap();
1234 hrefMap.put("webview", webView);
1235 final Message msg = mHandler.obtainMessage(
1236 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001237 webView.requestFocusNodeHref(msg);
1238 break;
1239
1240 default:
1241 // For other context menus
1242 return onOptionsItemSelected(item);
1243 }
1244 mCanChord = false;
1245 return true;
1246 }
1247
1248 private Bundle createGoogleSearchSourceBundle(String source) {
1249 Bundle bundle = new Bundle();
1250 bundle.putString(SearchManager.SOURCE, source);
1251 return bundle;
1252 }
1253
1254 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001255 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001256 */
1257 @Override
1258 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001259 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001260 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001261 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001262 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001263 return true;
1264 }
1265
1266 @Override
1267 public void startSearch(String initialQuery, boolean selectInitialQuery,
1268 Bundle appSearchData, boolean globalSearch) {
1269 if (appSearchData == null) {
1270 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1271 }
1272 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1273 }
1274
Leon Scroggins1f005d32009-08-10 17:36:42 -04001275 /**
1276 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1277 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001278 * @param index Index of the tab to change to, as defined by
1279 * mTabControl.getTabIndex(Tab t).
1280 * @return boolean True if we successfully switched to a different tab. If
1281 * the indexth tab is null, or if that tab is the same as
1282 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001283 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001284 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001285 Tab tab = mTabControl.getTab(index);
1286 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001287 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001288 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001289 }
1290 if (currentTab != null) {
1291 // currentTab may be null if it was just removed. In that case,
1292 // we do not need to remove it
1293 removeTabFromContentView(currentTab);
1294 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001295 mTabControl.setCurrentTab(tab);
1296 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001297 resetTitleIconAndProgress();
1298 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001299 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001300 }
1301
Grace Kloba22ac16e2009-10-07 18:00:23 -07001302 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001303 return openTabAndShow(mSettings.getHomePage(), false, null);
1304 }
1305
Leon Scroggins1f005d32009-08-10 17:36:42 -04001306 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001307 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001308 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001309 // This is the last tab. Open a new one, with the home
1310 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001311 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001312 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001313 return;
1314 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001315 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001316 int indexToShow = -1;
1317 if (parent != null) {
1318 indexToShow = mTabControl.getTabIndex(parent);
1319 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001320 final int currentIndex = mTabControl.getCurrentIndex();
1321 // Try to move to the tab to the right
1322 indexToShow = currentIndex + 1;
1323 if (indexToShow > mTabControl.getTabCount() - 1) {
1324 // Try to move to the tab to the left
1325 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001326 }
1327 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001328 if (switchToTab(indexToShow)) {
1329 // Close window
1330 closeTab(current);
1331 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001332 }
1333
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001334 private ActiveTabsPage mActiveTabsPage;
1335
1336 /**
1337 * Remove the active tabs page.
1338 * @param needToAttach If true, the active tabs page did not attach a tab
1339 * to the content view, so we need to do that here.
1340 */
1341 /* package */ void removeActiveTabPage(boolean needToAttach) {
1342 mContentView.removeView(mActiveTabsPage);
1343 mActiveTabsPage = null;
1344 mMenuState = R.id.MAIN_MENU;
1345 if (needToAttach) {
1346 attachTabToContentView(mTabControl.getCurrentTab());
1347 }
1348 getTopWindow().requestFocus();
1349 }
1350
The Android Open Source Project0c908882009-03-03 19:32:16 -08001351 @Override
1352 public boolean onOptionsItemSelected(MenuItem item) {
1353 if (!mCanChord) {
1354 // The user has already fired a shortcut with this hold down of the
1355 // menu key.
1356 return false;
1357 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001358 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001359 return false;
1360 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001361 if (mMenuIsDown) {
1362 // The shortcut action consumes the MENU. Even if it is still down,
1363 // it won't trigger the next shortcut action. In the case of the
1364 // shortcut action triggering a new activity, like Bookmarks, we
1365 // won't get onKeyUp for MENU. So it is important to reset it here.
1366 mMenuIsDown = false;
1367 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001368 switch (item.getItemId()) {
1369 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001370 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001371 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001372 break;
1373
Leon Scroggins64b80f32009-08-07 12:03:34 -04001374 case R.id.goto_menu_id:
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001375 onSearchRequested();
1376 break;
1377
1378 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001379 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001380 break;
1381
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001382 case R.id.active_tabs_menu_id:
1383 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1384 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001385 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001386 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1387 mActiveTabsPage.requestFocus();
1388 mMenuState = EMPTY_MENU;
1389 break;
1390
Leon Scroggins1f005d32009-08-10 17:36:42 -04001391 case R.id.add_bookmark_menu_id:
1392 Intent i = new Intent(BrowserActivity.this,
1393 AddBookmarkPage.class);
1394 WebView w = getTopWindow();
1395 i.putExtra("url", w.getUrl());
1396 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001397 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001398 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001399 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001400 break;
1401
1402 case R.id.stop_reload_menu_id:
1403 if (mInLoad) {
1404 stopLoading();
1405 } else {
1406 getTopWindow().reload();
1407 }
1408 break;
1409
1410 case R.id.back_menu_id:
1411 getTopWindow().goBack();
1412 break;
1413
1414 case R.id.forward_menu_id:
1415 getTopWindow().goForward();
1416 break;
1417
1418 case R.id.close_menu_id:
1419 // Close the subwindow if it exists.
1420 if (mTabControl.getCurrentSubWindow() != null) {
1421 dismissSubWindow(mTabControl.getCurrentTab());
1422 break;
1423 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001424 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001425 break;
1426
1427 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001428 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001429 if (current != null) {
1430 dismissSubWindow(current);
1431 current.getWebView().loadUrl(mSettings.getHomePage());
1432 }
1433 break;
1434
1435 case R.id.preferences_menu_id:
1436 Intent intent = new Intent(this,
1437 BrowserPreferencesPage.class);
1438 startActivityForResult(intent, PREFERENCES_PAGE);
1439 break;
1440
1441 case R.id.find_menu_id:
1442 if (null == mFindDialog) {
1443 mFindDialog = new FindDialog(this);
1444 }
1445 mFindDialog.setWebView(getTopWindow());
1446 mFindDialog.show();
1447 mMenuState = EMPTY_MENU;
1448 break;
1449
1450 case R.id.select_text_id:
1451 getTopWindow().emulateShiftHeld();
1452 break;
1453 case R.id.page_info_menu_id:
1454 showPageInfo(mTabControl.getCurrentTab(), false);
1455 break;
1456
1457 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001458 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001459 break;
1460
1461 case R.id.share_page_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01001462 Browser.sendString(this, getTopWindow().getUrl(),
1463 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001464 break;
1465
1466 case R.id.dump_nav_menu_id:
1467 getTopWindow().debugDump();
1468 break;
1469
1470 case R.id.zoom_in_menu_id:
1471 getTopWindow().zoomIn();
1472 break;
1473
1474 case R.id.zoom_out_menu_id:
1475 getTopWindow().zoomOut();
1476 break;
1477
1478 case R.id.view_downloads_menu_id:
1479 viewDownloads(null);
1480 break;
1481
The Android Open Source Project0c908882009-03-03 19:32:16 -08001482 case R.id.window_one_menu_id:
1483 case R.id.window_two_menu_id:
1484 case R.id.window_three_menu_id:
1485 case R.id.window_four_menu_id:
1486 case R.id.window_five_menu_id:
1487 case R.id.window_six_menu_id:
1488 case R.id.window_seven_menu_id:
1489 case R.id.window_eight_menu_id:
1490 {
1491 int menuid = item.getItemId();
1492 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1493 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001494 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001495 if (desiredTab != null &&
1496 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001497 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001498 }
1499 break;
1500 }
1501 }
1502 }
1503 break;
1504
1505 default:
1506 if (!super.onOptionsItemSelected(item)) {
1507 return false;
1508 }
1509 // Otherwise fall through.
1510 }
1511 mCanChord = false;
1512 return true;
1513 }
1514
1515 public void closeFind() {
1516 mMenuState = R.id.MAIN_MENU;
1517 }
1518
Grace Kloba22ac16e2009-10-07 18:00:23 -07001519 @Override
1520 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001521 // This happens when the user begins to hold down the menu key, so
1522 // allow them to chord to get a shortcut.
1523 mCanChord = true;
1524 // Note: setVisible will decide whether an item is visible; while
1525 // setEnabled() will decide whether an item is enabled, which also means
1526 // whether the matching shortcut key will function.
1527 super.onPrepareOptionsMenu(menu);
1528 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001529 case EMPTY_MENU:
1530 if (mCurrentMenuState != mMenuState) {
1531 menu.setGroupVisible(R.id.MAIN_MENU, false);
1532 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1533 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001534 }
1535 break;
1536 default:
1537 if (mCurrentMenuState != mMenuState) {
1538 menu.setGroupVisible(R.id.MAIN_MENU, true);
1539 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1540 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001541 }
1542 final WebView w = getTopWindow();
1543 boolean canGoBack = false;
1544 boolean canGoForward = false;
1545 boolean isHome = false;
1546 if (w != null) {
1547 canGoBack = w.canGoBack();
1548 canGoForward = w.canGoForward();
1549 isHome = mSettings.getHomePage().equals(w.getUrl());
1550 }
1551 final MenuItem back = menu.findItem(R.id.back_menu_id);
1552 back.setEnabled(canGoBack);
1553
1554 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1555 home.setEnabled(!isHome);
1556
1557 menu.findItem(R.id.forward_menu_id)
1558 .setEnabled(canGoForward);
1559
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001560 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001561 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001562
The Android Open Source Project0c908882009-03-03 19:32:16 -08001563 // decide whether to show the share link option
1564 PackageManager pm = getPackageManager();
1565 Intent send = new Intent(Intent.ACTION_SEND);
1566 send.setType("text/plain");
1567 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1568 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1569
The Android Open Source Project0c908882009-03-03 19:32:16 -08001570 boolean isNavDump = mSettings.isNavDump();
1571 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1572 nav.setVisible(isNavDump);
1573 nav.setEnabled(isNavDump);
1574 break;
1575 }
1576 mCurrentMenuState = mMenuState;
1577 return true;
1578 }
1579
1580 @Override
1581 public void onCreateContextMenu(ContextMenu menu, View v,
1582 ContextMenuInfo menuInfo) {
1583 WebView webview = (WebView) v;
1584 WebView.HitTestResult result = webview.getHitTestResult();
1585 if (result == null) {
1586 return;
1587 }
1588
1589 int type = result.getType();
1590 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1591 Log.w(LOGTAG,
1592 "We should not show context menu when nothing is touched");
1593 return;
1594 }
1595 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1596 // let TextView handles context menu
1597 return;
1598 }
1599
1600 // Note, http://b/issue?id=1106666 is requesting that
1601 // an inflated menu can be used again. This is not available
1602 // yet, so inflate each time (yuk!)
1603 MenuInflater inflater = getMenuInflater();
1604 inflater.inflate(R.menu.browsercontext, menu);
1605
1606 // Show the correct menu group
1607 String extra = result.getExtra();
1608 menu.setGroupVisible(R.id.PHONE_MENU,
1609 type == WebView.HitTestResult.PHONE_TYPE);
1610 menu.setGroupVisible(R.id.EMAIL_MENU,
1611 type == WebView.HitTestResult.EMAIL_TYPE);
1612 menu.setGroupVisible(R.id.GEO_MENU,
1613 type == WebView.HitTestResult.GEO_TYPE);
1614 menu.setGroupVisible(R.id.IMAGE_MENU,
1615 type == WebView.HitTestResult.IMAGE_TYPE
1616 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1617 menu.setGroupVisible(R.id.ANCHOR_MENU,
1618 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1619 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1620
1621 // Setup custom handling depending on the type
1622 switch (type) {
1623 case WebView.HitTestResult.PHONE_TYPE:
1624 menu.setHeaderTitle(Uri.decode(extra));
1625 menu.findItem(R.id.dial_context_menu_id).setIntent(
1626 new Intent(Intent.ACTION_VIEW, Uri
1627 .parse(WebView.SCHEME_TEL + extra)));
1628 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1629 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001630 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001631 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1632 addIntent);
1633 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1634 new Copy(extra));
1635 break;
1636
1637 case WebView.HitTestResult.EMAIL_TYPE:
1638 menu.setHeaderTitle(extra);
1639 menu.findItem(R.id.email_context_menu_id).setIntent(
1640 new Intent(Intent.ACTION_VIEW, Uri
1641 .parse(WebView.SCHEME_MAILTO + extra)));
1642 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1643 new Copy(extra));
1644 break;
1645
1646 case WebView.HitTestResult.GEO_TYPE:
1647 menu.setHeaderTitle(extra);
1648 menu.findItem(R.id.map_context_menu_id).setIntent(
1649 new Intent(Intent.ACTION_VIEW, Uri
1650 .parse(WebView.SCHEME_GEO
1651 + URLEncoder.encode(extra))));
1652 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1653 new Copy(extra));
1654 break;
1655
1656 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1657 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1658 TextView titleView = (TextView) LayoutInflater.from(this)
1659 .inflate(android.R.layout.browser_link_context_header,
1660 null);
1661 titleView.setText(extra);
1662 menu.setHeaderView(titleView);
1663 // decide whether to show the open link in new tab option
1664 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001665 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001666 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1667 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001668 PackageManager pm = getPackageManager();
1669 Intent send = new Intent(Intent.ACTION_SEND);
1670 send.setType("text/plain");
1671 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1672 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1673 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1674 break;
1675 }
1676 // otherwise fall through to handle image part
1677 case WebView.HitTestResult.IMAGE_TYPE:
1678 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1679 menu.setHeaderTitle(extra);
1680 }
1681 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1682 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1683 menu.findItem(R.id.download_context_menu_id).
1684 setOnMenuItemClickListener(new Download(extra));
1685 break;
1686
1687 default:
1688 Log.w(LOGTAG, "We should not get here.");
1689 break;
1690 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001691 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001692 }
1693
The Android Open Source Project0c908882009-03-03 19:32:16 -08001694 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001695 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001696 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001697 // Attach the container that contains the main WebView and any other UI
1698 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001699 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001700
1701 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001702 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001703 if (errorConsole.numberOfErrors() == 0) {
1704 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1705 } else {
1706 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1707 }
1708
1709 mErrorConsoleContainer.addView(errorConsole,
1710 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1711 ViewGroup.LayoutParams.WRAP_CONTENT));
1712 }
1713
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001714 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001715 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001716 // Request focus on the top window.
1717 t.getTopWindow().requestFocus();
1718 }
1719
1720 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001721 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001722 t.attachSubWindow(mContentView);
1723 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001724 }
1725
1726 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001727 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001728 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001729 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001730
Grace Kloba22ac16e2009-10-07 18:00:23 -07001731 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1732 if (errorConsole != null) {
1733 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001734 }
1735
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001736 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001737 if (view != null) {
1738 view.setEmbeddedTitleBar(null);
1739 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001740 }
1741
1742 // Remove the sub window if it exists. Also called by TabControl when the
1743 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001744 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001745 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001746 // dismiss the subwindow. This will destroy the WebView.
1747 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001748 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001749 }
1750
Leon Scroggins1f005d32009-08-10 17:36:42 -04001751 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001752 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001753 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001754 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001755 }
1756
1757 // This method does a ton of stuff. It will attempt to create a new tab
1758 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001759 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001760 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1761 String appId) {
1762 final Tab currentTab = mTabControl.getCurrentTab();
1763 if (mTabControl.canCreateNewTab()) {
1764 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1765 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001766 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001767 // If the last tab was removed from the active tabs page, currentTab
1768 // will be null.
1769 if (currentTab != null) {
1770 removeTabFromContentView(currentTab);
1771 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001772 // We must set the new tab as the current tab to reflect the old
1773 // animation behavior.
1774 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001775 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001776 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001777 urlData.loadIn(webview);
1778 }
1779 return tab;
1780 } else {
1781 // Get rid of the subwindow if it exists
1782 dismissSubWindow(currentTab);
1783 if (!urlData.isEmpty()) {
1784 // Load the given url.
1785 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001786 }
1787 }
Grace Klobac9181842009-04-14 08:53:22 -07001788 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001789 }
1790
Grace Kloba22ac16e2009-10-07 18:00:23 -07001791 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001792 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001793 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001794 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001795 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001796 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001797 }
Grace Klobac9181842009-04-14 08:53:22 -07001798 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001799 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001800 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001801 }
1802 }
1803
1804 private class Copy implements OnMenuItemClickListener {
1805 private CharSequence mText;
1806
1807 public boolean onMenuItemClick(MenuItem item) {
1808 copy(mText);
1809 return true;
1810 }
1811
1812 public Copy(CharSequence toCopy) {
1813 mText = toCopy;
1814 }
1815 }
1816
1817 private class Download implements OnMenuItemClickListener {
1818 private String mText;
1819
1820 public boolean onMenuItemClick(MenuItem item) {
1821 onDownloadStartNoStream(mText, null, null, null, -1);
1822 return true;
1823 }
1824
1825 public Download(String toDownload) {
1826 mText = toDownload;
1827 }
1828 }
1829
1830 private void copy(CharSequence text) {
1831 try {
1832 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1833 if (clip != null) {
1834 clip.setClipboardText(text);
1835 }
1836 } catch (android.os.RemoteException e) {
1837 Log.e(LOGTAG, "Copy failed", e);
1838 }
1839 }
1840
1841 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001842 * Resets the browser title-view to whatever it must be
1843 * (for example, if we had a loading error)
1844 * When we have a new page, we call resetTitle, when we
1845 * have to reset the titlebar to whatever it used to be
1846 * (for example, if the user chose to stop loading), we
1847 * call resetTitleAndRevertLockIcon.
1848 */
1849 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001850 mTabControl.getCurrentTab().revertLockIcon();
1851 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001852 resetTitleIconAndProgress();
1853 }
1854
1855 /**
1856 * Reset the title, favicon, and progress.
1857 */
1858 private void resetTitleIconAndProgress() {
1859 WebView current = mTabControl.getCurrentWebView();
1860 if (current == null) {
1861 return;
1862 }
1863 resetTitleAndIcon(current);
1864 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001865 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001866 }
1867
1868 // Reset the title and the icon based on the given item.
1869 private void resetTitleAndIcon(WebView view) {
1870 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1871 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001872 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001873 setFavicon(item.getFavicon());
1874 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001875 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001876 setFavicon(null);
1877 }
1878 }
1879
1880 /**
1881 * Sets a title composed of the URL and the title string.
1882 * @param url The URL of the site being loaded.
1883 * @param title The title of the site being loaded.
1884 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001885 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001886 mUrl = url;
1887 mTitle = title;
1888
Leon Scroggins68579392009-09-15 15:31:54 -04001889 mTitleBar.setTitleAndUrl(title, url);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001890 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001891 }
1892
1893 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001894 * @param url The URL to build a title version of the URL from.
1895 * @return The title version of the URL or null if fails.
1896 * The title version of the URL can be either the URL hostname,
1897 * or the hostname with an "https://" prefix (for secure URLs),
1898 * or an empty string if, for example, the URL in question is a
1899 * file:// URL with no hostname.
1900 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001901 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001902 String titleUrl = null;
1903
1904 if (url != null) {
1905 try {
1906 // parse the url string
1907 URL urlObj = new URL(url);
1908 if (urlObj != null) {
1909 titleUrl = "";
1910
1911 String protocol = urlObj.getProtocol();
1912 String host = urlObj.getHost();
1913
1914 if (host != null && 0 < host.length()) {
1915 titleUrl = host;
1916 if (protocol != null) {
1917 // if a secure site, add an "https://" prefix!
1918 if (protocol.equalsIgnoreCase("https")) {
1919 titleUrl = protocol + "://" + host;
1920 }
1921 }
1922 }
1923 }
1924 } catch (MalformedURLException e) {}
1925 }
1926
1927 return titleUrl;
1928 }
1929
1930 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001931 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04001932 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001933 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001934 }
1935
1936 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001937 * Close the tab, remove its associated title bar, and adjust mTabControl's
1938 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001939 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001940 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001941 int currentIndex = mTabControl.getCurrentIndex();
1942 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001943 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001944 if (currentIndex >= removeIndex && currentIndex != 0) {
1945 currentIndex--;
1946 }
1947 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01001948 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001949 }
1950
1951 private void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001952 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001953 if (current == null) {
1954 /*
1955 * Instead of finishing the activity, simply push this to the back
1956 * of the stack and let ActivityManager to choose the foreground
1957 * activity. As BrowserActivity is singleTask, it will be always the
1958 * root of the task. So we can use either true or false for
1959 * moveTaskToBack().
1960 */
1961 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07001962 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001963 }
1964 WebView w = current.getWebView();
1965 if (w.canGoBack()) {
1966 w.goBack();
1967 } else {
1968 // Check to see if we are closing a window that was created by
1969 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001970 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001971 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001972 switchToTab(mTabControl.getTabIndex(parent));
1973 // Now we close the other tab
1974 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001975 } else {
1976 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001977 // force the tab's inLoad() to be false as we are going to
1978 // either finish the activity or remove the tab. This will
1979 // ensure pauseWebViewTimers() taking action.
1980 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001981 if (mTabControl.getTabCount() == 1) {
1982 finish();
1983 return;
1984 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04001985 // call pauseWebViewTimers() now, we won't be able to call
1986 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07001987 // Temporarily change mActivityInPause to be true as
1988 // pauseWebViewTimers() will do nothing if mActivityInPause
1989 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07001990 boolean savedState = mActivityInPause;
1991 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07001992 Log.e(LOGTAG, "BrowserActivity is already paused "
1993 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07001994 }
1995 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001996 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07001997 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001998 removeTabFromContentView(current);
1999 mTabControl.removeTab(current);
2000 }
2001 /*
2002 * Instead of finishing the activity, simply push this to the back
2003 * of the stack and let ActivityManager to choose the foreground
2004 * activity. As BrowserActivity is singleTask, it will be always the
2005 * root of the task. So we can use either true or false for
2006 * moveTaskToBack().
2007 */
2008 moveTaskToBack(true);
2009 }
2010 }
2011 }
2012
Grace Kloba22ac16e2009-10-07 18:00:23 -07002013 boolean isMenuDown() {
2014 return mMenuIsDown;
2015 }
2016
Grace Kloba5942df02009-09-18 11:48:29 -07002017 @Override
2018 public boolean onKeyDown(int keyCode, KeyEvent event) {
2019 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2020 // still down, we don't want to trigger the search. Pretend to consume
2021 // the key and do nothing.
2022 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002023
Grace Kloba5942df02009-09-18 11:48:29 -07002024 switch(keyCode) {
2025 case KeyEvent.KEYCODE_MENU:
2026 mMenuIsDown = true;
2027 break;
2028 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002029 // WebView/WebTextView handle the keys in the KeyDown. As
2030 // the Activity's shortcut keys are only handled when WebView
2031 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2032 if (event.isShiftPressed()) {
2033 getTopWindow().pageUp(false);
2034 } else {
2035 getTopWindow().pageDown(false);
2036 }
Grace Kloba5942df02009-09-18 11:48:29 -07002037 return true;
2038 case KeyEvent.KEYCODE_BACK:
2039 if (event.getRepeatCount() == 0) {
2040 event.startTracking();
2041 return true;
2042 } else if (mCustomView == null && mActiveTabsPage == null
2043 && event.isLongPress()) {
2044 bookmarksOrHistoryPicker(true);
2045 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002046 }
Grace Kloba5942df02009-09-18 11:48:29 -07002047 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002048 }
Grace Kloba5942df02009-09-18 11:48:29 -07002049 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002050 }
2051
Grace Kloba5942df02009-09-18 11:48:29 -07002052 @Override
2053 public boolean onKeyUp(int keyCode, KeyEvent event) {
2054 switch(keyCode) {
2055 case KeyEvent.KEYCODE_MENU:
2056 mMenuIsDown = false;
2057 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002058 case KeyEvent.KEYCODE_BACK:
2059 if (event.isTracking() && !event.isCanceled()) {
2060 if (mCustomView != null) {
2061 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002062 mTabControl.getCurrentWebView().getWebChromeClient()
2063 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002064 } else if (mActiveTabsPage != null) {
2065 // if tab page is showing, hide it
2066 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002067 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002068 WebView subwindow = mTabControl.getCurrentSubWindow();
2069 if (subwindow != null) {
2070 if (subwindow.canGoBack()) {
2071 subwindow.goBack();
2072 } else {
2073 dismissSubWindow(mTabControl.getCurrentTab());
2074 }
2075 } else {
2076 goBackOnePageOrQuit();
2077 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002078 }
Grace Kloba5942df02009-09-18 11:48:29 -07002079 return true;
2080 }
2081 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002082 }
Grace Kloba5942df02009-09-18 11:48:29 -07002083 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002084 }
2085
Leon Scroggins68579392009-09-15 15:31:54 -04002086 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002087 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002088 resetTitleAndRevertLockIcon();
2089 WebView w = getTopWindow();
2090 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002091 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2092 // same logic here. But for subwindow case, should we call into the main
2093 // WebView's onPageFinished as we never call its onPageStarted and if
2094 // the page finishes itself, we don't call onPageFinished.
2095 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2096 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002097
2098 cancelStopToast();
2099 mStopToast = Toast
2100 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2101 mStopToast.show();
2102 }
2103
Grace Kloba22ac16e2009-10-07 18:00:23 -07002104 boolean didUserStopLoading() {
2105 return mDidStopLoad;
2106 }
2107
The Android Open Source Project0c908882009-03-03 19:32:16 -08002108 private void cancelStopToast() {
2109 if (mStopToast != null) {
2110 mStopToast.cancel();
2111 mStopToast = null;
2112 }
2113 }
2114
Grace Kloba22ac16e2009-10-07 18:00:23 -07002115 // called by a UI or non-UI thread to post the message
2116 public void postMessage(int what, int arg1, int arg2, Object obj,
2117 long delayMillis) {
2118 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2119 obj), delayMillis);
2120 }
2121
2122 // called by a UI or non-UI thread to remove the message
2123 void removeMessages(int what, Object object) {
2124 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002125 }
2126
2127 // public message ids
2128 public final static int LOAD_URL = 1001;
2129 public final static int STOP_LOAD = 1002;
2130
2131 // Message Ids
2132 private static final int FOCUS_NODE_HREF = 102;
2133 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002134 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002135
Grace Kloba22ac16e2009-10-07 18:00:23 -07002136 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002137
The Android Open Source Project0c908882009-03-03 19:32:16 -08002138 // Private handler for handling javascript and saving passwords
2139 private Handler mHandler = new Handler() {
2140
2141 public void handleMessage(Message msg) {
2142 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002143 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002144 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002145 String url = (String) msg.getData().get("url");
2146 if (url == null || url.length() == 0) {
2147 break;
2148 }
2149 HashMap focusNodeMap = (HashMap) msg.obj;
2150 WebView view = (WebView) focusNodeMap.get("webview");
2151 // Only apply the action if the top window did not change.
2152 if (getTopWindow() != view) {
2153 break;
2154 }
2155 switch (msg.arg1) {
2156 case R.id.open_context_menu_id:
2157 case R.id.view_image_context_menu_id:
2158 loadURL(getTopWindow(), url);
2159 break;
2160 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002161 final Tab parent = mTabControl.getCurrentTab();
2162 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002163 if (newTab != parent) {
2164 parent.addChildTab(newTab);
2165 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002166 break;
2167 case R.id.bookmark_context_menu_id:
2168 Intent intent = new Intent(BrowserActivity.this,
2169 AddBookmarkPage.class);
2170 intent.putExtra("url", url);
2171 startActivity(intent);
2172 break;
2173 case R.id.share_link_context_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01002174 Browser.sendString(BrowserActivity.this, url,
2175 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002176 break;
2177 case R.id.copy_link_context_menu_id:
2178 copy(url);
2179 break;
2180 case R.id.save_link_context_menu_id:
2181 case R.id.download_context_menu_id:
2182 onDownloadStartNoStream(url, null, null, null, -1);
2183 break;
2184 }
2185 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002186 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002187
2188 case LOAD_URL:
2189 loadURL(getTopWindow(), (String) msg.obj);
2190 break;
2191
2192 case STOP_LOAD:
2193 stopLoading();
2194 break;
2195
2196 case CANCEL_CREDS_REQUEST:
2197 resumeAfterCredentials();
2198 break;
2199
The Android Open Source Project0c908882009-03-03 19:32:16 -08002200 case RELEASE_WAKELOCK:
2201 if (mWakeLock.isHeld()) {
2202 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002203 // if we reach here, Browser should be still in the
2204 // background loading after WAKELOCK_TIMEOUT (5-min).
2205 // To avoid burning the battery, stop loading.
2206 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002207 }
2208 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002209
2210 case UPDATE_BOOKMARK_THUMBNAIL:
2211 WebView view = (WebView) msg.obj;
2212 if (view != null) {
2213 updateScreenshot(view);
2214 }
2215 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002216 }
2217 }
2218 };
2219
Leon Scroggins89c6d362009-07-15 16:54:37 -04002220 private void updateScreenshot(WebView view) {
2221 // If this is a bookmarked site, add a screenshot to the database.
2222 // FIXME: When should we update? Every time?
2223 // FIXME: Would like to make sure there is actually something to
2224 // draw, but the API for that (WebViewCore.pictureReady()) is not
2225 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002226
Patrick Scott3918d442009-08-04 13:22:29 -04002227 ContentResolver cr = getContentResolver();
2228 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002229 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002230 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002231 boolean succeed = c.moveToFirst();
2232 ContentValues values = null;
2233 while (succeed) {
2234 if (values == null) {
2235 final ByteArrayOutputStream os
2236 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002237 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002238 if (bm == null) {
2239 c.close();
2240 return;
2241 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002242 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2243 values = new ContentValues();
2244 values.put(Browser.BookmarkColumns.THUMBNAIL,
2245 os.toByteArray());
2246 }
2247 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2248 c.getInt(0)), values, null, null);
2249 succeed = c.moveToNext();
2250 }
2251 c.close();
2252 }
2253 }
2254
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002255 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002256 * Values for the size of the thumbnail created when taking a screenshot.
2257 * Lazily initialized. Instead of using these directly, use
2258 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002259 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002260 private static int THUMBNAIL_WIDTH = 0;
2261 private static int THUMBNAIL_HEIGHT = 0;
2262
2263 /**
2264 * Return the desired width for thumbnail screenshots, which are stored in
2265 * the database, and used on the bookmarks screen.
2266 * @param context Context for finding out the density of the screen.
2267 * @return int desired width for thumbnail screenshot.
2268 */
2269 /* package */ static int getDesiredThumbnailWidth(Context context) {
2270 if (THUMBNAIL_WIDTH == 0) {
2271 float density = context.getResources().getDisplayMetrics().density;
2272 THUMBNAIL_WIDTH = (int) (90 * density);
2273 THUMBNAIL_HEIGHT = (int) (80 * density);
2274 }
2275 return THUMBNAIL_WIDTH;
2276 }
2277
2278 /**
2279 * Return the desired height 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 height for thumbnail screenshot.
2283 */
2284 /* package */ static int getDesiredThumbnailHeight(Context context) {
2285 // To ensure that they are both initialized.
2286 getDesiredThumbnailWidth(context);
2287 return THUMBNAIL_HEIGHT;
2288 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002289
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002290 private Bitmap createScreenshot(WebView view) {
2291 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002292 if (thumbnail == null) {
2293 return null;
2294 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002295 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2296 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002297 Canvas canvas = new Canvas(bm);
2298 // May need to tweak these values to determine what is the
2299 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002300 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002301 int thumbnailHeight = thumbnail.getHeight();
2302 float scaleFactorX = 1.0f;
2303 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002304 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002305 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002306 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002307 } else {
2308 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002309 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002310
2311 if (view.getWidth() > view.getHeight() &&
2312 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2313 // If the device is in landscape and the page is shorter
2314 // than the height of the view, stretch the thumbnail to fill the
2315 // space.
2316 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2317 (float)thumbnailHeight;
2318 } else {
2319 // In the portrait case, this looks nice.
2320 scaleFactorY = scaleFactorX;
2321 }
2322
2323 canvas.scale(scaleFactorX, scaleFactorY);
2324
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002325 thumbnail.draw(canvas);
2326 return bm;
2327 }
2328
The Android Open Source Project0c908882009-03-03 19:32:16 -08002329 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002330 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002331 //-------------------------------------------------------------------------
2332
2333 // Use in overrideUrlLoading
2334 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2335 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2336 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2337 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2338
Grace Kloba22ac16e2009-10-07 18:00:23 -07002339 void onPageStarted(WebView view, String url, Bitmap favicon) {
2340 // when BrowserActivity just starts, onPageStarted may be called before
2341 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2342 // to start the timer. As we won't switch tabs while an activity is in
2343 // pause state, we can ensure calling resume and pause in pair.
2344 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002345
Grace Kloba22ac16e2009-10-07 18:00:23 -07002346 resetLockIcon(url);
2347 setUrlTitle(url, null);
2348 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002349 // Keep this initial progress in sync with initialProgressValue (* 100)
2350 // in ProgressTracker.cpp
2351 // Show some progress so that the user knows the page is beginning to
2352 // load
2353 onProgressChanged(view, 10);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002354 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002355 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002356
Grace Kloba22ac16e2009-10-07 18:00:23 -07002357 if (mSettings.isTracing()) {
2358 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002359 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002360 WebAddress uri = new WebAddress(url);
2361 host = uri.mHost;
2362 } catch (android.net.ParseException ex) {
2363 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002364 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002365 host = host.replace('.', '_');
2366 host += ".trace";
2367 mInTrace = true;
2368 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2369 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002370
Grace Kloba22ac16e2009-10-07 18:00:23 -07002371 // Performance probe
2372 if (false) {
2373 mStart = SystemClock.uptimeMillis();
2374 mProcessStart = Process.getElapsedCpuTime();
2375 long[] sysCpu = new long[7];
2376 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2377 sysCpu, null)) {
2378 mUserStart = sysCpu[0] + sysCpu[1];
2379 mSystemStart = sysCpu[2];
2380 mIdleStart = sysCpu[3];
2381 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2382 }
2383 mUiStart = SystemClock.currentThreadTimeMillis();
2384 }
2385 }
2386
2387 void onPageFinished(WebView view, String url) {
2388 // Reset the title and icon in case we stopped a provisional load.
2389 resetTitleAndIcon(view);
2390 // Update the lock icon image only once we are done loading
2391 updateLockIconToLatest();
2392 // pause the WebView timer and release the wake lock if it is finished
2393 // while BrowserActivity is in pause state.
2394 if (mActivityInPause && pauseWebViewTimers()) {
2395 if (mWakeLock.isHeld()) {
2396 mHandler.removeMessages(RELEASE_WAKELOCK);
2397 mWakeLock.release();
2398 }
2399 }
2400
2401 // Performance probe
2402 if (false) {
2403 long[] sysCpu = new long[7];
2404 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2405 sysCpu, null)) {
2406 String uiInfo = "UI thread used "
2407 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2408 + " ms";
2409 if (LOGD_ENABLED) {
2410 Log.d(LOGTAG, uiInfo);
2411 }
2412 //The string that gets written to the log
2413 String performanceString = "It took total "
2414 + (SystemClock.uptimeMillis() - mStart)
2415 + " ms clock time to load the page."
2416 + "\nbrowser process used "
2417 + (Process.getElapsedCpuTime() - mProcessStart)
2418 + " ms, user processes used "
2419 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2420 + " ms, kernel used "
2421 + (sysCpu[2] - mSystemStart) * 10
2422 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2423 + " ms and irq took "
2424 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2425 * 10 + " ms, " + uiInfo;
2426 if (LOGD_ENABLED) {
2427 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2428 }
2429 if (url != null) {
2430 // strip the url to maintain consistency
2431 String newUrl = new String(url);
2432 if (newUrl.startsWith("http://www.")) {
2433 newUrl = newUrl.substring(11);
2434 } else if (newUrl.startsWith("http://")) {
2435 newUrl = newUrl.substring(7);
2436 } else if (newUrl.startsWith("https://www.")) {
2437 newUrl = newUrl.substring(12);
2438 } else if (newUrl.startsWith("https://")) {
2439 newUrl = newUrl.substring(8);
2440 }
2441 if (LOGD_ENABLED) {
2442 Log.d(LOGTAG, newUrl + " loaded");
2443 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002444 }
2445 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002446 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002447
Grace Kloba22ac16e2009-10-07 18:00:23 -07002448 if (mInTrace) {
2449 mInTrace = false;
2450 Debug.stopMethodTracing();
2451 }
2452 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002453
Grace Kloba22ac16e2009-10-07 18:00:23 -07002454 boolean shouldOverrideUrlLoading(WebView view, String url) {
2455 if (url.startsWith(SCHEME_WTAI)) {
2456 // wtai://wp/mc;number
2457 // number=string(phone-number)
2458 if (url.startsWith(SCHEME_WTAI_MC)) {
2459 Intent intent = new Intent(Intent.ACTION_VIEW,
2460 Uri.parse(WebView.SCHEME_TEL +
2461 url.substring(SCHEME_WTAI_MC.length())));
2462 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002463 return true;
2464 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002465 // wtai://wp/sd;dtmf
2466 // dtmf=string(dialstring)
2467 if (url.startsWith(SCHEME_WTAI_SD)) {
2468 // TODO: only send when there is active voice connection
2469 return false;
2470 }
2471 // wtai://wp/ap;number;name
2472 // number=string(phone-number)
2473 // name=string
2474 if (url.startsWith(SCHEME_WTAI_AP)) {
2475 // TODO
2476 return false;
2477 }
2478 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002479
Grace Kloba22ac16e2009-10-07 18:00:23 -07002480 // The "about:" schemes are internal to the browser; don't want these to
2481 // be dispatched to other apps.
2482 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002483 return false;
2484 }
2485
Grace Kloba22ac16e2009-10-07 18:00:23 -07002486 Intent intent;
2487 // perform generic parsing of the URI to turn it into an Intent.
2488 try {
2489 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2490 } catch (URISyntaxException ex) {
2491 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2492 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002493 }
2494
Grace Kloba22ac16e2009-10-07 18:00:23 -07002495 // check whether the intent can be resolved. If not, we will see
2496 // whether we can download it from the Market.
2497 if (getPackageManager().resolveActivity(intent, 0) == null) {
2498 String packagename = intent.getPackage();
2499 if (packagename != null) {
2500 intent = new Intent(Intent.ACTION_VIEW, Uri
2501 .parse("market://search?q=pname:" + packagename));
2502 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2503 startActivity(intent);
2504 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002505 } else {
2506 return false;
2507 }
2508 }
2509
Grace Kloba22ac16e2009-10-07 18:00:23 -07002510 // sanitize the Intent, ensuring web pages can not bypass browser
2511 // security (only access to BROWSABLE activities).
2512 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2513 intent.setComponent(null);
2514 try {
2515 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002516 return true;
2517 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002518 } catch (ActivityNotFoundException ex) {
2519 // ignore the error. If no application can handle the URL,
2520 // eg about:blank, assume the browser can handle it.
2521 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002522
Grace Kloba22ac16e2009-10-07 18:00:23 -07002523 if (mMenuIsDown) {
2524 openTab(url);
2525 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002526 return true;
2527 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002528 return false;
2529 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002530
Grace Kloba22ac16e2009-10-07 18:00:23 -07002531 // -------------------------------------------------------------------------
2532 // Helper function for WebChromeClient
2533 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002534
Grace Kloba22ac16e2009-10-07 18:00:23 -07002535 void onProgressChanged(WebView view, int newProgress) {
2536 mTitleBar.setProgress(newProgress);
2537 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002538
Grace Kloba22ac16e2009-10-07 18:00:23 -07002539 if (newProgress == 100) {
2540 // onProgressChanged() may continue to be called after the main
2541 // frame has finished loading, as any remaining sub frames continue
2542 // to load. We'll only get called once though with newProgress as
2543 // 100 when everything is loaded. (onPageFinished is called once
2544 // when the main frame completes loading regardless of the state of
2545 // any sub frames so calls to onProgressChanges may continue after
2546 // onPageFinished has executed)
2547 if (mInLoad) {
2548 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002549 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002550 // If the options menu is open, leave the title bar
2551 if (!mOptionsMenuOpen || !mIconView) {
2552 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002553 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002554 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002555 } else if (!mInLoad) {
2556 // onPageFinished may have already been called but a subframe is
2557 // still loading and updating the progress. Reset mInLoad and update
2558 // the menu items.
2559 mInLoad = true;
2560 updateInLoadMenuItems();
2561 if (!mOptionsMenuOpen || mIconView) {
2562 // This page has begun to load, so show the title bar
2563 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002564 }
2565 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002566 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002567
Grace Kloba22ac16e2009-10-07 18:00:23 -07002568 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2569 if (mCustomView != null)
2570 return;
2571
2572 // Add the custom view to its container.
2573 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2574 mCustomView = view;
2575 mCustomViewCallback = callback;
2576 // Save the menu state and set it to empty while the custom
2577 // view is showing.
2578 mOldMenuState = mMenuState;
2579 mMenuState = EMPTY_MENU;
2580 // Hide the content view.
2581 mContentView.setVisibility(View.GONE);
2582 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002583 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002584 mCustomViewContainer.setVisibility(View.VISIBLE);
2585 mCustomViewContainer.bringToFront();
2586 }
2587
2588 void onHideCustomView() {
2589 if (mCustomView == null)
2590 return;
2591
2592 // Hide the custom view.
2593 mCustomView.setVisibility(View.GONE);
2594 // Remove the custom view from its container.
2595 mCustomViewContainer.removeView(mCustomView);
2596 mCustomView = null;
2597 // Reset the old menu state.
2598 mMenuState = mOldMenuState;
2599 mOldMenuState = EMPTY_MENU;
2600 mCustomViewContainer.setVisibility(View.GONE);
2601 mCustomViewCallback.onCustomViewHidden();
2602 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002603 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002604 mContentView.setVisibility(View.VISIBLE);
2605 }
2606
2607 Bitmap getDefaultVideoPoster() {
2608 if (mDefaultVideoPoster == null) {
2609 mDefaultVideoPoster = BitmapFactory.decodeResource(
2610 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002611 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002612 return mDefaultVideoPoster;
2613 }
Patrick Scott3918d442009-08-04 13:22:29 -04002614
Grace Kloba22ac16e2009-10-07 18:00:23 -07002615 View getVideoLoadingProgressView() {
2616 if (mVideoProgressView == null) {
2617 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2618 mVideoProgressView = inflater.inflate(
2619 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002620 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002621 return mVideoProgressView;
2622 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002623
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002624 /*
2625 * The Object used to inform the WebView of the file to upload.
2626 */
2627 private ValueCallback<Uri> mUploadMessage;
2628
Grace Kloba22ac16e2009-10-07 18:00:23 -07002629 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2630 if (mUploadMessage != null) return;
2631 mUploadMessage = uploadMsg;
2632 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2633 i.addCategory(Intent.CATEGORY_OPENABLE);
2634 i.setType("*/*");
2635 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2636 getString(R.string.choose_upload)), FILE_SELECTED);
2637 }
2638
2639 // -------------------------------------------------------------------------
2640 // Implement functions for DownloadListener
2641 // -------------------------------------------------------------------------
2642
The Android Open Source Project0c908882009-03-03 19:32:16 -08002643 /**
2644 * Notify the host application a download should be done, or that
2645 * the data should be streamed if a streaming viewer is available.
2646 * @param url The full url to the content that should be downloaded
2647 * @param contentDisposition Content-disposition http header, if
2648 * present.
2649 * @param mimetype The mimetype of the content reported by the server
2650 * @param contentLength The file size reported by the server
2651 */
2652 public void onDownloadStart(String url, String userAgent,
2653 String contentDisposition, String mimetype, long contentLength) {
2654 // if we're dealing wih A/V content that's not explicitly marked
2655 // for download, check if it's streamable.
2656 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002657 || !contentDisposition.regionMatches(
2658 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002659 // query the package manager to see if there's a registered handler
2660 // that matches.
2661 Intent intent = new Intent(Intent.ACTION_VIEW);
2662 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002663 ResolveInfo info = getPackageManager().resolveActivity(intent,
2664 PackageManager.MATCH_DEFAULT_ONLY);
2665 if (info != null) {
2666 ComponentName myName = getComponentName();
2667 // If we resolved to ourselves, we don't want to attempt to
2668 // load the url only to try and download it again.
2669 if (!myName.getPackageName().equals(
2670 info.activityInfo.packageName)
2671 || !myName.getClassName().equals(
2672 info.activityInfo.name)) {
2673 // someone (other than us) knows how to handle this mime
2674 // type with this scheme, don't download.
2675 try {
2676 startActivity(intent);
2677 return;
2678 } catch (ActivityNotFoundException ex) {
2679 if (LOGD_ENABLED) {
2680 Log.d(LOGTAG, "activity not found for " + mimetype
2681 + " over " + Uri.parse(url).getScheme(),
2682 ex);
2683 }
2684 // Best behavior is to fall back to a download in this
2685 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002686 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002687 }
2688 }
2689 }
2690 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2691 }
2692
2693 /**
2694 * Notify the host application a download should be done, even if there
2695 * is a streaming viewer available for thise type.
2696 * @param url The full url to the content that should be downloaded
2697 * @param contentDisposition Content-disposition http header, if
2698 * present.
2699 * @param mimetype The mimetype of the content reported by the server
2700 * @param contentLength The file size reported by the server
2701 */
2702 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2703 String contentDisposition, String mimetype, long contentLength) {
2704
2705 String filename = URLUtil.guessFileName(url,
2706 contentDisposition, mimetype);
2707
2708 // Check to see if we have an SDCard
2709 String status = Environment.getExternalStorageState();
2710 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2711 int title;
2712 String msg;
2713
2714 // Check to see if the SDCard is busy, same as the music app
2715 if (status.equals(Environment.MEDIA_SHARED)) {
2716 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2717 title = R.string.download_sdcard_busy_dlg_title;
2718 } else {
2719 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2720 title = R.string.download_no_sdcard_dlg_title;
2721 }
2722
2723 new AlertDialog.Builder(this)
2724 .setTitle(title)
2725 .setIcon(android.R.drawable.ic_dialog_alert)
2726 .setMessage(msg)
2727 .setPositiveButton(R.string.ok, null)
2728 .show();
2729 return;
2730 }
2731
2732 // java.net.URI is a lot stricter than KURL so we have to undo
2733 // KURL's percent-encoding and redo the encoding using java.net.URI.
2734 URI uri = null;
2735 try {
2736 // Undo the percent-encoding that KURL may have done.
2737 String newUrl = new String(URLUtil.decode(url.getBytes()));
2738 // Parse the url into pieces
2739 WebAddress w = new WebAddress(newUrl);
2740 String frag = null;
2741 String query = null;
2742 String path = w.mPath;
2743 // Break the path into path, query, and fragment
2744 if (path.length() > 0) {
2745 // Strip the fragment
2746 int idx = path.lastIndexOf('#');
2747 if (idx != -1) {
2748 frag = path.substring(idx + 1);
2749 path = path.substring(0, idx);
2750 }
2751 idx = path.lastIndexOf('?');
2752 if (idx != -1) {
2753 query = path.substring(idx + 1);
2754 path = path.substring(0, idx);
2755 }
2756 }
2757 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2758 query, frag);
2759 } catch (Exception e) {
2760 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2761 return;
2762 }
2763
2764 // XXX: Have to use the old url since the cookies were stored using the
2765 // old percent-encoded url.
2766 String cookies = CookieManager.getInstance().getCookie(url);
2767
2768 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002769 values.put(Downloads.COLUMN_URI, uri.toString());
2770 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
2771 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
2772 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002773 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002774 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002775 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002776 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2777 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
2778 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
2779 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002780 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002781 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002782 }
2783 if (mimetype == null) {
2784 // We must have long pressed on a link or image to download it. We
2785 // are not sure of the mimetype in this case, so do a head request
2786 new FetchUrlMimeType(this).execute(values);
2787 } else {
2788 final Uri contentUri =
2789 getContentResolver().insert(Downloads.CONTENT_URI, values);
2790 viewDownloads(contentUri);
2791 }
2792
2793 }
2794
Grace Kloba22ac16e2009-10-07 18:00:23 -07002795 // -------------------------------------------------------------------------
2796
The Android Open Source Project0c908882009-03-03 19:32:16 -08002797 /**
2798 * Resets the lock icon. This method is called when we start a new load and
2799 * know the url to be loaded.
2800 */
2801 private void resetLockIcon(String url) {
2802 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002803 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002804 updateLockIconImage(LOCK_ICON_UNSECURE);
2805 }
2806
The Android Open Source Project0c908882009-03-03 19:32:16 -08002807 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002808 * Update the lock icon to correspond to our latest state.
2809 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002810 private void updateLockIconToLatest() {
2811 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002812 }
2813
2814 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002815 * Updates the lock-icon image in the title-bar.
2816 */
2817 private void updateLockIconImage(int lockIconType) {
2818 Drawable d = null;
2819 if (lockIconType == LOCK_ICON_SECURE) {
2820 d = mSecLockIcon;
2821 } else if (lockIconType == LOCK_ICON_MIXED) {
2822 d = mMixLockIcon;
2823 }
Leon Scroggins68579392009-09-15 15:31:54 -04002824 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002825 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002826 }
2827
2828 /**
2829 * Displays a page-info dialog.
2830 * @param tab The tab to show info about
2831 * @param fromShowSSLCertificateOnError The flag that indicates whether
2832 * this dialog was opened from the SSL-certificate-on-error dialog or
2833 * not. This is important, since we need to know whether to return to
2834 * the parent dialog or simply dismiss.
2835 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002836 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002837 final boolean fromShowSSLCertificateOnError) {
2838 final LayoutInflater factory = LayoutInflater
2839 .from(this);
2840
2841 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2842
2843 final WebView view = tab.getWebView();
2844
2845 String url = null;
2846 String title = null;
2847
2848 if (view == null) {
2849 url = tab.getUrl();
2850 title = tab.getTitle();
2851 } else if (view == mTabControl.getCurrentWebView()) {
2852 // Use the cached title and url if this is the current WebView
2853 url = mUrl;
2854 title = mTitle;
2855 } else {
2856 url = view.getUrl();
2857 title = view.getTitle();
2858 }
2859
2860 if (url == null) {
2861 url = "";
2862 }
2863 if (title == null) {
2864 title = "";
2865 }
2866
2867 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
2868 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
2869
2870 mPageInfoView = tab;
2871 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
2872
2873 AlertDialog.Builder alertDialogBuilder =
2874 new AlertDialog.Builder(this)
2875 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
2876 .setView(pageInfoView)
2877 .setPositiveButton(
2878 R.string.ok,
2879 new DialogInterface.OnClickListener() {
2880 public void onClick(DialogInterface dialog,
2881 int whichButton) {
2882 mPageInfoDialog = null;
2883 mPageInfoView = null;
2884 mPageInfoFromShowSSLCertificateOnError = null;
2885
2886 // if we came here from the SSL error dialog
2887 if (fromShowSSLCertificateOnError) {
2888 // go back to the SSL error dialog
2889 showSSLCertificateOnError(
2890 mSSLCertificateOnErrorView,
2891 mSSLCertificateOnErrorHandler,
2892 mSSLCertificateOnErrorError);
2893 }
2894 }
2895 })
2896 .setOnCancelListener(
2897 new DialogInterface.OnCancelListener() {
2898 public void onCancel(DialogInterface dialog) {
2899 mPageInfoDialog = null;
2900 mPageInfoView = null;
2901 mPageInfoFromShowSSLCertificateOnError = null;
2902
2903 // if we came here from the SSL error dialog
2904 if (fromShowSSLCertificateOnError) {
2905 // go back to the SSL error dialog
2906 showSSLCertificateOnError(
2907 mSSLCertificateOnErrorView,
2908 mSSLCertificateOnErrorHandler,
2909 mSSLCertificateOnErrorError);
2910 }
2911 }
2912 });
2913
2914 // if we have a main top-level page SSL certificate set or a certificate
2915 // error
2916 if (fromShowSSLCertificateOnError ||
2917 (view != null && view.getCertificate() != null)) {
2918 // add a 'View Certificate' button
2919 alertDialogBuilder.setNeutralButton(
2920 R.string.view_certificate,
2921 new DialogInterface.OnClickListener() {
2922 public void onClick(DialogInterface dialog,
2923 int whichButton) {
2924 mPageInfoDialog = null;
2925 mPageInfoView = null;
2926 mPageInfoFromShowSSLCertificateOnError = null;
2927
2928 // if we came here from the SSL error dialog
2929 if (fromShowSSLCertificateOnError) {
2930 // go back to the SSL error dialog
2931 showSSLCertificateOnError(
2932 mSSLCertificateOnErrorView,
2933 mSSLCertificateOnErrorHandler,
2934 mSSLCertificateOnErrorError);
2935 } else {
2936 // otherwise, display the top-most certificate from
2937 // the chain
2938 if (view.getCertificate() != null) {
2939 showSSLCertificate(tab);
2940 }
2941 }
2942 }
2943 });
2944 }
2945
2946 mPageInfoDialog = alertDialogBuilder.show();
2947 }
2948
2949 /**
2950 * Displays the main top-level page SSL certificate dialog
2951 * (accessible from the Page-Info dialog).
2952 * @param tab The tab to show certificate for.
2953 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002954 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002955 final View certificateView =
2956 inflateCertificateView(tab.getWebView().getCertificate());
2957 if (certificateView == null) {
2958 return;
2959 }
2960
2961 LayoutInflater factory = LayoutInflater.from(this);
2962
2963 final LinearLayout placeholder =
2964 (LinearLayout)certificateView.findViewById(R.id.placeholder);
2965
2966 LinearLayout ll = (LinearLayout) factory.inflate(
2967 R.layout.ssl_success, placeholder);
2968 ((TextView)ll.findViewById(R.id.success))
2969 .setText(R.string.ssl_certificate_is_valid);
2970
2971 mSSLCertificateView = tab;
2972 mSSLCertificateDialog =
2973 new AlertDialog.Builder(this)
2974 .setTitle(R.string.ssl_certificate).setIcon(
2975 R.drawable.ic_dialog_browser_certificate_secure)
2976 .setView(certificateView)
2977 .setPositiveButton(R.string.ok,
2978 new DialogInterface.OnClickListener() {
2979 public void onClick(DialogInterface dialog,
2980 int whichButton) {
2981 mSSLCertificateDialog = null;
2982 mSSLCertificateView = null;
2983
2984 showPageInfo(tab, false);
2985 }
2986 })
2987 .setOnCancelListener(
2988 new DialogInterface.OnCancelListener() {
2989 public void onCancel(DialogInterface dialog) {
2990 mSSLCertificateDialog = null;
2991 mSSLCertificateView = null;
2992
2993 showPageInfo(tab, false);
2994 }
2995 })
2996 .show();
2997 }
2998
2999 /**
3000 * Displays the SSL error certificate dialog.
3001 * @param view The target web-view.
3002 * @param handler The SSL error handler responsible for cancelling the
3003 * connection that resulted in an SSL error or proceeding per user request.
3004 * @param error The SSL error object.
3005 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003006 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003007 final WebView view, final SslErrorHandler handler, final SslError error) {
3008
3009 final View certificateView =
3010 inflateCertificateView(error.getCertificate());
3011 if (certificateView == null) {
3012 return;
3013 }
3014
3015 LayoutInflater factory = LayoutInflater.from(this);
3016
3017 final LinearLayout placeholder =
3018 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3019
3020 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3021 LinearLayout ll = (LinearLayout)factory
3022 .inflate(R.layout.ssl_warning, placeholder);
3023 ((TextView)ll.findViewById(R.id.warning))
3024 .setText(R.string.ssl_untrusted);
3025 }
3026
3027 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3028 LinearLayout ll = (LinearLayout)factory
3029 .inflate(R.layout.ssl_warning, placeholder);
3030 ((TextView)ll.findViewById(R.id.warning))
3031 .setText(R.string.ssl_mismatch);
3032 }
3033
3034 if (error.hasError(SslError.SSL_EXPIRED)) {
3035 LinearLayout ll = (LinearLayout)factory
3036 .inflate(R.layout.ssl_warning, placeholder);
3037 ((TextView)ll.findViewById(R.id.warning))
3038 .setText(R.string.ssl_expired);
3039 }
3040
3041 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3042 LinearLayout ll = (LinearLayout)factory
3043 .inflate(R.layout.ssl_warning, placeholder);
3044 ((TextView)ll.findViewById(R.id.warning))
3045 .setText(R.string.ssl_not_yet_valid);
3046 }
3047
3048 mSSLCertificateOnErrorHandler = handler;
3049 mSSLCertificateOnErrorView = view;
3050 mSSLCertificateOnErrorError = error;
3051 mSSLCertificateOnErrorDialog =
3052 new AlertDialog.Builder(this)
3053 .setTitle(R.string.ssl_certificate).setIcon(
3054 R.drawable.ic_dialog_browser_certificate_partially_secure)
3055 .setView(certificateView)
3056 .setPositiveButton(R.string.ok,
3057 new DialogInterface.OnClickListener() {
3058 public void onClick(DialogInterface dialog,
3059 int whichButton) {
3060 mSSLCertificateOnErrorDialog = null;
3061 mSSLCertificateOnErrorView = null;
3062 mSSLCertificateOnErrorHandler = null;
3063 mSSLCertificateOnErrorError = null;
3064
Grace Kloba22ac16e2009-10-07 18:00:23 -07003065 view.getWebViewClient().onReceivedSslError(
3066 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003067 }
3068 })
3069 .setNeutralButton(R.string.page_info_view,
3070 new DialogInterface.OnClickListener() {
3071 public void onClick(DialogInterface dialog,
3072 int whichButton) {
3073 mSSLCertificateOnErrorDialog = null;
3074
3075 // do not clear the dialog state: we will
3076 // need to show the dialog again once the
3077 // user is done exploring the page-info details
3078
3079 showPageInfo(mTabControl.getTabFromView(view),
3080 true);
3081 }
3082 })
3083 .setOnCancelListener(
3084 new DialogInterface.OnCancelListener() {
3085 public void onCancel(DialogInterface dialog) {
3086 mSSLCertificateOnErrorDialog = null;
3087 mSSLCertificateOnErrorView = null;
3088 mSSLCertificateOnErrorHandler = null;
3089 mSSLCertificateOnErrorError = null;
3090
Grace Kloba22ac16e2009-10-07 18:00:23 -07003091 view.getWebViewClient().onReceivedSslError(
3092 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003093 }
3094 })
3095 .show();
3096 }
3097
3098 /**
3099 * Inflates the SSL certificate view (helper method).
3100 * @param certificate The SSL certificate.
3101 * @return The resultant certificate view with issued-to, issued-by,
3102 * issued-on, expires-on, and possibly other fields set.
3103 * If the input certificate is null, returns null.
3104 */
3105 private View inflateCertificateView(SslCertificate certificate) {
3106 if (certificate == null) {
3107 return null;
3108 }
3109
3110 LayoutInflater factory = LayoutInflater.from(this);
3111
3112 View certificateView = factory.inflate(
3113 R.layout.ssl_certificate, null);
3114
3115 // issued to:
3116 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3117 if (issuedTo != null) {
3118 ((TextView) certificateView.findViewById(R.id.to_common))
3119 .setText(issuedTo.getCName());
3120 ((TextView) certificateView.findViewById(R.id.to_org))
3121 .setText(issuedTo.getOName());
3122 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3123 .setText(issuedTo.getUName());
3124 }
3125
3126 // issued by:
3127 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3128 if (issuedBy != null) {
3129 ((TextView) certificateView.findViewById(R.id.by_common))
3130 .setText(issuedBy.getCName());
3131 ((TextView) certificateView.findViewById(R.id.by_org))
3132 .setText(issuedBy.getOName());
3133 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3134 .setText(issuedBy.getUName());
3135 }
3136
3137 // issued on:
3138 String issuedOn = reformatCertificateDate(
3139 certificate.getValidNotBefore());
3140 ((TextView) certificateView.findViewById(R.id.issued_on))
3141 .setText(issuedOn);
3142
3143 // expires on:
3144 String expiresOn = reformatCertificateDate(
3145 certificate.getValidNotAfter());
3146 ((TextView) certificateView.findViewById(R.id.expires_on))
3147 .setText(expiresOn);
3148
3149 return certificateView;
3150 }
3151
3152 /**
3153 * Re-formats the certificate date (Date.toString()) string to
3154 * a properly localized date string.
3155 * @return Properly localized version of the certificate date string and
3156 * the original certificate date string if fails to localize.
3157 * If the original string is null, returns an empty string "".
3158 */
3159 private String reformatCertificateDate(String certificateDate) {
3160 String reformattedDate = null;
3161
3162 if (certificateDate != null) {
3163 Date date = null;
3164 try {
3165 date = java.text.DateFormat.getInstance().parse(certificateDate);
3166 } catch (ParseException e) {
3167 date = null;
3168 }
3169
3170 if (date != null) {
3171 reformattedDate =
3172 DateFormat.getDateFormat(this).format(date);
3173 }
3174 }
3175
3176 return reformattedDate != null ? reformattedDate :
3177 (certificateDate != null ? certificateDate : "");
3178 }
3179
3180 /**
3181 * Displays an http-authentication dialog.
3182 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003183 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003184 final String host, final String realm, final String title,
3185 final String name, final String password, int focusId) {
3186 LayoutInflater factory = LayoutInflater.from(this);
3187 final View v = factory
3188 .inflate(R.layout.http_authentication, null);
3189 if (name != null) {
3190 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3191 }
3192 if (password != null) {
3193 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3194 }
3195
3196 String titleText = title;
3197 if (titleText == null) {
3198 titleText = getText(R.string.sign_in_to).toString().replace(
3199 "%s1", host).replace("%s2", realm);
3200 }
3201
3202 mHttpAuthHandler = handler;
3203 AlertDialog dialog = new AlertDialog.Builder(this)
3204 .setTitle(titleText)
3205 .setIcon(android.R.drawable.ic_dialog_alert)
3206 .setView(v)
3207 .setPositiveButton(R.string.action,
3208 new DialogInterface.OnClickListener() {
3209 public void onClick(DialogInterface dialog,
3210 int whichButton) {
3211 String nm = ((EditText) v
3212 .findViewById(R.id.username_edit))
3213 .getText().toString();
3214 String pw = ((EditText) v
3215 .findViewById(R.id.password_edit))
3216 .getText().toString();
3217 BrowserActivity.this.setHttpAuthUsernamePassword
3218 (host, realm, nm, pw);
3219 handler.proceed(nm, pw);
3220 mHttpAuthenticationDialog = null;
3221 mHttpAuthHandler = null;
3222 }})
3223 .setNegativeButton(R.string.cancel,
3224 new DialogInterface.OnClickListener() {
3225 public void onClick(DialogInterface dialog,
3226 int whichButton) {
3227 handler.cancel();
3228 BrowserActivity.this.resetTitleAndRevertLockIcon();
3229 mHttpAuthenticationDialog = null;
3230 mHttpAuthHandler = null;
3231 }})
3232 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3233 public void onCancel(DialogInterface dialog) {
3234 handler.cancel();
3235 BrowserActivity.this.resetTitleAndRevertLockIcon();
3236 mHttpAuthenticationDialog = null;
3237 mHttpAuthHandler = null;
3238 }})
3239 .create();
3240 // Make the IME appear when the dialog is displayed if applicable.
3241 dialog.getWindow().setSoftInputMode(
3242 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3243 dialog.show();
3244 if (focusId != 0) {
3245 dialog.findViewById(focusId).requestFocus();
3246 } else {
3247 v.findViewById(R.id.username_edit).requestFocus();
3248 }
3249 mHttpAuthenticationDialog = dialog;
3250 }
3251
3252 public int getProgress() {
3253 WebView w = mTabControl.getCurrentWebView();
3254 if (w != null) {
3255 return w.getProgress();
3256 } else {
3257 return 100;
3258 }
3259 }
3260
3261 /**
3262 * Set HTTP authentication password.
3263 *
3264 * @param host The host for the password
3265 * @param realm The realm for the password
3266 * @param username The username for the password. If it is null, it means
3267 * password can't be saved.
3268 * @param password The password
3269 */
3270 public void setHttpAuthUsernamePassword(String host, String realm,
3271 String username,
3272 String password) {
3273 WebView w = mTabControl.getCurrentWebView();
3274 if (w != null) {
3275 w.setHttpAuthUsernamePassword(host, realm, username, password);
3276 }
3277 }
3278
3279 /**
3280 * connectivity manager says net has come or gone... inform the user
3281 * @param up true if net has come up, false if net has gone down
3282 */
3283 public void onNetworkToggle(boolean up) {
3284 if (up == mIsNetworkUp) {
3285 return;
3286 } else if (up) {
3287 mIsNetworkUp = true;
3288 if (mAlertDialog != null) {
3289 mAlertDialog.cancel();
3290 mAlertDialog = null;
3291 }
3292 } else {
3293 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003294 if (mInLoad) {
3295 createAndShowNetworkDialog();
3296 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003297 }
3298 WebView w = mTabControl.getCurrentWebView();
3299 if (w != null) {
3300 w.setNetworkAvailable(up);
3301 }
3302 }
3303
Grace Kloba22ac16e2009-10-07 18:00:23 -07003304 boolean isNetworkUp() {
3305 return mIsNetworkUp;
3306 }
3307
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003308 // This method shows the network dialog alerting the user that the net is
3309 // down. It will only show the dialog if mAlertDialog is null.
3310 private void createAndShowNetworkDialog() {
3311 if (mAlertDialog == null) {
3312 mAlertDialog = new AlertDialog.Builder(this)
3313 .setTitle(R.string.loadSuspendedTitle)
3314 .setMessage(R.string.loadSuspended)
3315 .setPositiveButton(R.string.ok, null)
3316 .show();
3317 }
3318 }
3319
The Android Open Source Project0c908882009-03-03 19:32:16 -08003320 @Override
3321 protected void onActivityResult(int requestCode, int resultCode,
3322 Intent intent) {
3323 switch (requestCode) {
3324 case COMBO_PAGE:
3325 if (resultCode == RESULT_OK && intent != null) {
3326 String data = intent.getAction();
3327 Bundle extras = intent.getExtras();
3328 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003329 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003330 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003331 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003332 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003333 dismissSubWindow(currentTab);
3334 if (data != null && data.length() != 0) {
3335 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003336 }
3337 }
3338 }
3339 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003340 // Choose a file from the file picker.
3341 case FILE_SELECTED:
3342 if (null == mUploadMessage) break;
3343 Uri result = intent == null || resultCode != RESULT_OK ? null
3344 : intent.getData();
3345 mUploadMessage.onReceiveValue(result);
3346 mUploadMessage = null;
3347 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003348 default:
3349 break;
3350 }
Leon Scroggins30444232009-09-04 18:36:20 -04003351 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003352 }
3353
3354 /*
3355 * This method is called as a result of the user selecting the options
3356 * menu to see the download window, or when a download changes state. It
3357 * shows the download window ontop of the current window.
3358 */
3359 /* package */ void viewDownloads(Uri downloadRecord) {
3360 Intent intent = new Intent(this,
3361 BrowserDownloadPage.class);
3362 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003363 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003364
3365 }
3366
Leon Scroggins160a7e72009-08-14 18:28:01 -04003367 /**
3368 * Open the Go page.
3369 * @param startWithHistory If true, open starting on the history tab.
3370 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003371 */
Leon Scroggins30444232009-09-04 18:36:20 -04003372 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003373 WebView current = mTabControl.getCurrentWebView();
3374 if (current == null) {
3375 return;
3376 }
3377 Intent intent = new Intent(this,
3378 CombinedBookmarkHistoryActivity.class);
3379 String title = current.getTitle();
3380 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003381 Bitmap thumbnail = createScreenshot(current);
3382
The Android Open Source Project0c908882009-03-03 19:32:16 -08003383 // Just in case the user opens bookmarks before a page finishes loading
3384 // so the current history item, and therefore the page, is null.
3385 if (null == url) {
3386 url = mLastEnteredUrl;
3387 // This can happen.
3388 if (null == url) {
3389 url = mSettings.getHomePage();
3390 }
3391 }
3392 // In case the web page has not yet received its associated title.
3393 if (title == null) {
3394 title = url;
3395 }
3396 intent.putExtra("title", title);
3397 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003398 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003399 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003400 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003401 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003402 if (startWithHistory) {
3403 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3404 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3405 }
3406 startActivityForResult(intent, COMBO_PAGE);
3407 }
3408
3409 // Called when loading from context menu or LOAD_URL message
3410 private void loadURL(WebView view, String url) {
3411 // In case the user enters nothing.
3412 if (url != null && url.length() != 0 && view != null) {
3413 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003414 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003415 view.loadUrl(url);
3416 }
3417 }
3418 }
3419
The Android Open Source Project0c908882009-03-03 19:32:16 -08003420 private String smartUrlFilter(Uri inUri) {
3421 if (inUri != null) {
3422 return smartUrlFilter(inUri.toString());
3423 }
3424 return null;
3425 }
3426
Feng Qianb34f87a2009-03-24 21:27:26 -07003427 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003428 "(?i)" + // switch on case insensitive matching
3429 "(" + // begin group for schema
3430 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003431 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003432 ")" +
3433 "(.*)" );
3434
3435 /**
3436 * Attempts to determine whether user input is a URL or search
3437 * terms. Anything with a space is passed to search.
3438 *
3439 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3440 * "Http://" converts to "http://"
3441 *
3442 * @return Original or modified URL
3443 *
3444 */
3445 String smartUrlFilter(String url) {
3446
3447 String inUrl = url.trim();
3448 boolean hasSpace = inUrl.indexOf(' ') != -1;
3449
3450 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3451 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003452 // force scheme to lowercase
3453 String scheme = matcher.group(1);
3454 String lcScheme = scheme.toLowerCase();
3455 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003456 inUrl = lcScheme + matcher.group(2);
3457 }
3458 if (hasSpace) {
3459 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003460 }
3461 return inUrl;
3462 }
3463 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003464 // FIXME: Is this the correct place to add to searches?
3465 // what if someone else calls this function?
3466 int shortcut = parseUrlShortcut(inUrl);
3467 if (shortcut != SHORTCUT_INVALID) {
3468 Browser.addSearchUrl(mResolver, inUrl);
3469 String query = inUrl.substring(2);
3470 switch (shortcut) {
3471 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003472 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003473 case SHORTCUT_WIKIPEDIA_SEARCH:
3474 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3475 case SHORTCUT_DICTIONARY_SEARCH:
3476 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3477 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003478 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003479 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003480 }
3481 }
3482 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003483 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003484 return URLUtil.guessUrl(inUrl);
3485 }
3486 }
3487
3488 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003489 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003490 }
3491
Ben Murdochbff2d602009-07-01 20:19:05 +01003492 /* package */ void setShouldShowErrorConsole(boolean flag) {
3493 if (flag == mShouldShowErrorConsole) {
3494 // Nothing to do.
3495 return;
3496 }
3497
3498 mShouldShowErrorConsole = flag;
3499
Grace Kloba22ac16e2009-10-07 18:00:23 -07003500 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3501 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003502
3503 if (flag) {
3504 // Setting the show state of the console will cause it's the layout to be inflated.
3505 if (errorConsole.numberOfErrors() > 0) {
3506 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3507 } else {
3508 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3509 }
3510
3511 // Now we can add it to the main view.
3512 mErrorConsoleContainer.addView(errorConsole,
3513 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
3514 ViewGroup.LayoutParams.WRAP_CONTENT));
3515 } else {
3516 mErrorConsoleContainer.removeView(errorConsole);
3517 }
3518
3519 }
3520
Grace Kloba22ac16e2009-10-07 18:00:23 -07003521 boolean shouldShowErrorConsole() {
3522 return mShouldShowErrorConsole;
3523 }
3524
Andrei Popescu163ab742009-10-20 17:58:23 +01003525 private void setStatusBarVisibility(boolean visible) {
3526 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3527 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3528 }
3529
Grace Klobaeb6eef42009-09-15 17:56:32 -07003530 final static int LOCK_ICON_UNSECURE = 0;
3531 final static int LOCK_ICON_SECURE = 1;
3532 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003533
The Android Open Source Project0c908882009-03-03 19:32:16 -08003534 private BrowserSettings mSettings;
3535 private TabControl mTabControl;
3536 private ContentResolver mResolver;
3537 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003538 private View mCustomView;
3539 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003540 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003541
3542 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3543 // view, we should rewrite this.
3544 private int mCurrentMenuState = 0;
3545 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003546 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003547 private static final int EMPTY_MENU = -1;
3548 private Menu mMenu;
3549
3550 private FindDialog mFindDialog;
3551 // Used to prevent chording to result in firing two shortcuts immediately
3552 // one after another. Fixes bug 1211714.
3553 boolean mCanChord;
3554
3555 private boolean mInLoad;
3556 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003557 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003558
The Android Open Source Project0c908882009-03-03 19:32:16 -08003559 private boolean mActivityInPause = true;
3560
3561 private boolean mMenuIsDown;
3562
The Android Open Source Project0c908882009-03-03 19:32:16 -08003563 private static boolean mInTrace;
3564
3565 // Performance probe
3566 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3567 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3568 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3569 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3570 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3571 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3572 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3573 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3574 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3575 };
3576
3577 private long mStart;
3578 private long mProcessStart;
3579 private long mUserStart;
3580 private long mSystemStart;
3581 private long mIdleStart;
3582 private long mIrqStart;
3583
3584 private long mUiStart;
3585
3586 private Drawable mMixLockIcon;
3587 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003588
3589 /* hold a ref so we can auto-cancel if necessary */
3590 private AlertDialog mAlertDialog;
3591
3592 // Wait for credentials before loading google.com
3593 private ProgressDialog mCredsDlg;
3594
3595 // The up-to-date URL and title (these can be different from those stored
3596 // in WebView, since it takes some time for the information in WebView to
3597 // get updated)
3598 private String mUrl;
3599 private String mTitle;
3600
3601 // As PageInfo has different style for landscape / portrait, we have
3602 // to re-open it when configuration changed
3603 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003604 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003605 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3606 // dialog, we should not just dismiss it, but should get back to the
3607 // SSL-certificate-on-error dialog. This flag is used to store this state
3608 private Boolean mPageInfoFromShowSSLCertificateOnError;
3609
3610 // as SSLCertificateOnError has different style for landscape / portrait,
3611 // we have to re-open it when configuration changed
3612 private AlertDialog mSSLCertificateOnErrorDialog;
3613 private WebView mSSLCertificateOnErrorView;
3614 private SslErrorHandler mSSLCertificateOnErrorHandler;
3615 private SslError mSSLCertificateOnErrorError;
3616
3617 // as SSLCertificate has different style for landscape / portrait, we
3618 // have to re-open it when configuration changed
3619 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003620 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003621
3622 // as HttpAuthentication has different style for landscape / portrait, we
3623 // have to re-open it when configuration changed
3624 private AlertDialog mHttpAuthenticationDialog;
3625 private HttpAuthHandler mHttpAuthHandler;
3626
3627 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3628 new FrameLayout.LayoutParams(
3629 ViewGroup.LayoutParams.FILL_PARENT,
3630 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003631 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3632 new FrameLayout.LayoutParams(
3633 ViewGroup.LayoutParams.FILL_PARENT,
3634 ViewGroup.LayoutParams.FILL_PARENT,
3635 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003636 // Google search
3637 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003638 // Wikipedia search
3639 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3640 // Dictionary search
3641 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3642 // Google Mobile Local search
3643 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3644
3645 final static String QUERY_PLACE_HOLDER = "%s";
3646
3647 // "source" parameter for Google search through search key
3648 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3649 // "source" parameter for Google search through goto menu
3650 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3651 // "source" parameter for Google search through simplily type
3652 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3653 // "source" parameter for Google search suggested by the browser
3654 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3655 // "source" parameter for Google search from unknown source
3656 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3657
3658 private final static String LOGTAG = "browser";
3659
The Android Open Source Project0c908882009-03-03 19:32:16 -08003660 private String mLastEnteredUrl;
3661
3662 private PowerManager.WakeLock mWakeLock;
3663 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3664
3665 private Toast mStopToast;
3666
Leon Scroggins68579392009-09-15 15:31:54 -04003667 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003668
Ben Murdochbff2d602009-07-01 20:19:05 +01003669 private LinearLayout mErrorConsoleContainer = null;
3670 private boolean mShouldShowErrorConsole = false;
3671
The Android Open Source Project0c908882009-03-03 19:32:16 -08003672 // As the ids are dynamically created, we can't guarantee that they will
3673 // be in sequence, so this static array maps ids to a window number.
3674 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3675 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3676 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3677 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3678
3679 // monitor platform changes
3680 private IntentFilter mNetworkStateChangedFilter;
3681 private BroadcastReceiver mNetworkStateIntentReceiver;
3682
Grace Klobab4da0ad2009-05-14 14:45:40 -07003683 private BroadcastReceiver mPackageInstallationReceiver;
3684
The Android Open Source Project0c908882009-03-03 19:32:16 -08003685 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003686 final static int COMBO_PAGE = 1;
3687 final static int DOWNLOAD_PAGE = 2;
3688 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003689 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003690
Andrei Popescu540035d2009-09-18 18:59:20 +01003691 // the default <video> poster
3692 private Bitmap mDefaultVideoPoster;
3693 // the video progress view
3694 private View mVideoProgressView;
3695
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003696 /**
3697 * A UrlData class to abstract how the content will be set to WebView.
3698 * This base class uses loadUrl to show the content.
3699 */
3700 private static class UrlData {
3701 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07003702 byte[] mPostData;
3703
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003704 UrlData(String url) {
3705 this.mUrl = url;
3706 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003707
3708 void setPostData(byte[] postData) {
3709 mPostData = postData;
3710 }
3711
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003712 boolean isEmpty() {
3713 return mUrl == null || mUrl.length() == 0;
3714 }
3715
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003716 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07003717 if (mPostData != null) {
3718 webView.postUrl(mUrl, mPostData);
3719 } else {
3720 webView.loadUrl(mUrl);
3721 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003722 }
3723 };
3724
3725 /**
3726 * A subclass of UrlData class that can display inlined content using
3727 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
3728 */
3729 private static class InlinedUrlData extends UrlData {
3730 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
3731 super(failUrl);
3732 mInlined = inlined;
3733 mMimeType = mimeType;
3734 mEncoding = encoding;
3735 }
3736 String mMimeType;
3737 String mInlined;
3738 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003739 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003740 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01003741 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003742 }
3743
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003744 @Override
3745 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003746 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
3747 }
3748 }
3749
Leon Scroggins1f005d32009-08-10 17:36:42 -04003750 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003751}