blob: 3cc9005ee75b2677000acc2c24e2f02fb8042ab8 [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;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000113import java.io.IOException;
114import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800115import java.net.MalformedURLException;
116import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700117import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800118import java.net.URL;
119import java.net.URLEncoder;
120import java.text.ParseException;
121import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800122import java.util.HashMap;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800123import java.util.regex.Matcher;
124import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800125
126public class BrowserActivity extends Activity
Grace Kloba5942df02009-09-18 11:48:29 -0700127 implements View.OnCreateContextMenuListener,
The Android Open Source Project0c908882009-03-03 19:32:16 -0800128 DownloadListener {
129
Dave Bort31a6d1c2009-04-13 15:56:49 -0700130 /* Define some aliases to make these debugging flags easier to refer to.
131 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
132 */
133 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
134 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
135 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
136
The Android Open Source Project0c908882009-03-03 19:32:16 -0800137 private IGoogleLoginService mGls = null;
138 private ServiceConnection mGlsConnection = null;
139
Satish Sampath565505b2009-05-29 15:37:27 +0100140 // These are single-character shortcuts for searching popular sources.
141 private static final int SHORTCUT_INVALID = 0;
142 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
143 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
144 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
145 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
146
The Android Open Source Project0c908882009-03-03 19:32:16 -0800147 private void setupHomePage() {
148 final Runnable getAccount = new Runnable() {
149 public void run() {
150 // Lower priority
151 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
152 // get the default home page
153 String homepage = mSettings.getHomePage();
154
155 try {
156 if (mGls == null) return;
157
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700158 if (!homepage.startsWith("http://www.google.")) return;
159 if (homepage.indexOf('?') == -1) return;
160
The Android Open Source Project0c908882009-03-03 19:32:16 -0800161 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
162 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
163
164 // three cases:
165 //
166 // hostedUser == googleUser
167 // The device has only a google account
168 //
169 // hostedUser != googleUser
170 // The device has a hosted account and a google account
171 //
172 // hostedUser != null, googleUser == null
173 // The device has only a hosted account (so far)
174
175 // developers might have no accounts at all
176 if (hostedUser == null) return;
177
178 if (googleUser == null || !hostedUser.equals(googleUser)) {
179 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700180 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800181 }
182 } catch (RemoteException ignore) {
183 // Login service died; carry on
184 } catch (RuntimeException ignore) {
185 // Login service died; carry on
186 } finally {
187 finish(homepage);
188 }
189 }
190
191 private void finish(final String homepage) {
192 mHandler.post(new Runnable() {
193 public void run() {
194 mSettings.setHomePage(BrowserActivity.this, homepage);
195 resumeAfterCredentials();
196
197 // as this is running in a separate thread,
198 // BrowserActivity's onDestroy() may have been called,
199 // which also calls unbindService().
200 if (mGlsConnection != null) {
201 // we no longer need to keep GLS open
202 unbindService(mGlsConnection);
203 mGlsConnection = null;
204 }
205 } });
206 } };
207
208 final boolean[] done = { false };
209
210 // Open a connection to the Google Login Service. The first
211 // time the connection is established, set up the homepage depending on
212 // the account in a background thread.
213 mGlsConnection = new ServiceConnection() {
214 public void onServiceConnected(ComponentName className, IBinder service) {
215 mGls = IGoogleLoginService.Stub.asInterface(service);
216 if (done[0] == false) {
217 done[0] = true;
218 Thread account = new Thread(getAccount);
219 account.setName("GLSAccount");
220 account.start();
221 }
222 }
223 public void onServiceDisconnected(ComponentName className) {
224 mGls = null;
225 }
226 };
227
228 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
229 mGlsConnection, Context.BIND_AUTO_CREATE);
230 }
231
Cary Clarka9771242009-08-11 16:42:26 -0400232 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800233 @Override
234 public Void doInBackground(File... files) {
235 if (files != null) {
236 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400237 if (!f.delete()) {
238 Log.e(LOGTAG, f.getPath() + " was not deleted");
239 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800240 }
241 }
242 return null;
243 }
244 }
245
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400246 /**
247 * This layout holds everything you see below the status bar, including the
248 * error console, the custom view container, and the webviews.
249 */
250 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400251
Grace Kloba22ac16e2009-10-07 18:00:23 -0700252 @Override
253 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700254 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800255 Log.v(LOGTAG, this + " onStart");
256 }
257 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800258 // test the browser in OpenGL
259 // requestWindowFeature(Window.FEATURE_OPENGL);
260
261 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
262
263 mResolver = getContentResolver();
264
Grace Kloba0923d692009-09-23 21:37:25 -0700265 // If this was a web search request, pass it on to the default web
266 // search provider and finish this activity.
267 if (handleWebSearchIntent(getIntent())) {
268 finish();
269 return;
270 }
271
The Android Open Source Project0c908882009-03-03 19:32:16 -0800272 mSecLockIcon = Resources.getSystem().getDrawable(
273 android.R.drawable.ic_secure);
274 mMixLockIcon = Resources.getSystem().getDrawable(
275 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800276
Leon Scroggins81db3662009-06-04 17:45:11 -0400277 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
278 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400279 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
280 .inflate(R.layout.custom_screen, null);
281 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
282 R.id.main_content);
283 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
284 .findViewById(R.id.error_console);
285 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
286 .findViewById(R.id.fullscreen_custom_content);
287 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400288 mTitleBar = new TitleBar(this);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400289 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800290
291 // Create the tab control and our initial tab
292 mTabControl = new TabControl(this);
293
294 // Open the icon database and retain all the bookmark urls for favicons
295 retainIconsOnStartup();
296
297 // Keep a settings instance handy.
298 mSettings = BrowserSettings.getInstance();
299 mSettings.setTabControl(mTabControl);
300 mSettings.loadFromDb(this);
301
302 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
303 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
304
Grace Klobaa34f6862009-07-31 16:28:17 -0700305 /* enables registration for changes in network status from
306 http stack */
307 mNetworkStateChangedFilter = new IntentFilter();
308 mNetworkStateChangedFilter.addAction(
309 ConnectivityManager.CONNECTIVITY_ACTION);
310 mNetworkStateIntentReceiver = new BroadcastReceiver() {
311 @Override
312 public void onReceive(Context context, Intent intent) {
313 if (intent.getAction().equals(
314 ConnectivityManager.CONNECTIVITY_ACTION)) {
Robert Greenwalt7d899d62009-10-23 10:33:48 -0700315 boolean noConnectivity = intent.getBooleanExtra(
316 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
317 onNetworkToggle(!noConnectivity);
Grace Klobaa34f6862009-07-31 16:28:17 -0700318 }
319 }
320 };
321
Grace Kloba615c6c92009-08-03 10:22:44 -0700322 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
323 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
324 filter.addDataScheme("package");
325 mPackageInstallationReceiver = new BroadcastReceiver() {
326 @Override
327 public void onReceive(Context context, Intent intent) {
328 final String action = intent.getAction();
329 final String packageName = intent.getData()
330 .getSchemeSpecificPart();
331 final boolean replacing = intent.getBooleanExtra(
332 Intent.EXTRA_REPLACING, false);
333 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
334 // if it is replacing, refreshPlugins() when adding
335 return;
336 }
337 PackageManager pm = BrowserActivity.this.getPackageManager();
338 PackageInfo pkgInfo = null;
339 try {
340 pkgInfo = pm.getPackageInfo(packageName,
341 PackageManager.GET_PERMISSIONS);
342 } catch (PackageManager.NameNotFoundException e) {
343 return;
344 }
345 if (pkgInfo != null) {
346 String permissions[] = pkgInfo.requestedPermissions;
347 if (permissions == null) {
348 return;
349 }
350 boolean permissionOk = false;
351 for (String permit : permissions) {
352 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
353 permissionOk = true;
354 break;
355 }
356 }
357 if (permissionOk) {
358 PluginManager.getInstance(BrowserActivity.this)
359 .refreshPlugins(
360 Intent.ACTION_PACKAGE_ADDED
361 .equals(action));
362 }
363 }
364 }
365 };
366 registerReceiver(mPackageInstallationReceiver, filter);
367
The Android Open Source Project0c908882009-03-03 19:32:16 -0800368 if (!mTabControl.restoreState(icicle)) {
369 // clear up the thumbnail directory if we can't restore the state as
370 // none of the files in the directory are referenced any more.
371 new ClearThumbnails().execute(
372 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700373 // there is no quit on Android. But if we can't restore the state,
374 // we can treat it as a new Browser, remove the old session cookies.
375 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800376 final Intent intent = getIntent();
377 final Bundle extra = intent.getExtras();
378 // Create an initial tab.
379 // If the intent is ACTION_VIEW and data is not null, the Browser is
380 // invoked to view the content by another application. In this case,
381 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700382 UrlData urlData = getUrlDataFromIntent(intent);
383
Grace Kloba22ac16e2009-10-07 18:00:23 -0700384 final Tab t = mTabControl.createNewTab(
The Android Open Source Project0c908882009-03-03 19:32:16 -0800385 Intent.ACTION_VIEW.equals(intent.getAction()) &&
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700386 intent.getData() != null,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700387 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800388 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800389 attachTabToContentView(t);
390 WebView webView = t.getWebView();
391 if (extra != null) {
392 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
393 if (scale > 0 && scale <= 1000) {
394 webView.setInitialScale(scale);
395 }
396 }
397 // If we are not restoring from an icicle, then there is a high
398 // likely hood this is the first run. So, check to see if the
399 // homepage needs to be configured and copy any plugins from our
400 // asset directory to the data partition.
401 if ((extra == null || !extra.getBoolean("testing"))
402 && !mSettings.isLoginInitialized()) {
403 setupHomePage();
404 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800405
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700406 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400407 if (mSettings.isLoginInitialized()) {
408 webView.loadUrl(mSettings.getHomePage());
409 } else {
410 waitForCredentials();
411 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800412 } else {
Grace Kloba81678d92009-06-30 07:09:56 -0700413 if (extra != null) {
414 urlData.setPostData(extra
415 .getByteArray(Browser.EXTRA_POST_DATA));
416 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700417 urlData.loadIn(webView);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800418 }
419 } else {
420 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400421 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800422 attachTabToContentView(mTabControl.getCurrentTab());
423 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700424
Feng Qianb3c02da2009-06-29 15:58:08 -0700425 // Read JavaScript flags if it exists.
426 String jsFlags = mSettings.getJsFlags();
427 if (jsFlags.trim().length() != 0) {
428 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
429 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800430 }
431
432 @Override
433 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700434 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800435 // When a tab is closed on exit, the current tab index is set to -1.
436 // Reset before proceed as Browser requires the current tab to be set.
437 if (current == null) {
438 // Try to reset the tab in case the index was incorrect.
439 current = mTabControl.getTab(0);
440 if (current == null) {
441 // No tabs at all so just ignore this intent.
442 return;
443 }
444 mTabControl.setCurrentTab(current);
445 attachTabToContentView(current);
446 resetTitleAndIcon(current.getWebView());
447 }
448 final String action = intent.getAction();
449 final int flags = intent.getFlags();
450 if (Intent.ACTION_MAIN.equals(action) ||
451 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
452 // just resume the browser
453 return;
454 }
455 if (Intent.ACTION_VIEW.equals(action)
456 || Intent.ACTION_SEARCH.equals(action)
457 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
458 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100459 // If this was a search request (e.g. search query directly typed into the address bar),
460 // pass it on to the default web search provider.
461 if (handleWebSearchIntent(intent)) {
462 return;
463 }
464
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700465 UrlData urlData = getUrlDataFromIntent(intent);
466 if (urlData.isEmpty()) {
467 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800468 }
Grace Kloba81678d92009-06-30 07:09:56 -0700469 urlData.setPostData(intent
470 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700471
Grace Klobacc634032009-07-28 15:58:19 -0700472 final String appId = intent
473 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
474 if (Intent.ACTION_VIEW.equals(action)
475 && !getPackageName().equals(appId)
476 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700477 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700478 if (appTab != null) {
479 Log.i(LOGTAG, "Reusing tab for " + appId);
480 // Dismiss the subwindow if applicable.
481 dismissSubWindow(appTab);
482 // Since we might kill the WebView, remove it from the
483 // content view first.
484 removeTabFromContentView(appTab);
485 // Recreate the main WebView after destroying the old one.
486 // If the WebView has the same original url and is on that
487 // page, it can be reused.
488 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700489 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100490
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700491 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400492 switchToTab(mTabControl.getTabIndex(appTab));
493 if (needsLoad) {
494 urlData.loadIn(appTab.getWebView());
495 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700496 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400497 // If the tab was the current tab, we have to attach
498 // it to the view system again.
499 attachTabToContentView(appTab);
500 if (needsLoad) {
501 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700502 }
503 }
504 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400505 } else {
506 // No matching application tab, try to find a regular tab
507 // with a matching url.
508 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400509 if (appTab != null) {
510 if (current != appTab) {
511 switchToTab(mTabControl.getTabIndex(appTab));
512 }
513 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400514 } else {
515 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
516 // will be opened in a new tab unless we have reached
517 // MAX_TABS. Then the url will be opened in the current
518 // tab. If a new tab is created, it will have "true" for
519 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400520 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400521 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700522 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800523 } else {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700524 if ("about:debug".equals(urlData.mUrl)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800525 mSettings.toggleDebugSettings();
526 return;
527 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400528 // Get rid of the subwindow if it exists
529 dismissSubWindow(current);
530 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800531 }
532 }
533 }
534
Satish Sampath565505b2009-05-29 15:37:27 +0100535 private int parseUrlShortcut(String url) {
536 if (url == null) return SHORTCUT_INVALID;
537
538 // FIXME: quick search, need to be customized by setting
539 if (url.length() > 2 && url.charAt(1) == ' ') {
540 switch (url.charAt(0)) {
541 case 'g': return SHORTCUT_GOOGLE_SEARCH;
542 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
543 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
544 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
545 }
546 }
547 return SHORTCUT_INVALID;
548 }
549
550 /**
551 * Launches the default web search activity with the query parameters if the given intent's data
552 * are identified as plain search terms and not URLs/shortcuts.
553 * @return true if the intent was handled and web search activity was launched, false if not.
554 */
555 private boolean handleWebSearchIntent(Intent intent) {
556 if (intent == null) return false;
557
558 String url = null;
559 final String action = intent.getAction();
560 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700561 Uri data = intent.getData();
562 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100563 } else if (Intent.ACTION_SEARCH.equals(action)
564 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
565 || Intent.ACTION_WEB_SEARCH.equals(action)) {
566 url = intent.getStringExtra(SearchManager.QUERY);
567 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100568 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
569 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100570 }
571
572 /**
573 * Launches the default web search activity with the query parameters if the given url string
574 * was identified as plain search terms and not URL/shortcut.
575 * @return true if the request was handled and web search activity was launched, false if not.
576 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100577 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100578 if (inUrl == null) return false;
579
580 // In general, we shouldn't modify URL from Intent.
581 // But currently, we get the user-typed URL from search box as well.
582 String url = fixUrl(inUrl).trim();
583
584 // URLs and site specific search shortcuts are handled by the regular flow of control, so
585 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800586 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100587 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100588 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
589 return false;
590 }
591
592 Browser.updateVisitedHistory(mResolver, url, false);
593 Browser.addSearchUrl(mResolver, url);
594
595 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
596 intent.addCategory(Intent.CATEGORY_DEFAULT);
597 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100598 if (appData != null) {
599 intent.putExtra(SearchManager.APP_DATA, appData);
600 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100601 if (extraData != null) {
602 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
603 }
Grace Klobacc634032009-07-28 15:58:19 -0700604 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100605 startActivity(intent);
606
607 return true;
608 }
609
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700610 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800611 String url = null;
612 if (intent != null) {
613 final String action = intent.getAction();
614 if (Intent.ACTION_VIEW.equals(action)) {
615 url = smartUrlFilter(intent.getData());
616 if (url != null && url.startsWith("content:")) {
617 /* Append mimetype so webview knows how to display */
618 String mimeType = intent.resolveType(getContentResolver());
619 if (mimeType != null) {
620 url += "?" + mimeType;
621 }
622 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700623 if ("inline:".equals(url)) {
624 return new InlinedUrlData(
625 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
626 intent.getType(),
627 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
628 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
629 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800630 } else if (Intent.ACTION_SEARCH.equals(action)
631 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
632 || Intent.ACTION_WEB_SEARCH.equals(action)) {
633 url = intent.getStringExtra(SearchManager.QUERY);
634 if (url != null) {
635 mLastEnteredUrl = url;
636 // Don't add Urls, just search terms.
637 // Urls will get added when the page is loaded.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800638 if (!Patterns.WEB_URL.matcher(url).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800639 Browser.updateVisitedHistory(mResolver, url, false);
640 }
641 // In general, we shouldn't modify URL from Intent.
642 // But currently, we get the user-typed URL from search box as well.
643 url = fixUrl(url);
644 url = smartUrlFilter(url);
645 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
646 if (url.contains(searchSource)) {
647 String source = null;
648 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
649 if (appData != null) {
650 source = appData.getString(SearchManager.SOURCE);
651 }
652 if (TextUtils.isEmpty(source)) {
653 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
654 }
655 url = url.replace(searchSource, "&source=android-"+source+"&");
656 }
657 }
658 }
659 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700660 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800661 }
662
663 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400664 // FIXME: Converting the url to lower case
665 // duplicates functionality in smartUrlFilter().
666 // However, changing all current callers of fixUrl to
667 // call smartUrlFilter in addition may have unwanted
668 // consequences, and is deferred for now.
669 int colon = inUrl.indexOf(':');
670 boolean allLower = true;
671 for (int index = 0; index < colon; index++) {
672 char ch = inUrl.charAt(index);
673 if (!Character.isLetter(ch)) {
674 break;
675 }
676 allLower &= Character.isLowerCase(ch);
677 if (index == colon - 1 && !allLower) {
678 inUrl = inUrl.substring(0, colon).toLowerCase()
679 + inUrl.substring(colon);
680 }
681 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800682 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
683 return inUrl;
684 if (inUrl.startsWith("http:") ||
685 inUrl.startsWith("https:")) {
686 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
687 inUrl = inUrl.replaceFirst("/", "//");
688 } else inUrl = inUrl.replaceFirst(":", "://");
689 }
690 return inUrl;
691 }
692
Grace Kloba22ac16e2009-10-07 18:00:23 -0700693 @Override
694 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800695 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700696 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800697 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
698 }
699
700 if (!mActivityInPause) {
701 Log.e(LOGTAG, "BrowserActivity is already resumed.");
702 return;
703 }
704
Mike Reed7bfa63b2009-05-28 11:08:32 -0400705 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800706 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400707 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800708
709 if (mWakeLock.isHeld()) {
710 mHandler.removeMessages(RELEASE_WAKELOCK);
711 mWakeLock.release();
712 }
713
714 if (mCredsDlg != null) {
715 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
716 // In case credential request never comes back
717 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
718 }
719 }
720
721 registerReceiver(mNetworkStateIntentReceiver,
722 mNetworkStateChangedFilter);
723 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800724 }
725
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400726 /**
727 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400728 * would change its appearance, use a different TitleBar to show overlayed
729 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400730 */
731 private TitleBar mFakeTitleBar;
732
733 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400734 * Holder for the fake title bar. It will have a foreground shadow, as well
735 * as a white background, so the fake title bar looks like the real one.
736 */
737 private ViewGroup mFakeTitleBarHolder;
738
739 /**
740 * Layout parameters for the fake title bar within mFakeTitleBarHolder
741 */
742 private FrameLayout.LayoutParams mFakeTitleBarParams
743 = new FrameLayout.LayoutParams(
Leon Scrogginsc01e4a82009-09-16 14:41:00 -0400744 ViewGroup.LayoutParams.FILL_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400745 ViewGroup.LayoutParams.WRAP_CONTENT);
746 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400747 * Keeps track of whether the options menu is open. This is important in
748 * determining whether to show or hide the title bar overlay.
749 */
750 private boolean mOptionsMenuOpen;
751
752 /**
753 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
754 * of whether the configuration has changed. The first onMenuOpened call
755 * after a configuration change is simply a reopening of the same menu
756 * (i.e. mIconView did not change).
757 */
758 private boolean mConfigChanged;
759
760 /**
761 * Whether or not the options menu is in its smaller, icon menu form. When
762 * true, we want the title bar overlay to be up. When false, we do not.
763 * Only meaningful if mOptionsMenuOpen is true.
764 */
765 private boolean mIconView;
766
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400767 @Override
768 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400769 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
770 if (mOptionsMenuOpen) {
771 if (mConfigChanged) {
772 // We do not need to make any changes to the state of the
773 // title bar, since the only thing that happened was a
774 // change in orientation
775 mConfigChanged = false;
776 } else {
777 if (mIconView) {
778 // Switching the menu to expanded view, so hide the
779 // title bar.
780 hideFakeTitleBar();
781 mIconView = false;
782 } else {
783 // Switching the menu back to icon view, so show the
784 // title bar once again.
785 showFakeTitleBar();
786 mIconView = true;
787 }
788 }
789 } else {
790 // The options menu is closed, so open it, and show the title
791 showFakeTitleBar();
792 mOptionsMenuOpen = true;
793 mConfigChanged = false;
794 mIconView = true;
795 }
796 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400797 return true;
798 }
799
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400800 /**
801 * Special class used exclusively for the shadow drawn underneath the fake
802 * title bar. The shadow does not need to be drawn if the WebView
803 * underneath is scrolled to the top, because it will draw directly on top
804 * of the embedded shadow.
805 */
806 private static class Shadow extends View {
807 private WebView mWebView;
808
809 public Shadow(Context context, AttributeSet attrs) {
810 super(context, attrs);
811 }
812
813 public void setWebView(WebView view) {
814 mWebView = view;
815 }
816
817 @Override
818 public void draw(Canvas canvas) {
819 // In general onDraw is the method to override, but we care about
820 // whether or not the background gets drawn, which happens in draw()
821 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
822 super.draw(canvas);
823 }
824 // Need to invalidate so that if the scroll position changes, we
825 // still draw as appropriate.
826 invalidate();
827 }
828 }
829
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400830 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400831 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400832 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400833 && !mActivityInPause && decor != null
834 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400835 Rect visRect = new Rect();
836 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
837 if (LOGD_ENABLED) {
838 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
839 }
840 return;
841 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400842
843 WindowManager manager
844 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
845
846 // Add the title bar to the window manager so it can receive touches
847 // while the menu is up
848 WindowManager.LayoutParams params
849 = new WindowManager.LayoutParams(
850 ViewGroup.LayoutParams.FILL_PARENT,
851 ViewGroup.LayoutParams.WRAP_CONTENT,
852 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
853 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400854 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400855 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400856 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400857 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400858 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400859 // XXX : Without providing an offset, the fake title bar will be
860 // placed underneath the status bar. Use the global visible rect
861 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400862 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400863 // Add a holder for the title bar. It also holds a shadow to show
864 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400865 if (mFakeTitleBarHolder == null) {
866 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
867 .inflate(R.layout.title_bar_bg, null);
868 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400869 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
870 R.id.shadow);
871 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400872 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400873 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400874 }
875 }
876
877 @Override
878 public void onOptionsMenuClosed(Menu menu) {
879 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400880 if (!mInLoad) {
881 hideFakeTitleBar();
882 } else if (!mIconView) {
883 // The page is currently loading, and we are in expanded mode, so
884 // we were not showing the menu. Show it once again. It will be
885 // removed when the page finishes.
886 showFakeTitleBar();
887 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400888 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700889
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400890 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400891 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400892 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
893 mFakeTitleBarHolder.getLayoutParams();
894 WebView mainView = mTabControl.getCurrentWebView();
895 // Although we decided whether or not to animate based on the current
896 // scroll position, the scroll position may have changed since the
897 // fake title bar was displayed. Make sure it has the appropriate
898 // animation/lack thereof before removing.
899 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400900 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400901 WindowManager manager
902 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -0400903 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400904 mFakeTitleBarHolder.removeView(mFakeTitleBar);
905 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400906 }
907
The Android Open Source Project0c908882009-03-03 19:32:16 -0800908 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400909 * Special method for the fake title bar to call when displaying its context
910 * menu, since it is in its own Window, and its parent does not show a
911 * context menu.
912 */
913 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400914 if (null == mTitleBar.getParent()) {
915 return;
916 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400917 openContextMenu(mTitleBar);
918 }
919
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400920 @Override
921 public void onContextMenuClosed(Menu menu) {
922 super.onContextMenuClosed(menu);
923 if (mInLoad) {
924 showFakeTitleBar();
925 }
926 }
927
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400928 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800929 * onSaveInstanceState(Bundle map)
930 * onSaveInstanceState is called right before onStop(). The map contains
931 * the saved state.
932 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700933 @Override
934 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700935 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800936 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
937 }
938 // the default implementation requires each view to have an id. As the
939 // browser handles the state itself and it doesn't use id for the views,
940 // don't call the default implementation. Otherwise it will trigger the
941 // warning like this, "couldn't save which view has focus because the
942 // focused view XXX has no id".
943
944 // Save all the tabs
945 mTabControl.saveState(outState);
946 }
947
Grace Kloba22ac16e2009-10-07 18:00:23 -0700948 @Override
949 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800950 super.onPause();
951
952 if (mActivityInPause) {
953 Log.e(LOGTAG, "BrowserActivity is already paused.");
954 return;
955 }
956
Mike Reed7bfa63b2009-05-28 11:08:32 -0400957 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800958 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400959 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800960 mWakeLock.acquire();
961 mHandler.sendMessageDelayed(mHandler
962 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
963 }
964
965 // Clear the credentials toast if it is up
966 if (mCredsDlg != null && mCredsDlg.isShowing()) {
967 mCredsDlg.dismiss();
968 }
969 mCredsDlg = null;
970
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400971 // FIXME: This removes the active tabs page and resets the menu to
972 // MAIN_MENU. A better solution might be to do this work in onNewIntent
973 // but then we would need to save it in onSaveInstanceState and restore
974 // it in onCreate/onRestoreInstanceState
975 if (mActiveTabsPage != null) {
976 removeActiveTabPage(true);
977 }
978
The Android Open Source Project0c908882009-03-03 19:32:16 -0800979 cancelStopToast();
980
981 // unregister network state listener
982 unregisterReceiver(mNetworkStateIntentReceiver);
983 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800984 }
985
Grace Kloba22ac16e2009-10-07 18:00:23 -0700986 @Override
987 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700988 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800989 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
990 }
991 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700992
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400993 if (mUploadMessage != null) {
994 mUploadMessage.onReceiveValue(null);
995 mUploadMessage = null;
996 }
997
Grace Kloba0923d692009-09-23 21:37:25 -0700998 if (mTabControl == null) return;
999
Grace Kloba1fc98a32009-10-21 13:23:08 -07001000 // Remove the fake title bar if it is there
1001 hideFakeTitleBar();
1002
The Android Open Source Project0c908882009-03-03 19:32:16 -08001003 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001004 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001005 if (t != null) {
1006 dismissSubWindow(t);
1007 removeTabFromContentView(t);
1008 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001009 // Destroy all the tabs
1010 mTabControl.destroy();
1011 WebIconDatabase.getInstance().close();
1012 if (mGlsConnection != null) {
1013 unbindService(mGlsConnection);
1014 mGlsConnection = null;
1015 }
1016
Grace Klobab4da0ad2009-05-14 14:45:40 -07001017 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001018 }
1019
1020 @Override
1021 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001022 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001023 super.onConfigurationChanged(newConfig);
1024
1025 if (mPageInfoDialog != null) {
1026 mPageInfoDialog.dismiss();
1027 showPageInfo(
1028 mPageInfoView,
1029 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1030 }
1031 if (mSSLCertificateDialog != null) {
1032 mSSLCertificateDialog.dismiss();
1033 showSSLCertificate(
1034 mSSLCertificateView);
1035 }
1036 if (mSSLCertificateOnErrorDialog != null) {
1037 mSSLCertificateOnErrorDialog.dismiss();
1038 showSSLCertificateOnError(
1039 mSSLCertificateOnErrorView,
1040 mSSLCertificateOnErrorHandler,
1041 mSSLCertificateOnErrorError);
1042 }
1043 if (mHttpAuthenticationDialog != null) {
1044 String title = ((TextView) mHttpAuthenticationDialog
1045 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1046 .toString();
1047 String name = ((TextView) mHttpAuthenticationDialog
1048 .findViewById(R.id.username_edit)).getText().toString();
1049 String password = ((TextView) mHttpAuthenticationDialog
1050 .findViewById(R.id.password_edit)).getText().toString();
1051 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1052 .getId();
1053 mHttpAuthenticationDialog.dismiss();
1054 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1055 name, password, focusId);
1056 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001057 }
1058
Grace Kloba22ac16e2009-10-07 18:00:23 -07001059 @Override
1060 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001061 super.onLowMemory();
1062 mTabControl.freeMemory();
1063 }
1064
Mike Reed7bfa63b2009-05-28 11:08:32 -04001065 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001066 Tab tab = mTabControl.getCurrentTab();
1067 boolean inLoad = tab.inLoad();
1068 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001069 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001070 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001071 if (w != null) {
1072 w.resumeTimers();
1073 }
1074 return true;
1075 } else {
1076 return false;
1077 }
1078 }
1079
Mike Reed7bfa63b2009-05-28 11:08:32 -04001080 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001081 Tab tab = mTabControl.getCurrentTab();
1082 boolean inLoad = tab.inLoad();
1083 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001084 CookieSyncManager.getInstance().stopSync();
1085 WebView w = mTabControl.getCurrentWebView();
1086 if (w != null) {
1087 w.pauseTimers();
1088 }
1089 return true;
1090 } else {
1091 return false;
1092 }
1093 }
1094
Leon Scroggins1f005d32009-08-10 17:36:42 -04001095 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001096 /*
1097 * This function is called when we are launching for the first time. We
1098 * are waiting for the login credentials before loading Google home
1099 * pages. This way the user will be logged in straight away.
1100 */
1101 private void waitForCredentials() {
1102 // Show a toast
1103 mCredsDlg = new ProgressDialog(this);
1104 mCredsDlg.setIndeterminate(true);
1105 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1106 // If the user cancels the operation, then cancel the Google
1107 // Credentials request.
1108 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1109 mCredsDlg.show();
1110
1111 // We set a timeout for the retrieval of credentials in onResume()
1112 // as that is when we have freed up some CPU time to get
1113 // the login credentials.
1114 }
1115
1116 /*
1117 * If we have received the credentials or we have timed out and we are
1118 * showing the credentials dialog, then it is time to move on.
1119 */
1120 private void resumeAfterCredentials() {
1121 if (mCredsDlg == null) {
1122 return;
1123 }
1124
1125 // Clear the toast
1126 if (mCredsDlg.isShowing()) {
1127 mCredsDlg.dismiss();
1128 }
1129 mCredsDlg = null;
1130
1131 // Clear any pending timeout
1132 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1133
1134 // Load the page
1135 WebView w = mTabControl.getCurrentWebView();
1136 if (w != null) {
1137 w.loadUrl(mSettings.getHomePage());
1138 }
1139
1140 // Update the settings, need to do this last as it can take a moment
1141 // to persist the settings. In the mean time we could be loading
1142 // content.
1143 mSettings.setLoginInitialized(this);
1144 }
1145
1146 // Open the icon database and retain all the icons for visited sites.
1147 private void retainIconsOnStartup() {
1148 final WebIconDatabase db = WebIconDatabase.getInstance();
1149 db.open(getDir("icons", 0).getPath());
1150 try {
1151 Cursor c = Browser.getAllBookmarks(mResolver);
1152 if (!c.moveToFirst()) {
1153 c.deactivate();
1154 return;
1155 }
1156 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1157 do {
1158 String url = c.getString(urlIndex);
1159 db.retainIconForPageUrl(url);
1160 } while (c.moveToNext());
1161 c.deactivate();
1162 } catch (IllegalStateException e) {
1163 Log.e(LOGTAG, "retainIconsOnStartup", e);
1164 }
1165 }
1166
1167 // Helper method for getting the top window.
1168 WebView getTopWindow() {
1169 return mTabControl.getCurrentTopWebView();
1170 }
1171
Grace Kloba22ac16e2009-10-07 18:00:23 -07001172 TabControl getTabControl() {
1173 return mTabControl;
1174 }
1175
The Android Open Source Project0c908882009-03-03 19:32:16 -08001176 @Override
1177 public boolean onCreateOptionsMenu(Menu menu) {
1178 super.onCreateOptionsMenu(menu);
1179
1180 MenuInflater inflater = getMenuInflater();
1181 inflater.inflate(R.menu.browser, menu);
1182 mMenu = menu;
1183 updateInLoadMenuItems();
1184 return true;
1185 }
1186
1187 /**
1188 * As the menu can be open when loading state changes
1189 * we must manually update the state of the stop/reload menu
1190 * item
1191 */
1192 private void updateInLoadMenuItems() {
1193 if (mMenu == null) {
1194 return;
1195 }
1196 MenuItem src = mInLoad ?
1197 mMenu.findItem(R.id.stop_menu_id):
1198 mMenu.findItem(R.id.reload_menu_id);
1199 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1200 dest.setIcon(src.getIcon());
1201 dest.setTitle(src.getTitle());
1202 }
1203
1204 @Override
1205 public boolean onContextItemSelected(MenuItem item) {
1206 // chording is not an issue with context menus, but we use the same
1207 // options selector, so set mCanChord to true so we can access them.
1208 mCanChord = true;
1209 int id = item.getItemId();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001210 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001211 // For the context menu from the title bar
1212 case R.id.title_bar_share_page_url:
1213 case R.id.title_bar_copy_page_url:
1214 WebView mainView = mTabControl.getCurrentWebView();
1215 if (null == mainView) {
1216 return false;
1217 }
1218 if (id == R.id.title_bar_share_page_url) {
1219 Browser.sendString(this, mainView.getUrl());
1220 } else {
1221 copy(mainView.getUrl());
1222 }
1223 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001224 // -- Browser context menu
1225 case R.id.open_context_menu_id:
1226 case R.id.open_newtab_context_menu_id:
1227 case R.id.bookmark_context_menu_id:
1228 case R.id.save_link_context_menu_id:
1229 case R.id.share_link_context_menu_id:
1230 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001231 final WebView webView = getTopWindow();
1232 if (null == webView) {
1233 return false;
1234 }
1235 final HashMap hrefMap = new HashMap();
1236 hrefMap.put("webview", webView);
1237 final Message msg = mHandler.obtainMessage(
1238 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001239 webView.requestFocusNodeHref(msg);
1240 break;
1241
1242 default:
1243 // For other context menus
1244 return onOptionsItemSelected(item);
1245 }
1246 mCanChord = false;
1247 return true;
1248 }
1249
1250 private Bundle createGoogleSearchSourceBundle(String source) {
1251 Bundle bundle = new Bundle();
1252 bundle.putString(SearchManager.SOURCE, source);
1253 return bundle;
1254 }
1255
1256 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001257 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001258 */
1259 @Override
1260 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001261 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001262 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001263 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001264 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001265 return true;
1266 }
1267
1268 @Override
1269 public void startSearch(String initialQuery, boolean selectInitialQuery,
1270 Bundle appSearchData, boolean globalSearch) {
1271 if (appSearchData == null) {
1272 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1273 }
1274 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1275 }
1276
Leon Scroggins1f005d32009-08-10 17:36:42 -04001277 /**
1278 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1279 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001280 * @param index Index of the tab to change to, as defined by
1281 * mTabControl.getTabIndex(Tab t).
1282 * @return boolean True if we successfully switched to a different tab. If
1283 * the indexth tab is null, or if that tab is the same as
1284 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001285 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001286 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001287 Tab tab = mTabControl.getTab(index);
1288 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001289 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001290 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001291 }
1292 if (currentTab != null) {
1293 // currentTab may be null if it was just removed. In that case,
1294 // we do not need to remove it
1295 removeTabFromContentView(currentTab);
1296 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001297 mTabControl.setCurrentTab(tab);
1298 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001299 resetTitleIconAndProgress();
1300 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001301 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001302 }
1303
Grace Kloba22ac16e2009-10-07 18:00:23 -07001304 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001305 return openTabAndShow(mSettings.getHomePage(), false, null);
1306 }
1307
Leon Scroggins1f005d32009-08-10 17:36:42 -04001308 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001309 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001310 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001311 // This is the last tab. Open a new one, with the home
1312 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001313 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001314 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001315 return;
1316 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001317 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001318 int indexToShow = -1;
1319 if (parent != null) {
1320 indexToShow = mTabControl.getTabIndex(parent);
1321 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001322 final int currentIndex = mTabControl.getCurrentIndex();
1323 // Try to move to the tab to the right
1324 indexToShow = currentIndex + 1;
1325 if (indexToShow > mTabControl.getTabCount() - 1) {
1326 // Try to move to the tab to the left
1327 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001328 }
1329 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001330 if (switchToTab(indexToShow)) {
1331 // Close window
1332 closeTab(current);
1333 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001334 }
1335
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001336 private ActiveTabsPage mActiveTabsPage;
1337
1338 /**
1339 * Remove the active tabs page.
1340 * @param needToAttach If true, the active tabs page did not attach a tab
1341 * to the content view, so we need to do that here.
1342 */
1343 /* package */ void removeActiveTabPage(boolean needToAttach) {
1344 mContentView.removeView(mActiveTabsPage);
1345 mActiveTabsPage = null;
1346 mMenuState = R.id.MAIN_MENU;
1347 if (needToAttach) {
1348 attachTabToContentView(mTabControl.getCurrentTab());
1349 }
1350 getTopWindow().requestFocus();
1351 }
1352
The Android Open Source Project0c908882009-03-03 19:32:16 -08001353 @Override
1354 public boolean onOptionsItemSelected(MenuItem item) {
1355 if (!mCanChord) {
1356 // The user has already fired a shortcut with this hold down of the
1357 // menu key.
1358 return false;
1359 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001360 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001361 return false;
1362 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001363 if (mMenuIsDown) {
1364 // The shortcut action consumes the MENU. Even if it is still down,
1365 // it won't trigger the next shortcut action. In the case of the
1366 // shortcut action triggering a new activity, like Bookmarks, we
1367 // won't get onKeyUp for MENU. So it is important to reset it here.
1368 mMenuIsDown = false;
1369 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001370 switch (item.getItemId()) {
1371 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001372 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001373 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001374 break;
1375
Leon Scroggins64b80f32009-08-07 12:03:34 -04001376 case R.id.goto_menu_id:
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001377 onSearchRequested();
1378 break;
1379
1380 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001381 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001382 break;
1383
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001384 case R.id.active_tabs_menu_id:
1385 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1386 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001387 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001388 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1389 mActiveTabsPage.requestFocus();
1390 mMenuState = EMPTY_MENU;
1391 break;
1392
Leon Scroggins1f005d32009-08-10 17:36:42 -04001393 case R.id.add_bookmark_menu_id:
1394 Intent i = new Intent(BrowserActivity.this,
1395 AddBookmarkPage.class);
1396 WebView w = getTopWindow();
1397 i.putExtra("url", w.getUrl());
1398 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001399 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001400 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001401 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001402 break;
1403
1404 case R.id.stop_reload_menu_id:
1405 if (mInLoad) {
1406 stopLoading();
1407 } else {
1408 getTopWindow().reload();
1409 }
1410 break;
1411
1412 case R.id.back_menu_id:
1413 getTopWindow().goBack();
1414 break;
1415
1416 case R.id.forward_menu_id:
1417 getTopWindow().goForward();
1418 break;
1419
1420 case R.id.close_menu_id:
1421 // Close the subwindow if it exists.
1422 if (mTabControl.getCurrentSubWindow() != null) {
1423 dismissSubWindow(mTabControl.getCurrentTab());
1424 break;
1425 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001426 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001427 break;
1428
1429 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001430 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001431 if (current != null) {
1432 dismissSubWindow(current);
1433 current.getWebView().loadUrl(mSettings.getHomePage());
1434 }
1435 break;
1436
1437 case R.id.preferences_menu_id:
1438 Intent intent = new Intent(this,
1439 BrowserPreferencesPage.class);
1440 startActivityForResult(intent, PREFERENCES_PAGE);
1441 break;
1442
1443 case R.id.find_menu_id:
1444 if (null == mFindDialog) {
1445 mFindDialog = new FindDialog(this);
1446 }
1447 mFindDialog.setWebView(getTopWindow());
1448 mFindDialog.show();
1449 mMenuState = EMPTY_MENU;
1450 break;
1451
1452 case R.id.select_text_id:
1453 getTopWindow().emulateShiftHeld();
1454 break;
1455 case R.id.page_info_menu_id:
1456 showPageInfo(mTabControl.getCurrentTab(), false);
1457 break;
1458
1459 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001460 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001461 break;
1462
1463 case R.id.share_page_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01001464 Browser.sendString(this, getTopWindow().getUrl(),
1465 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001466 break;
1467
1468 case R.id.dump_nav_menu_id:
1469 getTopWindow().debugDump();
1470 break;
1471
1472 case R.id.zoom_in_menu_id:
1473 getTopWindow().zoomIn();
1474 break;
1475
1476 case R.id.zoom_out_menu_id:
1477 getTopWindow().zoomOut();
1478 break;
1479
1480 case R.id.view_downloads_menu_id:
1481 viewDownloads(null);
1482 break;
1483
The Android Open Source Project0c908882009-03-03 19:32:16 -08001484 case R.id.window_one_menu_id:
1485 case R.id.window_two_menu_id:
1486 case R.id.window_three_menu_id:
1487 case R.id.window_four_menu_id:
1488 case R.id.window_five_menu_id:
1489 case R.id.window_six_menu_id:
1490 case R.id.window_seven_menu_id:
1491 case R.id.window_eight_menu_id:
1492 {
1493 int menuid = item.getItemId();
1494 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1495 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001496 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001497 if (desiredTab != null &&
1498 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001499 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001500 }
1501 break;
1502 }
1503 }
1504 }
1505 break;
1506
1507 default:
1508 if (!super.onOptionsItemSelected(item)) {
1509 return false;
1510 }
1511 // Otherwise fall through.
1512 }
1513 mCanChord = false;
1514 return true;
1515 }
1516
1517 public void closeFind() {
1518 mMenuState = R.id.MAIN_MENU;
1519 }
1520
Grace Kloba22ac16e2009-10-07 18:00:23 -07001521 @Override
1522 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001523 // This happens when the user begins to hold down the menu key, so
1524 // allow them to chord to get a shortcut.
1525 mCanChord = true;
1526 // Note: setVisible will decide whether an item is visible; while
1527 // setEnabled() will decide whether an item is enabled, which also means
1528 // whether the matching shortcut key will function.
1529 super.onPrepareOptionsMenu(menu);
1530 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001531 case EMPTY_MENU:
1532 if (mCurrentMenuState != mMenuState) {
1533 menu.setGroupVisible(R.id.MAIN_MENU, false);
1534 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1535 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001536 }
1537 break;
1538 default:
1539 if (mCurrentMenuState != mMenuState) {
1540 menu.setGroupVisible(R.id.MAIN_MENU, true);
1541 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1542 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001543 }
1544 final WebView w = getTopWindow();
1545 boolean canGoBack = false;
1546 boolean canGoForward = false;
1547 boolean isHome = false;
1548 if (w != null) {
1549 canGoBack = w.canGoBack();
1550 canGoForward = w.canGoForward();
1551 isHome = mSettings.getHomePage().equals(w.getUrl());
1552 }
1553 final MenuItem back = menu.findItem(R.id.back_menu_id);
1554 back.setEnabled(canGoBack);
1555
1556 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1557 home.setEnabled(!isHome);
1558
1559 menu.findItem(R.id.forward_menu_id)
1560 .setEnabled(canGoForward);
1561
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001562 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001563 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001564
The Android Open Source Project0c908882009-03-03 19:32:16 -08001565 // decide whether to show the share link option
1566 PackageManager pm = getPackageManager();
1567 Intent send = new Intent(Intent.ACTION_SEND);
1568 send.setType("text/plain");
1569 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1570 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1571
The Android Open Source Project0c908882009-03-03 19:32:16 -08001572 boolean isNavDump = mSettings.isNavDump();
1573 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1574 nav.setVisible(isNavDump);
1575 nav.setEnabled(isNavDump);
1576 break;
1577 }
1578 mCurrentMenuState = mMenuState;
1579 return true;
1580 }
1581
1582 @Override
1583 public void onCreateContextMenu(ContextMenu menu, View v,
1584 ContextMenuInfo menuInfo) {
1585 WebView webview = (WebView) v;
1586 WebView.HitTestResult result = webview.getHitTestResult();
1587 if (result == null) {
1588 return;
1589 }
1590
1591 int type = result.getType();
1592 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1593 Log.w(LOGTAG,
1594 "We should not show context menu when nothing is touched");
1595 return;
1596 }
1597 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1598 // let TextView handles context menu
1599 return;
1600 }
1601
1602 // Note, http://b/issue?id=1106666 is requesting that
1603 // an inflated menu can be used again. This is not available
1604 // yet, so inflate each time (yuk!)
1605 MenuInflater inflater = getMenuInflater();
1606 inflater.inflate(R.menu.browsercontext, menu);
1607
1608 // Show the correct menu group
1609 String extra = result.getExtra();
1610 menu.setGroupVisible(R.id.PHONE_MENU,
1611 type == WebView.HitTestResult.PHONE_TYPE);
1612 menu.setGroupVisible(R.id.EMAIL_MENU,
1613 type == WebView.HitTestResult.EMAIL_TYPE);
1614 menu.setGroupVisible(R.id.GEO_MENU,
1615 type == WebView.HitTestResult.GEO_TYPE);
1616 menu.setGroupVisible(R.id.IMAGE_MENU,
1617 type == WebView.HitTestResult.IMAGE_TYPE
1618 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1619 menu.setGroupVisible(R.id.ANCHOR_MENU,
1620 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1621 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1622
1623 // Setup custom handling depending on the type
1624 switch (type) {
1625 case WebView.HitTestResult.PHONE_TYPE:
1626 menu.setHeaderTitle(Uri.decode(extra));
1627 menu.findItem(R.id.dial_context_menu_id).setIntent(
1628 new Intent(Intent.ACTION_VIEW, Uri
1629 .parse(WebView.SCHEME_TEL + extra)));
1630 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1631 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001632 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001633 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1634 addIntent);
1635 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1636 new Copy(extra));
1637 break;
1638
1639 case WebView.HitTestResult.EMAIL_TYPE:
1640 menu.setHeaderTitle(extra);
1641 menu.findItem(R.id.email_context_menu_id).setIntent(
1642 new Intent(Intent.ACTION_VIEW, Uri
1643 .parse(WebView.SCHEME_MAILTO + extra)));
1644 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1645 new Copy(extra));
1646 break;
1647
1648 case WebView.HitTestResult.GEO_TYPE:
1649 menu.setHeaderTitle(extra);
1650 menu.findItem(R.id.map_context_menu_id).setIntent(
1651 new Intent(Intent.ACTION_VIEW, Uri
1652 .parse(WebView.SCHEME_GEO
1653 + URLEncoder.encode(extra))));
1654 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1655 new Copy(extra));
1656 break;
1657
1658 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1659 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1660 TextView titleView = (TextView) LayoutInflater.from(this)
1661 .inflate(android.R.layout.browser_link_context_header,
1662 null);
1663 titleView.setText(extra);
1664 menu.setHeaderView(titleView);
1665 // decide whether to show the open link in new tab option
1666 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001667 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001668 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1669 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001670 PackageManager pm = getPackageManager();
1671 Intent send = new Intent(Intent.ACTION_SEND);
1672 send.setType("text/plain");
1673 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1674 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1675 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1676 break;
1677 }
1678 // otherwise fall through to handle image part
1679 case WebView.HitTestResult.IMAGE_TYPE:
1680 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1681 menu.setHeaderTitle(extra);
1682 }
1683 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1684 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1685 menu.findItem(R.id.download_context_menu_id).
1686 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001687 menu.findItem(R.id.set_wallpaper_context_menu_id).
1688 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001689 break;
1690
1691 default:
1692 Log.w(LOGTAG, "We should not get here.");
1693 break;
1694 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001695 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001696 }
1697
The Android Open Source Project0c908882009-03-03 19:32:16 -08001698 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001699 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001700 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001701 // Attach the container that contains the main WebView and any other UI
1702 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001703 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001704
1705 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001706 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001707 if (errorConsole.numberOfErrors() == 0) {
1708 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1709 } else {
1710 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1711 }
1712
1713 mErrorConsoleContainer.addView(errorConsole,
1714 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1715 ViewGroup.LayoutParams.WRAP_CONTENT));
1716 }
1717
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001718 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001719 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001720 // Request focus on the top window.
1721 t.getTopWindow().requestFocus();
1722 }
1723
1724 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001725 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001726 t.attachSubWindow(mContentView);
1727 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001728 }
1729
1730 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001731 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001732 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001733 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001734
Grace Kloba22ac16e2009-10-07 18:00:23 -07001735 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1736 if (errorConsole != null) {
1737 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001738 }
1739
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001740 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001741 if (view != null) {
1742 view.setEmbeddedTitleBar(null);
1743 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001744 }
1745
1746 // Remove the sub window if it exists. Also called by TabControl when the
1747 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001748 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001749 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001750 // dismiss the subwindow. This will destroy the WebView.
1751 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001752 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001753 }
1754
Leon Scroggins1f005d32009-08-10 17:36:42 -04001755 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001756 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001757 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001758 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001759 }
1760
1761 // This method does a ton of stuff. It will attempt to create a new tab
1762 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001763 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001764 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1765 String appId) {
1766 final Tab currentTab = mTabControl.getCurrentTab();
1767 if (mTabControl.canCreateNewTab()) {
1768 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1769 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001770 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001771 // If the last tab was removed from the active tabs page, currentTab
1772 // will be null.
1773 if (currentTab != null) {
1774 removeTabFromContentView(currentTab);
1775 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001776 // We must set the new tab as the current tab to reflect the old
1777 // animation behavior.
1778 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001779 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001780 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001781 urlData.loadIn(webview);
1782 }
1783 return tab;
1784 } else {
1785 // Get rid of the subwindow if it exists
1786 dismissSubWindow(currentTab);
1787 if (!urlData.isEmpty()) {
1788 // Load the given url.
1789 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001790 }
1791 }
Grace Klobac9181842009-04-14 08:53:22 -07001792 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001793 }
1794
Grace Kloba22ac16e2009-10-07 18:00:23 -07001795 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001796 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001797 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001798 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001799 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001800 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001801 }
Grace Klobac9181842009-04-14 08:53:22 -07001802 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001803 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001804 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001805 }
1806 }
1807
1808 private class Copy implements OnMenuItemClickListener {
1809 private CharSequence mText;
1810
1811 public boolean onMenuItemClick(MenuItem item) {
1812 copy(mText);
1813 return true;
1814 }
1815
1816 public Copy(CharSequence toCopy) {
1817 mText = toCopy;
1818 }
1819 }
1820
1821 private class Download implements OnMenuItemClickListener {
1822 private String mText;
1823
1824 public boolean onMenuItemClick(MenuItem item) {
1825 onDownloadStartNoStream(mText, null, null, null, -1);
1826 return true;
1827 }
1828
1829 public Download(String toDownload) {
1830 mText = toDownload;
1831 }
1832 }
1833
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001834 private class SetAsWallpaper extends Thread implements
1835 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1836 private URL mUrl;
1837 private ProgressDialog mWallpaperProgress;
1838 private boolean mCanceled = false;
1839
1840 public SetAsWallpaper(String url) {
1841 try {
1842 mUrl = new URL(url);
1843 } catch (MalformedURLException e) {
1844 mUrl = null;
1845 }
1846 }
1847
1848 public void onCancel(DialogInterface dialog) {
1849 mCanceled = true;
1850 }
1851
1852 public boolean onMenuItemClick(MenuItem item) {
1853 if (mUrl != null) {
1854 // The user may have tried to set a image with a large file size as their
1855 // background so it may take a few moments to perform the operation. Display
1856 // a progress spinner while it is working.
1857 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1858 mWallpaperProgress.setIndeterminate(true);
1859 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1860 mWallpaperProgress.setCancelable(true);
1861 mWallpaperProgress.setOnCancelListener(this);
1862 mWallpaperProgress.show();
1863 start();
1864 }
1865 return true;
1866 }
1867
1868 public void run() {
1869 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1870 try {
1871 // TODO: This will cause the resource to be downloaded again, when we
1872 // should in most cases be able to grab it from the cache. To fix this
1873 // we should query WebCore to see if we can access a cached version and
1874 // instead open an input stream on that. This pattern could also be used
1875 // in the download manager where the same problem exists.
1876 InputStream inputstream = mUrl.openStream();
1877 if (inputstream != null) {
1878 setWallpaper(inputstream);
1879 }
1880 } catch (IOException e) {
1881 Log.e(LOGTAG, "Unable to set new wallpaper");
1882 // Act as though the user canceled the operation so we try to
1883 // restore the old wallpaper.
1884 mCanceled = true;
1885 }
1886
1887 if (mCanceled) {
1888 // Restore the old wallpaper if the user cancelled whilst we were setting
1889 // the new wallpaper.
1890 int width = oldWallpaper.getIntrinsicWidth();
1891 int height = oldWallpaper.getIntrinsicHeight();
1892 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1893 Canvas canvas = new Canvas(bm);
1894 oldWallpaper.setBounds(0, 0, width, height);
1895 oldWallpaper.draw(canvas);
1896 try {
1897 setWallpaper(bm);
1898 } catch (IOException e) {
1899 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1900 }
1901 mCanceled = false;
1902 }
1903
1904 if (mWallpaperProgress.isShowing()) {
1905 mWallpaperProgress.dismiss();
1906 }
1907 }
1908 }
1909
The Android Open Source Project0c908882009-03-03 19:32:16 -08001910 private void copy(CharSequence text) {
1911 try {
1912 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1913 if (clip != null) {
1914 clip.setClipboardText(text);
1915 }
1916 } catch (android.os.RemoteException e) {
1917 Log.e(LOGTAG, "Copy failed", e);
1918 }
1919 }
1920
1921 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001922 * Resets the browser title-view to whatever it must be
1923 * (for example, if we had a loading error)
1924 * When we have a new page, we call resetTitle, when we
1925 * have to reset the titlebar to whatever it used to be
1926 * (for example, if the user chose to stop loading), we
1927 * call resetTitleAndRevertLockIcon.
1928 */
1929 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001930 mTabControl.getCurrentTab().revertLockIcon();
1931 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001932 resetTitleIconAndProgress();
1933 }
1934
1935 /**
1936 * Reset the title, favicon, and progress.
1937 */
1938 private void resetTitleIconAndProgress() {
1939 WebView current = mTabControl.getCurrentWebView();
1940 if (current == null) {
1941 return;
1942 }
1943 resetTitleAndIcon(current);
1944 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001945 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001946 }
1947
1948 // Reset the title and the icon based on the given item.
1949 private void resetTitleAndIcon(WebView view) {
1950 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1951 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001952 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001953 setFavicon(item.getFavicon());
1954 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001955 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001956 setFavicon(null);
1957 }
1958 }
1959
1960 /**
1961 * Sets a title composed of the URL and the title string.
1962 * @param url The URL of the site being loaded.
1963 * @param title The title of the site being loaded.
1964 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001965 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001966 mUrl = url;
1967 mTitle = title;
1968
Leon Scroggins68579392009-09-15 15:31:54 -04001969 mTitleBar.setTitleAndUrl(title, url);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001970 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001971 }
1972
1973 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001974 * @param url The URL to build a title version of the URL from.
1975 * @return The title version of the URL or null if fails.
1976 * The title version of the URL can be either the URL hostname,
1977 * or the hostname with an "https://" prefix (for secure URLs),
1978 * or an empty string if, for example, the URL in question is a
1979 * file:// URL with no hostname.
1980 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001981 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001982 String titleUrl = null;
1983
1984 if (url != null) {
1985 try {
1986 // parse the url string
1987 URL urlObj = new URL(url);
1988 if (urlObj != null) {
1989 titleUrl = "";
1990
1991 String protocol = urlObj.getProtocol();
1992 String host = urlObj.getHost();
1993
1994 if (host != null && 0 < host.length()) {
1995 titleUrl = host;
1996 if (protocol != null) {
1997 // if a secure site, add an "https://" prefix!
1998 if (protocol.equalsIgnoreCase("https")) {
1999 titleUrl = protocol + "://" + host;
2000 }
2001 }
2002 }
2003 }
2004 } catch (MalformedURLException e) {}
2005 }
2006
2007 return titleUrl;
2008 }
2009
2010 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002011 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002012 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002013 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002014 }
2015
2016 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002017 * Close the tab, remove its associated title bar, and adjust mTabControl's
2018 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002019 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002020 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002021 int currentIndex = mTabControl.getCurrentIndex();
2022 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002023 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002024 if (currentIndex >= removeIndex && currentIndex != 0) {
2025 currentIndex--;
2026 }
2027 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002028 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002029 }
2030
2031 private void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002032 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002033 if (current == null) {
2034 /*
2035 * Instead of finishing the activity, simply push this to the back
2036 * of the stack and let ActivityManager to choose the foreground
2037 * activity. As BrowserActivity is singleTask, it will be always the
2038 * root of the task. So we can use either true or false for
2039 * moveTaskToBack().
2040 */
2041 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002042 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002043 }
2044 WebView w = current.getWebView();
2045 if (w.canGoBack()) {
2046 w.goBack();
2047 } else {
2048 // Check to see if we are closing a window that was created by
2049 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002050 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002051 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002052 switchToTab(mTabControl.getTabIndex(parent));
2053 // Now we close the other tab
2054 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002055 } else {
2056 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002057 // force the tab's inLoad() to be false as we are going to
2058 // either finish the activity or remove the tab. This will
2059 // ensure pauseWebViewTimers() taking action.
2060 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002061 if (mTabControl.getTabCount() == 1) {
2062 finish();
2063 return;
2064 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002065 // call pauseWebViewTimers() now, we won't be able to call
2066 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002067 // Temporarily change mActivityInPause to be true as
2068 // pauseWebViewTimers() will do nothing if mActivityInPause
2069 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002070 boolean savedState = mActivityInPause;
2071 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002072 Log.e(LOGTAG, "BrowserActivity is already paused "
2073 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002074 }
2075 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002076 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002077 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002078 removeTabFromContentView(current);
2079 mTabControl.removeTab(current);
2080 }
2081 /*
2082 * Instead of finishing the activity, simply push this to the back
2083 * of the stack and let ActivityManager to choose the foreground
2084 * activity. As BrowserActivity is singleTask, it will be always the
2085 * root of the task. So we can use either true or false for
2086 * moveTaskToBack().
2087 */
2088 moveTaskToBack(true);
2089 }
2090 }
2091 }
2092
Grace Kloba22ac16e2009-10-07 18:00:23 -07002093 boolean isMenuDown() {
2094 return mMenuIsDown;
2095 }
2096
Grace Kloba5942df02009-09-18 11:48:29 -07002097 @Override
2098 public boolean onKeyDown(int keyCode, KeyEvent event) {
2099 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2100 // still down, we don't want to trigger the search. Pretend to consume
2101 // the key and do nothing.
2102 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002103
Grace Kloba5942df02009-09-18 11:48:29 -07002104 switch(keyCode) {
2105 case KeyEvent.KEYCODE_MENU:
2106 mMenuIsDown = true;
2107 break;
2108 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002109 // WebView/WebTextView handle the keys in the KeyDown. As
2110 // the Activity's shortcut keys are only handled when WebView
2111 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2112 if (event.isShiftPressed()) {
2113 getTopWindow().pageUp(false);
2114 } else {
2115 getTopWindow().pageDown(false);
2116 }
Grace Kloba5942df02009-09-18 11:48:29 -07002117 return true;
2118 case KeyEvent.KEYCODE_BACK:
2119 if (event.getRepeatCount() == 0) {
2120 event.startTracking();
2121 return true;
2122 } else if (mCustomView == null && mActiveTabsPage == null
2123 && event.isLongPress()) {
2124 bookmarksOrHistoryPicker(true);
2125 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002126 }
Grace Kloba5942df02009-09-18 11:48:29 -07002127 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002128 }
Grace Kloba5942df02009-09-18 11:48:29 -07002129 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002130 }
2131
Grace Kloba5942df02009-09-18 11:48:29 -07002132 @Override
2133 public boolean onKeyUp(int keyCode, KeyEvent event) {
2134 switch(keyCode) {
2135 case KeyEvent.KEYCODE_MENU:
2136 mMenuIsDown = false;
2137 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002138 case KeyEvent.KEYCODE_BACK:
2139 if (event.isTracking() && !event.isCanceled()) {
2140 if (mCustomView != null) {
2141 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002142 mTabControl.getCurrentWebView().getWebChromeClient()
2143 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002144 } else if (mActiveTabsPage != null) {
2145 // if tab page is showing, hide it
2146 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002147 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002148 WebView subwindow = mTabControl.getCurrentSubWindow();
2149 if (subwindow != null) {
2150 if (subwindow.canGoBack()) {
2151 subwindow.goBack();
2152 } else {
2153 dismissSubWindow(mTabControl.getCurrentTab());
2154 }
2155 } else {
2156 goBackOnePageOrQuit();
2157 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002158 }
Grace Kloba5942df02009-09-18 11:48:29 -07002159 return true;
2160 }
2161 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002162 }
Grace Kloba5942df02009-09-18 11:48:29 -07002163 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002164 }
2165
Leon Scroggins68579392009-09-15 15:31:54 -04002166 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002167 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002168 resetTitleAndRevertLockIcon();
2169 WebView w = getTopWindow();
2170 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002171 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2172 // same logic here. But for subwindow case, should we call into the main
2173 // WebView's onPageFinished as we never call its onPageStarted and if
2174 // the page finishes itself, we don't call onPageFinished.
2175 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2176 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002177
2178 cancelStopToast();
2179 mStopToast = Toast
2180 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2181 mStopToast.show();
2182 }
2183
Grace Kloba22ac16e2009-10-07 18:00:23 -07002184 boolean didUserStopLoading() {
2185 return mDidStopLoad;
2186 }
2187
The Android Open Source Project0c908882009-03-03 19:32:16 -08002188 private void cancelStopToast() {
2189 if (mStopToast != null) {
2190 mStopToast.cancel();
2191 mStopToast = null;
2192 }
2193 }
2194
Grace Kloba22ac16e2009-10-07 18:00:23 -07002195 // called by a UI or non-UI thread to post the message
2196 public void postMessage(int what, int arg1, int arg2, Object obj,
2197 long delayMillis) {
2198 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2199 obj), delayMillis);
2200 }
2201
2202 // called by a UI or non-UI thread to remove the message
2203 void removeMessages(int what, Object object) {
2204 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002205 }
2206
2207 // public message ids
2208 public final static int LOAD_URL = 1001;
2209 public final static int STOP_LOAD = 1002;
2210
2211 // Message Ids
2212 private static final int FOCUS_NODE_HREF = 102;
2213 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002214 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002215
Grace Kloba22ac16e2009-10-07 18:00:23 -07002216 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002217
The Android Open Source Project0c908882009-03-03 19:32:16 -08002218 // Private handler for handling javascript and saving passwords
2219 private Handler mHandler = new Handler() {
2220
2221 public void handleMessage(Message msg) {
2222 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002223 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002224 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002225 String url = (String) msg.getData().get("url");
2226 if (url == null || url.length() == 0) {
2227 break;
2228 }
2229 HashMap focusNodeMap = (HashMap) msg.obj;
2230 WebView view = (WebView) focusNodeMap.get("webview");
2231 // Only apply the action if the top window did not change.
2232 if (getTopWindow() != view) {
2233 break;
2234 }
2235 switch (msg.arg1) {
2236 case R.id.open_context_menu_id:
2237 case R.id.view_image_context_menu_id:
2238 loadURL(getTopWindow(), url);
2239 break;
2240 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002241 final Tab parent = mTabControl.getCurrentTab();
2242 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002243 if (newTab != parent) {
2244 parent.addChildTab(newTab);
2245 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002246 break;
2247 case R.id.bookmark_context_menu_id:
2248 Intent intent = new Intent(BrowserActivity.this,
2249 AddBookmarkPage.class);
2250 intent.putExtra("url", url);
2251 startActivity(intent);
2252 break;
2253 case R.id.share_link_context_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01002254 Browser.sendString(BrowserActivity.this, url,
2255 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002256 break;
2257 case R.id.copy_link_context_menu_id:
2258 copy(url);
2259 break;
2260 case R.id.save_link_context_menu_id:
2261 case R.id.download_context_menu_id:
2262 onDownloadStartNoStream(url, null, null, null, -1);
2263 break;
2264 }
2265 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002266 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002267
2268 case LOAD_URL:
2269 loadURL(getTopWindow(), (String) msg.obj);
2270 break;
2271
2272 case STOP_LOAD:
2273 stopLoading();
2274 break;
2275
2276 case CANCEL_CREDS_REQUEST:
2277 resumeAfterCredentials();
2278 break;
2279
The Android Open Source Project0c908882009-03-03 19:32:16 -08002280 case RELEASE_WAKELOCK:
2281 if (mWakeLock.isHeld()) {
2282 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002283 // if we reach here, Browser should be still in the
2284 // background loading after WAKELOCK_TIMEOUT (5-min).
2285 // To avoid burning the battery, stop loading.
2286 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002287 }
2288 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002289
2290 case UPDATE_BOOKMARK_THUMBNAIL:
2291 WebView view = (WebView) msg.obj;
2292 if (view != null) {
2293 updateScreenshot(view);
2294 }
2295 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002296 }
2297 }
2298 };
2299
Leon Scroggins89c6d362009-07-15 16:54:37 -04002300 private void updateScreenshot(WebView view) {
2301 // If this is a bookmarked site, add a screenshot to the database.
2302 // FIXME: When should we update? Every time?
2303 // FIXME: Would like to make sure there is actually something to
2304 // draw, but the API for that (WebViewCore.pictureReady()) is not
2305 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002306
Patrick Scott3918d442009-08-04 13:22:29 -04002307 ContentResolver cr = getContentResolver();
2308 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002309 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002310 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002311 boolean succeed = c.moveToFirst();
2312 ContentValues values = null;
2313 while (succeed) {
2314 if (values == null) {
2315 final ByteArrayOutputStream os
2316 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002317 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002318 if (bm == null) {
2319 c.close();
2320 return;
2321 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002322 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2323 values = new ContentValues();
2324 values.put(Browser.BookmarkColumns.THUMBNAIL,
2325 os.toByteArray());
2326 }
2327 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2328 c.getInt(0)), values, null, null);
2329 succeed = c.moveToNext();
2330 }
2331 c.close();
2332 }
2333 }
2334
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002335 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002336 * Values for the size of the thumbnail created when taking a screenshot.
2337 * Lazily initialized. Instead of using these directly, use
2338 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002339 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002340 private static int THUMBNAIL_WIDTH = 0;
2341 private static int THUMBNAIL_HEIGHT = 0;
2342
2343 /**
2344 * Return the desired width for thumbnail screenshots, which are stored in
2345 * the database, and used on the bookmarks screen.
2346 * @param context Context for finding out the density of the screen.
2347 * @return int desired width for thumbnail screenshot.
2348 */
2349 /* package */ static int getDesiredThumbnailWidth(Context context) {
2350 if (THUMBNAIL_WIDTH == 0) {
2351 float density = context.getResources().getDisplayMetrics().density;
2352 THUMBNAIL_WIDTH = (int) (90 * density);
2353 THUMBNAIL_HEIGHT = (int) (80 * density);
2354 }
2355 return THUMBNAIL_WIDTH;
2356 }
2357
2358 /**
2359 * Return the desired height for thumbnail screenshots, which are stored in
2360 * the database, and used on the bookmarks screen.
2361 * @param context Context for finding out the density of the screen.
2362 * @return int desired height for thumbnail screenshot.
2363 */
2364 /* package */ static int getDesiredThumbnailHeight(Context context) {
2365 // To ensure that they are both initialized.
2366 getDesiredThumbnailWidth(context);
2367 return THUMBNAIL_HEIGHT;
2368 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002369
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002370 private Bitmap createScreenshot(WebView view) {
2371 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002372 if (thumbnail == null) {
2373 return null;
2374 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002375 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2376 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002377 Canvas canvas = new Canvas(bm);
2378 // May need to tweak these values to determine what is the
2379 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002380 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002381 int thumbnailHeight = thumbnail.getHeight();
2382 float scaleFactorX = 1.0f;
2383 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002384 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002385 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002386 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002387 } else {
2388 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002389 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002390
2391 if (view.getWidth() > view.getHeight() &&
2392 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2393 // If the device is in landscape and the page is shorter
2394 // than the height of the view, stretch the thumbnail to fill the
2395 // space.
2396 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2397 (float)thumbnailHeight;
2398 } else {
2399 // In the portrait case, this looks nice.
2400 scaleFactorY = scaleFactorX;
2401 }
2402
2403 canvas.scale(scaleFactorX, scaleFactorY);
2404
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002405 thumbnail.draw(canvas);
2406 return bm;
2407 }
2408
The Android Open Source Project0c908882009-03-03 19:32:16 -08002409 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002410 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002411 //-------------------------------------------------------------------------
2412
2413 // Use in overrideUrlLoading
2414 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2415 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2416 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2417 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2418
Grace Kloba22ac16e2009-10-07 18:00:23 -07002419 void onPageStarted(WebView view, String url, Bitmap favicon) {
2420 // when BrowserActivity just starts, onPageStarted may be called before
2421 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2422 // to start the timer. As we won't switch tabs while an activity is in
2423 // pause state, we can ensure calling resume and pause in pair.
2424 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002425
Grace Kloba22ac16e2009-10-07 18:00:23 -07002426 resetLockIcon(url);
2427 setUrlTitle(url, null);
2428 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002429 // Keep this initial progress in sync with initialProgressValue (* 100)
2430 // in ProgressTracker.cpp
2431 // Show some progress so that the user knows the page is beginning to
2432 // load
2433 onProgressChanged(view, 10);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002434 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002435 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002436
Grace Kloba22ac16e2009-10-07 18:00:23 -07002437 if (mSettings.isTracing()) {
2438 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002439 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002440 WebAddress uri = new WebAddress(url);
2441 host = uri.mHost;
2442 } catch (android.net.ParseException ex) {
2443 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002444 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002445 host = host.replace('.', '_');
2446 host += ".trace";
2447 mInTrace = true;
2448 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2449 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002450
Grace Kloba22ac16e2009-10-07 18:00:23 -07002451 // Performance probe
2452 if (false) {
2453 mStart = SystemClock.uptimeMillis();
2454 mProcessStart = Process.getElapsedCpuTime();
2455 long[] sysCpu = new long[7];
2456 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2457 sysCpu, null)) {
2458 mUserStart = sysCpu[0] + sysCpu[1];
2459 mSystemStart = sysCpu[2];
2460 mIdleStart = sysCpu[3];
2461 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2462 }
2463 mUiStart = SystemClock.currentThreadTimeMillis();
2464 }
2465 }
2466
2467 void onPageFinished(WebView view, String url) {
2468 // Reset the title and icon in case we stopped a provisional load.
2469 resetTitleAndIcon(view);
2470 // Update the lock icon image only once we are done loading
2471 updateLockIconToLatest();
2472 // pause the WebView timer and release the wake lock if it is finished
2473 // while BrowserActivity is in pause state.
2474 if (mActivityInPause && pauseWebViewTimers()) {
2475 if (mWakeLock.isHeld()) {
2476 mHandler.removeMessages(RELEASE_WAKELOCK);
2477 mWakeLock.release();
2478 }
2479 }
2480
2481 // Performance probe
2482 if (false) {
2483 long[] sysCpu = new long[7];
2484 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2485 sysCpu, null)) {
2486 String uiInfo = "UI thread used "
2487 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2488 + " ms";
2489 if (LOGD_ENABLED) {
2490 Log.d(LOGTAG, uiInfo);
2491 }
2492 //The string that gets written to the log
2493 String performanceString = "It took total "
2494 + (SystemClock.uptimeMillis() - mStart)
2495 + " ms clock time to load the page."
2496 + "\nbrowser process used "
2497 + (Process.getElapsedCpuTime() - mProcessStart)
2498 + " ms, user processes used "
2499 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2500 + " ms, kernel used "
2501 + (sysCpu[2] - mSystemStart) * 10
2502 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2503 + " ms and irq took "
2504 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2505 * 10 + " ms, " + uiInfo;
2506 if (LOGD_ENABLED) {
2507 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2508 }
2509 if (url != null) {
2510 // strip the url to maintain consistency
2511 String newUrl = new String(url);
2512 if (newUrl.startsWith("http://www.")) {
2513 newUrl = newUrl.substring(11);
2514 } else if (newUrl.startsWith("http://")) {
2515 newUrl = newUrl.substring(7);
2516 } else if (newUrl.startsWith("https://www.")) {
2517 newUrl = newUrl.substring(12);
2518 } else if (newUrl.startsWith("https://")) {
2519 newUrl = newUrl.substring(8);
2520 }
2521 if (LOGD_ENABLED) {
2522 Log.d(LOGTAG, newUrl + " loaded");
2523 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002524 }
2525 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002526 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002527
Grace Kloba22ac16e2009-10-07 18:00:23 -07002528 if (mInTrace) {
2529 mInTrace = false;
2530 Debug.stopMethodTracing();
2531 }
2532 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002533
Grace Kloba22ac16e2009-10-07 18:00:23 -07002534 boolean shouldOverrideUrlLoading(WebView view, String url) {
2535 if (url.startsWith(SCHEME_WTAI)) {
2536 // wtai://wp/mc;number
2537 // number=string(phone-number)
2538 if (url.startsWith(SCHEME_WTAI_MC)) {
2539 Intent intent = new Intent(Intent.ACTION_VIEW,
2540 Uri.parse(WebView.SCHEME_TEL +
2541 url.substring(SCHEME_WTAI_MC.length())));
2542 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002543 return true;
2544 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002545 // wtai://wp/sd;dtmf
2546 // dtmf=string(dialstring)
2547 if (url.startsWith(SCHEME_WTAI_SD)) {
2548 // TODO: only send when there is active voice connection
2549 return false;
2550 }
2551 // wtai://wp/ap;number;name
2552 // number=string(phone-number)
2553 // name=string
2554 if (url.startsWith(SCHEME_WTAI_AP)) {
2555 // TODO
2556 return false;
2557 }
2558 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002559
Grace Kloba22ac16e2009-10-07 18:00:23 -07002560 // The "about:" schemes are internal to the browser; don't want these to
2561 // be dispatched to other apps.
2562 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002563 return false;
2564 }
2565
Grace Kloba22ac16e2009-10-07 18:00:23 -07002566 Intent intent;
2567 // perform generic parsing of the URI to turn it into an Intent.
2568 try {
2569 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2570 } catch (URISyntaxException ex) {
2571 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2572 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002573 }
2574
Grace Kloba22ac16e2009-10-07 18:00:23 -07002575 // check whether the intent can be resolved. If not, we will see
2576 // whether we can download it from the Market.
2577 if (getPackageManager().resolveActivity(intent, 0) == null) {
2578 String packagename = intent.getPackage();
2579 if (packagename != null) {
2580 intent = new Intent(Intent.ACTION_VIEW, Uri
2581 .parse("market://search?q=pname:" + packagename));
2582 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2583 startActivity(intent);
2584 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002585 } else {
2586 return false;
2587 }
2588 }
2589
Grace Kloba22ac16e2009-10-07 18:00:23 -07002590 // sanitize the Intent, ensuring web pages can not bypass browser
2591 // security (only access to BROWSABLE activities).
2592 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2593 intent.setComponent(null);
2594 try {
2595 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002596 return true;
2597 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002598 } catch (ActivityNotFoundException ex) {
2599 // ignore the error. If no application can handle the URL,
2600 // eg about:blank, assume the browser can handle it.
2601 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002602
Grace Kloba22ac16e2009-10-07 18:00:23 -07002603 if (mMenuIsDown) {
2604 openTab(url);
2605 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002606 return true;
2607 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002608 return false;
2609 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002610
Grace Kloba22ac16e2009-10-07 18:00:23 -07002611 // -------------------------------------------------------------------------
2612 // Helper function for WebChromeClient
2613 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002614
Grace Kloba22ac16e2009-10-07 18:00:23 -07002615 void onProgressChanged(WebView view, int newProgress) {
2616 mTitleBar.setProgress(newProgress);
2617 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002618
Grace Kloba22ac16e2009-10-07 18:00:23 -07002619 if (newProgress == 100) {
2620 // onProgressChanged() may continue to be called after the main
2621 // frame has finished loading, as any remaining sub frames continue
2622 // to load. We'll only get called once though with newProgress as
2623 // 100 when everything is loaded. (onPageFinished is called once
2624 // when the main frame completes loading regardless of the state of
2625 // any sub frames so calls to onProgressChanges may continue after
2626 // onPageFinished has executed)
2627 if (mInLoad) {
2628 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002629 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002630 // If the options menu is open, leave the title bar
2631 if (!mOptionsMenuOpen || !mIconView) {
2632 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002633 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002634 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002635 } else if (!mInLoad) {
2636 // onPageFinished may have already been called but a subframe is
2637 // still loading and updating the progress. Reset mInLoad and update
2638 // the menu items.
2639 mInLoad = true;
2640 updateInLoadMenuItems();
2641 if (!mOptionsMenuOpen || mIconView) {
2642 // This page has begun to load, so show the title bar
2643 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002644 }
2645 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002646 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002647
Grace Kloba22ac16e2009-10-07 18:00:23 -07002648 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2649 if (mCustomView != null)
2650 return;
2651
2652 // Add the custom view to its container.
2653 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2654 mCustomView = view;
2655 mCustomViewCallback = callback;
2656 // Save the menu state and set it to empty while the custom
2657 // view is showing.
2658 mOldMenuState = mMenuState;
2659 mMenuState = EMPTY_MENU;
2660 // Hide the content view.
2661 mContentView.setVisibility(View.GONE);
2662 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002663 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002664 mCustomViewContainer.setVisibility(View.VISIBLE);
2665 mCustomViewContainer.bringToFront();
2666 }
2667
2668 void onHideCustomView() {
2669 if (mCustomView == null)
2670 return;
2671
2672 // Hide the custom view.
2673 mCustomView.setVisibility(View.GONE);
2674 // Remove the custom view from its container.
2675 mCustomViewContainer.removeView(mCustomView);
2676 mCustomView = null;
2677 // Reset the old menu state.
2678 mMenuState = mOldMenuState;
2679 mOldMenuState = EMPTY_MENU;
2680 mCustomViewContainer.setVisibility(View.GONE);
2681 mCustomViewCallback.onCustomViewHidden();
2682 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002683 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002684 mContentView.setVisibility(View.VISIBLE);
2685 }
2686
2687 Bitmap getDefaultVideoPoster() {
2688 if (mDefaultVideoPoster == null) {
2689 mDefaultVideoPoster = BitmapFactory.decodeResource(
2690 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002691 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002692 return mDefaultVideoPoster;
2693 }
Patrick Scott3918d442009-08-04 13:22:29 -04002694
Grace Kloba22ac16e2009-10-07 18:00:23 -07002695 View getVideoLoadingProgressView() {
2696 if (mVideoProgressView == null) {
2697 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2698 mVideoProgressView = inflater.inflate(
2699 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002700 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002701 return mVideoProgressView;
2702 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002703
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002704 /*
2705 * The Object used to inform the WebView of the file to upload.
2706 */
2707 private ValueCallback<Uri> mUploadMessage;
2708
Grace Kloba22ac16e2009-10-07 18:00:23 -07002709 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2710 if (mUploadMessage != null) return;
2711 mUploadMessage = uploadMsg;
2712 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2713 i.addCategory(Intent.CATEGORY_OPENABLE);
2714 i.setType("*/*");
2715 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2716 getString(R.string.choose_upload)), FILE_SELECTED);
2717 }
2718
2719 // -------------------------------------------------------------------------
2720 // Implement functions for DownloadListener
2721 // -------------------------------------------------------------------------
2722
The Android Open Source Project0c908882009-03-03 19:32:16 -08002723 /**
2724 * Notify the host application a download should be done, or that
2725 * the data should be streamed if a streaming viewer is available.
2726 * @param url The full url to the content that should be downloaded
2727 * @param contentDisposition Content-disposition http header, if
2728 * present.
2729 * @param mimetype The mimetype of the content reported by the server
2730 * @param contentLength The file size reported by the server
2731 */
2732 public void onDownloadStart(String url, String userAgent,
2733 String contentDisposition, String mimetype, long contentLength) {
2734 // if we're dealing wih A/V content that's not explicitly marked
2735 // for download, check if it's streamable.
2736 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002737 || !contentDisposition.regionMatches(
2738 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002739 // query the package manager to see if there's a registered handler
2740 // that matches.
2741 Intent intent = new Intent(Intent.ACTION_VIEW);
2742 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002743 ResolveInfo info = getPackageManager().resolveActivity(intent,
2744 PackageManager.MATCH_DEFAULT_ONLY);
2745 if (info != null) {
2746 ComponentName myName = getComponentName();
2747 // If we resolved to ourselves, we don't want to attempt to
2748 // load the url only to try and download it again.
2749 if (!myName.getPackageName().equals(
2750 info.activityInfo.packageName)
2751 || !myName.getClassName().equals(
2752 info.activityInfo.name)) {
2753 // someone (other than us) knows how to handle this mime
2754 // type with this scheme, don't download.
2755 try {
2756 startActivity(intent);
2757 return;
2758 } catch (ActivityNotFoundException ex) {
2759 if (LOGD_ENABLED) {
2760 Log.d(LOGTAG, "activity not found for " + mimetype
2761 + " over " + Uri.parse(url).getScheme(),
2762 ex);
2763 }
2764 // Best behavior is to fall back to a download in this
2765 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002766 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002767 }
2768 }
2769 }
2770 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2771 }
2772
2773 /**
2774 * Notify the host application a download should be done, even if there
2775 * is a streaming viewer available for thise type.
2776 * @param url The full url to the content that should be downloaded
2777 * @param contentDisposition Content-disposition http header, if
2778 * present.
2779 * @param mimetype The mimetype of the content reported by the server
2780 * @param contentLength The file size reported by the server
2781 */
2782 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2783 String contentDisposition, String mimetype, long contentLength) {
2784
2785 String filename = URLUtil.guessFileName(url,
2786 contentDisposition, mimetype);
2787
2788 // Check to see if we have an SDCard
2789 String status = Environment.getExternalStorageState();
2790 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2791 int title;
2792 String msg;
2793
2794 // Check to see if the SDCard is busy, same as the music app
2795 if (status.equals(Environment.MEDIA_SHARED)) {
2796 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2797 title = R.string.download_sdcard_busy_dlg_title;
2798 } else {
2799 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2800 title = R.string.download_no_sdcard_dlg_title;
2801 }
2802
2803 new AlertDialog.Builder(this)
2804 .setTitle(title)
2805 .setIcon(android.R.drawable.ic_dialog_alert)
2806 .setMessage(msg)
2807 .setPositiveButton(R.string.ok, null)
2808 .show();
2809 return;
2810 }
2811
2812 // java.net.URI is a lot stricter than KURL so we have to undo
2813 // KURL's percent-encoding and redo the encoding using java.net.URI.
2814 URI uri = null;
2815 try {
2816 // Undo the percent-encoding that KURL may have done.
2817 String newUrl = new String(URLUtil.decode(url.getBytes()));
2818 // Parse the url into pieces
2819 WebAddress w = new WebAddress(newUrl);
2820 String frag = null;
2821 String query = null;
2822 String path = w.mPath;
2823 // Break the path into path, query, and fragment
2824 if (path.length() > 0) {
2825 // Strip the fragment
2826 int idx = path.lastIndexOf('#');
2827 if (idx != -1) {
2828 frag = path.substring(idx + 1);
2829 path = path.substring(0, idx);
2830 }
2831 idx = path.lastIndexOf('?');
2832 if (idx != -1) {
2833 query = path.substring(idx + 1);
2834 path = path.substring(0, idx);
2835 }
2836 }
2837 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2838 query, frag);
2839 } catch (Exception e) {
2840 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2841 return;
2842 }
2843
2844 // XXX: Have to use the old url since the cookies were stored using the
2845 // old percent-encoded url.
2846 String cookies = CookieManager.getInstance().getCookie(url);
2847
2848 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002849 values.put(Downloads.COLUMN_URI, uri.toString());
2850 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
2851 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
2852 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002853 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002854 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002855 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002856 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2857 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
2858 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
2859 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002860 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002861 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002862 }
2863 if (mimetype == null) {
2864 // We must have long pressed on a link or image to download it. We
2865 // are not sure of the mimetype in this case, so do a head request
2866 new FetchUrlMimeType(this).execute(values);
2867 } else {
2868 final Uri contentUri =
2869 getContentResolver().insert(Downloads.CONTENT_URI, values);
2870 viewDownloads(contentUri);
2871 }
2872
2873 }
2874
Grace Kloba22ac16e2009-10-07 18:00:23 -07002875 // -------------------------------------------------------------------------
2876
The Android Open Source Project0c908882009-03-03 19:32:16 -08002877 /**
2878 * Resets the lock icon. This method is called when we start a new load and
2879 * know the url to be loaded.
2880 */
2881 private void resetLockIcon(String url) {
2882 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002883 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002884 updateLockIconImage(LOCK_ICON_UNSECURE);
2885 }
2886
The Android Open Source Project0c908882009-03-03 19:32:16 -08002887 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002888 * Update the lock icon to correspond to our latest state.
2889 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002890 private void updateLockIconToLatest() {
2891 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002892 }
2893
2894 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002895 * Updates the lock-icon image in the title-bar.
2896 */
2897 private void updateLockIconImage(int lockIconType) {
2898 Drawable d = null;
2899 if (lockIconType == LOCK_ICON_SECURE) {
2900 d = mSecLockIcon;
2901 } else if (lockIconType == LOCK_ICON_MIXED) {
2902 d = mMixLockIcon;
2903 }
Leon Scroggins68579392009-09-15 15:31:54 -04002904 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002905 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002906 }
2907
2908 /**
2909 * Displays a page-info dialog.
2910 * @param tab The tab to show info about
2911 * @param fromShowSSLCertificateOnError The flag that indicates whether
2912 * this dialog was opened from the SSL-certificate-on-error dialog or
2913 * not. This is important, since we need to know whether to return to
2914 * the parent dialog or simply dismiss.
2915 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002916 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002917 final boolean fromShowSSLCertificateOnError) {
2918 final LayoutInflater factory = LayoutInflater
2919 .from(this);
2920
2921 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2922
2923 final WebView view = tab.getWebView();
2924
2925 String url = null;
2926 String title = null;
2927
2928 if (view == null) {
2929 url = tab.getUrl();
2930 title = tab.getTitle();
2931 } else if (view == mTabControl.getCurrentWebView()) {
2932 // Use the cached title and url if this is the current WebView
2933 url = mUrl;
2934 title = mTitle;
2935 } else {
2936 url = view.getUrl();
2937 title = view.getTitle();
2938 }
2939
2940 if (url == null) {
2941 url = "";
2942 }
2943 if (title == null) {
2944 title = "";
2945 }
2946
2947 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
2948 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
2949
2950 mPageInfoView = tab;
2951 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
2952
2953 AlertDialog.Builder alertDialogBuilder =
2954 new AlertDialog.Builder(this)
2955 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
2956 .setView(pageInfoView)
2957 .setPositiveButton(
2958 R.string.ok,
2959 new DialogInterface.OnClickListener() {
2960 public void onClick(DialogInterface dialog,
2961 int whichButton) {
2962 mPageInfoDialog = null;
2963 mPageInfoView = null;
2964 mPageInfoFromShowSSLCertificateOnError = null;
2965
2966 // if we came here from the SSL error dialog
2967 if (fromShowSSLCertificateOnError) {
2968 // go back to the SSL error dialog
2969 showSSLCertificateOnError(
2970 mSSLCertificateOnErrorView,
2971 mSSLCertificateOnErrorHandler,
2972 mSSLCertificateOnErrorError);
2973 }
2974 }
2975 })
2976 .setOnCancelListener(
2977 new DialogInterface.OnCancelListener() {
2978 public void onCancel(DialogInterface dialog) {
2979 mPageInfoDialog = null;
2980 mPageInfoView = null;
2981 mPageInfoFromShowSSLCertificateOnError = null;
2982
2983 // if we came here from the SSL error dialog
2984 if (fromShowSSLCertificateOnError) {
2985 // go back to the SSL error dialog
2986 showSSLCertificateOnError(
2987 mSSLCertificateOnErrorView,
2988 mSSLCertificateOnErrorHandler,
2989 mSSLCertificateOnErrorError);
2990 }
2991 }
2992 });
2993
2994 // if we have a main top-level page SSL certificate set or a certificate
2995 // error
2996 if (fromShowSSLCertificateOnError ||
2997 (view != null && view.getCertificate() != null)) {
2998 // add a 'View Certificate' button
2999 alertDialogBuilder.setNeutralButton(
3000 R.string.view_certificate,
3001 new DialogInterface.OnClickListener() {
3002 public void onClick(DialogInterface dialog,
3003 int whichButton) {
3004 mPageInfoDialog = null;
3005 mPageInfoView = null;
3006 mPageInfoFromShowSSLCertificateOnError = null;
3007
3008 // if we came here from the SSL error dialog
3009 if (fromShowSSLCertificateOnError) {
3010 // go back to the SSL error dialog
3011 showSSLCertificateOnError(
3012 mSSLCertificateOnErrorView,
3013 mSSLCertificateOnErrorHandler,
3014 mSSLCertificateOnErrorError);
3015 } else {
3016 // otherwise, display the top-most certificate from
3017 // the chain
3018 if (view.getCertificate() != null) {
3019 showSSLCertificate(tab);
3020 }
3021 }
3022 }
3023 });
3024 }
3025
3026 mPageInfoDialog = alertDialogBuilder.show();
3027 }
3028
3029 /**
3030 * Displays the main top-level page SSL certificate dialog
3031 * (accessible from the Page-Info dialog).
3032 * @param tab The tab to show certificate for.
3033 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003034 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003035 final View certificateView =
3036 inflateCertificateView(tab.getWebView().getCertificate());
3037 if (certificateView == null) {
3038 return;
3039 }
3040
3041 LayoutInflater factory = LayoutInflater.from(this);
3042
3043 final LinearLayout placeholder =
3044 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3045
3046 LinearLayout ll = (LinearLayout) factory.inflate(
3047 R.layout.ssl_success, placeholder);
3048 ((TextView)ll.findViewById(R.id.success))
3049 .setText(R.string.ssl_certificate_is_valid);
3050
3051 mSSLCertificateView = tab;
3052 mSSLCertificateDialog =
3053 new AlertDialog.Builder(this)
3054 .setTitle(R.string.ssl_certificate).setIcon(
3055 R.drawable.ic_dialog_browser_certificate_secure)
3056 .setView(certificateView)
3057 .setPositiveButton(R.string.ok,
3058 new DialogInterface.OnClickListener() {
3059 public void onClick(DialogInterface dialog,
3060 int whichButton) {
3061 mSSLCertificateDialog = null;
3062 mSSLCertificateView = null;
3063
3064 showPageInfo(tab, false);
3065 }
3066 })
3067 .setOnCancelListener(
3068 new DialogInterface.OnCancelListener() {
3069 public void onCancel(DialogInterface dialog) {
3070 mSSLCertificateDialog = null;
3071 mSSLCertificateView = null;
3072
3073 showPageInfo(tab, false);
3074 }
3075 })
3076 .show();
3077 }
3078
3079 /**
3080 * Displays the SSL error certificate dialog.
3081 * @param view The target web-view.
3082 * @param handler The SSL error handler responsible for cancelling the
3083 * connection that resulted in an SSL error or proceeding per user request.
3084 * @param error The SSL error object.
3085 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003086 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003087 final WebView view, final SslErrorHandler handler, final SslError error) {
3088
3089 final View certificateView =
3090 inflateCertificateView(error.getCertificate());
3091 if (certificateView == null) {
3092 return;
3093 }
3094
3095 LayoutInflater factory = LayoutInflater.from(this);
3096
3097 final LinearLayout placeholder =
3098 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3099
3100 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3101 LinearLayout ll = (LinearLayout)factory
3102 .inflate(R.layout.ssl_warning, placeholder);
3103 ((TextView)ll.findViewById(R.id.warning))
3104 .setText(R.string.ssl_untrusted);
3105 }
3106
3107 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3108 LinearLayout ll = (LinearLayout)factory
3109 .inflate(R.layout.ssl_warning, placeholder);
3110 ((TextView)ll.findViewById(R.id.warning))
3111 .setText(R.string.ssl_mismatch);
3112 }
3113
3114 if (error.hasError(SslError.SSL_EXPIRED)) {
3115 LinearLayout ll = (LinearLayout)factory
3116 .inflate(R.layout.ssl_warning, placeholder);
3117 ((TextView)ll.findViewById(R.id.warning))
3118 .setText(R.string.ssl_expired);
3119 }
3120
3121 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3122 LinearLayout ll = (LinearLayout)factory
3123 .inflate(R.layout.ssl_warning, placeholder);
3124 ((TextView)ll.findViewById(R.id.warning))
3125 .setText(R.string.ssl_not_yet_valid);
3126 }
3127
3128 mSSLCertificateOnErrorHandler = handler;
3129 mSSLCertificateOnErrorView = view;
3130 mSSLCertificateOnErrorError = error;
3131 mSSLCertificateOnErrorDialog =
3132 new AlertDialog.Builder(this)
3133 .setTitle(R.string.ssl_certificate).setIcon(
3134 R.drawable.ic_dialog_browser_certificate_partially_secure)
3135 .setView(certificateView)
3136 .setPositiveButton(R.string.ok,
3137 new DialogInterface.OnClickListener() {
3138 public void onClick(DialogInterface dialog,
3139 int whichButton) {
3140 mSSLCertificateOnErrorDialog = null;
3141 mSSLCertificateOnErrorView = null;
3142 mSSLCertificateOnErrorHandler = null;
3143 mSSLCertificateOnErrorError = null;
3144
Grace Kloba22ac16e2009-10-07 18:00:23 -07003145 view.getWebViewClient().onReceivedSslError(
3146 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003147 }
3148 })
3149 .setNeutralButton(R.string.page_info_view,
3150 new DialogInterface.OnClickListener() {
3151 public void onClick(DialogInterface dialog,
3152 int whichButton) {
3153 mSSLCertificateOnErrorDialog = null;
3154
3155 // do not clear the dialog state: we will
3156 // need to show the dialog again once the
3157 // user is done exploring the page-info details
3158
3159 showPageInfo(mTabControl.getTabFromView(view),
3160 true);
3161 }
3162 })
3163 .setOnCancelListener(
3164 new DialogInterface.OnCancelListener() {
3165 public void onCancel(DialogInterface dialog) {
3166 mSSLCertificateOnErrorDialog = null;
3167 mSSLCertificateOnErrorView = null;
3168 mSSLCertificateOnErrorHandler = null;
3169 mSSLCertificateOnErrorError = null;
3170
Grace Kloba22ac16e2009-10-07 18:00:23 -07003171 view.getWebViewClient().onReceivedSslError(
3172 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003173 }
3174 })
3175 .show();
3176 }
3177
3178 /**
3179 * Inflates the SSL certificate view (helper method).
3180 * @param certificate The SSL certificate.
3181 * @return The resultant certificate view with issued-to, issued-by,
3182 * issued-on, expires-on, and possibly other fields set.
3183 * If the input certificate is null, returns null.
3184 */
3185 private View inflateCertificateView(SslCertificate certificate) {
3186 if (certificate == null) {
3187 return null;
3188 }
3189
3190 LayoutInflater factory = LayoutInflater.from(this);
3191
3192 View certificateView = factory.inflate(
3193 R.layout.ssl_certificate, null);
3194
3195 // issued to:
3196 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3197 if (issuedTo != null) {
3198 ((TextView) certificateView.findViewById(R.id.to_common))
3199 .setText(issuedTo.getCName());
3200 ((TextView) certificateView.findViewById(R.id.to_org))
3201 .setText(issuedTo.getOName());
3202 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3203 .setText(issuedTo.getUName());
3204 }
3205
3206 // issued by:
3207 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3208 if (issuedBy != null) {
3209 ((TextView) certificateView.findViewById(R.id.by_common))
3210 .setText(issuedBy.getCName());
3211 ((TextView) certificateView.findViewById(R.id.by_org))
3212 .setText(issuedBy.getOName());
3213 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3214 .setText(issuedBy.getUName());
3215 }
3216
3217 // issued on:
3218 String issuedOn = reformatCertificateDate(
3219 certificate.getValidNotBefore());
3220 ((TextView) certificateView.findViewById(R.id.issued_on))
3221 .setText(issuedOn);
3222
3223 // expires on:
3224 String expiresOn = reformatCertificateDate(
3225 certificate.getValidNotAfter());
3226 ((TextView) certificateView.findViewById(R.id.expires_on))
3227 .setText(expiresOn);
3228
3229 return certificateView;
3230 }
3231
3232 /**
3233 * Re-formats the certificate date (Date.toString()) string to
3234 * a properly localized date string.
3235 * @return Properly localized version of the certificate date string and
3236 * the original certificate date string if fails to localize.
3237 * If the original string is null, returns an empty string "".
3238 */
3239 private String reformatCertificateDate(String certificateDate) {
3240 String reformattedDate = null;
3241
3242 if (certificateDate != null) {
3243 Date date = null;
3244 try {
3245 date = java.text.DateFormat.getInstance().parse(certificateDate);
3246 } catch (ParseException e) {
3247 date = null;
3248 }
3249
3250 if (date != null) {
3251 reformattedDate =
3252 DateFormat.getDateFormat(this).format(date);
3253 }
3254 }
3255
3256 return reformattedDate != null ? reformattedDate :
3257 (certificateDate != null ? certificateDate : "");
3258 }
3259
3260 /**
3261 * Displays an http-authentication dialog.
3262 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003263 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003264 final String host, final String realm, final String title,
3265 final String name, final String password, int focusId) {
3266 LayoutInflater factory = LayoutInflater.from(this);
3267 final View v = factory
3268 .inflate(R.layout.http_authentication, null);
3269 if (name != null) {
3270 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3271 }
3272 if (password != null) {
3273 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3274 }
3275
3276 String titleText = title;
3277 if (titleText == null) {
3278 titleText = getText(R.string.sign_in_to).toString().replace(
3279 "%s1", host).replace("%s2", realm);
3280 }
3281
3282 mHttpAuthHandler = handler;
3283 AlertDialog dialog = new AlertDialog.Builder(this)
3284 .setTitle(titleText)
3285 .setIcon(android.R.drawable.ic_dialog_alert)
3286 .setView(v)
3287 .setPositiveButton(R.string.action,
3288 new DialogInterface.OnClickListener() {
3289 public void onClick(DialogInterface dialog,
3290 int whichButton) {
3291 String nm = ((EditText) v
3292 .findViewById(R.id.username_edit))
3293 .getText().toString();
3294 String pw = ((EditText) v
3295 .findViewById(R.id.password_edit))
3296 .getText().toString();
3297 BrowserActivity.this.setHttpAuthUsernamePassword
3298 (host, realm, nm, pw);
3299 handler.proceed(nm, pw);
3300 mHttpAuthenticationDialog = null;
3301 mHttpAuthHandler = null;
3302 }})
3303 .setNegativeButton(R.string.cancel,
3304 new DialogInterface.OnClickListener() {
3305 public void onClick(DialogInterface dialog,
3306 int whichButton) {
3307 handler.cancel();
3308 BrowserActivity.this.resetTitleAndRevertLockIcon();
3309 mHttpAuthenticationDialog = null;
3310 mHttpAuthHandler = null;
3311 }})
3312 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3313 public void onCancel(DialogInterface dialog) {
3314 handler.cancel();
3315 BrowserActivity.this.resetTitleAndRevertLockIcon();
3316 mHttpAuthenticationDialog = null;
3317 mHttpAuthHandler = null;
3318 }})
3319 .create();
3320 // Make the IME appear when the dialog is displayed if applicable.
3321 dialog.getWindow().setSoftInputMode(
3322 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3323 dialog.show();
3324 if (focusId != 0) {
3325 dialog.findViewById(focusId).requestFocus();
3326 } else {
3327 v.findViewById(R.id.username_edit).requestFocus();
3328 }
3329 mHttpAuthenticationDialog = dialog;
3330 }
3331
3332 public int getProgress() {
3333 WebView w = mTabControl.getCurrentWebView();
3334 if (w != null) {
3335 return w.getProgress();
3336 } else {
3337 return 100;
3338 }
3339 }
3340
3341 /**
3342 * Set HTTP authentication password.
3343 *
3344 * @param host The host for the password
3345 * @param realm The realm for the password
3346 * @param username The username for the password. If it is null, it means
3347 * password can't be saved.
3348 * @param password The password
3349 */
3350 public void setHttpAuthUsernamePassword(String host, String realm,
3351 String username,
3352 String password) {
3353 WebView w = mTabControl.getCurrentWebView();
3354 if (w != null) {
3355 w.setHttpAuthUsernamePassword(host, realm, username, password);
3356 }
3357 }
3358
3359 /**
3360 * connectivity manager says net has come or gone... inform the user
3361 * @param up true if net has come up, false if net has gone down
3362 */
3363 public void onNetworkToggle(boolean up) {
3364 if (up == mIsNetworkUp) {
3365 return;
3366 } else if (up) {
3367 mIsNetworkUp = true;
3368 if (mAlertDialog != null) {
3369 mAlertDialog.cancel();
3370 mAlertDialog = null;
3371 }
3372 } else {
3373 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003374 if (mInLoad) {
3375 createAndShowNetworkDialog();
3376 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003377 }
3378 WebView w = mTabControl.getCurrentWebView();
3379 if (w != null) {
3380 w.setNetworkAvailable(up);
3381 }
3382 }
3383
Grace Kloba22ac16e2009-10-07 18:00:23 -07003384 boolean isNetworkUp() {
3385 return mIsNetworkUp;
3386 }
3387
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003388 // This method shows the network dialog alerting the user that the net is
3389 // down. It will only show the dialog if mAlertDialog is null.
3390 private void createAndShowNetworkDialog() {
3391 if (mAlertDialog == null) {
3392 mAlertDialog = new AlertDialog.Builder(this)
3393 .setTitle(R.string.loadSuspendedTitle)
3394 .setMessage(R.string.loadSuspended)
3395 .setPositiveButton(R.string.ok, null)
3396 .show();
3397 }
3398 }
3399
The Android Open Source Project0c908882009-03-03 19:32:16 -08003400 @Override
3401 protected void onActivityResult(int requestCode, int resultCode,
3402 Intent intent) {
3403 switch (requestCode) {
3404 case COMBO_PAGE:
3405 if (resultCode == RESULT_OK && intent != null) {
3406 String data = intent.getAction();
3407 Bundle extras = intent.getExtras();
3408 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003409 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003410 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003411 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003412 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003413 dismissSubWindow(currentTab);
3414 if (data != null && data.length() != 0) {
3415 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003416 }
3417 }
3418 }
3419 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003420 // Choose a file from the file picker.
3421 case FILE_SELECTED:
3422 if (null == mUploadMessage) break;
3423 Uri result = intent == null || resultCode != RESULT_OK ? null
3424 : intent.getData();
3425 mUploadMessage.onReceiveValue(result);
3426 mUploadMessage = null;
3427 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003428 default:
3429 break;
3430 }
Leon Scroggins30444232009-09-04 18:36:20 -04003431 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003432 }
3433
3434 /*
3435 * This method is called as a result of the user selecting the options
3436 * menu to see the download window, or when a download changes state. It
3437 * shows the download window ontop of the current window.
3438 */
3439 /* package */ void viewDownloads(Uri downloadRecord) {
3440 Intent intent = new Intent(this,
3441 BrowserDownloadPage.class);
3442 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003443 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003444
3445 }
3446
Leon Scroggins160a7e72009-08-14 18:28:01 -04003447 /**
3448 * Open the Go page.
3449 * @param startWithHistory If true, open starting on the history tab.
3450 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003451 */
Leon Scroggins30444232009-09-04 18:36:20 -04003452 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003453 WebView current = mTabControl.getCurrentWebView();
3454 if (current == null) {
3455 return;
3456 }
3457 Intent intent = new Intent(this,
3458 CombinedBookmarkHistoryActivity.class);
3459 String title = current.getTitle();
3460 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003461 Bitmap thumbnail = createScreenshot(current);
3462
The Android Open Source Project0c908882009-03-03 19:32:16 -08003463 // Just in case the user opens bookmarks before a page finishes loading
3464 // so the current history item, and therefore the page, is null.
3465 if (null == url) {
3466 url = mLastEnteredUrl;
3467 // This can happen.
3468 if (null == url) {
3469 url = mSettings.getHomePage();
3470 }
3471 }
3472 // In case the web page has not yet received its associated title.
3473 if (title == null) {
3474 title = url;
3475 }
3476 intent.putExtra("title", title);
3477 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003478 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003479 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003480 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003481 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003482 if (startWithHistory) {
3483 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3484 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3485 }
3486 startActivityForResult(intent, COMBO_PAGE);
3487 }
3488
3489 // Called when loading from context menu or LOAD_URL message
3490 private void loadURL(WebView view, String url) {
3491 // In case the user enters nothing.
3492 if (url != null && url.length() != 0 && view != null) {
3493 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003494 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003495 view.loadUrl(url);
3496 }
3497 }
3498 }
3499
The Android Open Source Project0c908882009-03-03 19:32:16 -08003500 private String smartUrlFilter(Uri inUri) {
3501 if (inUri != null) {
3502 return smartUrlFilter(inUri.toString());
3503 }
3504 return null;
3505 }
3506
Feng Qianb34f87a2009-03-24 21:27:26 -07003507 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003508 "(?i)" + // switch on case insensitive matching
3509 "(" + // begin group for schema
3510 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003511 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003512 ")" +
3513 "(.*)" );
3514
3515 /**
3516 * Attempts to determine whether user input is a URL or search
3517 * terms. Anything with a space is passed to search.
3518 *
3519 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3520 * "Http://" converts to "http://"
3521 *
3522 * @return Original or modified URL
3523 *
3524 */
3525 String smartUrlFilter(String url) {
3526
3527 String inUrl = url.trim();
3528 boolean hasSpace = inUrl.indexOf(' ') != -1;
3529
3530 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3531 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003532 // force scheme to lowercase
3533 String scheme = matcher.group(1);
3534 String lcScheme = scheme.toLowerCase();
3535 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003536 inUrl = lcScheme + matcher.group(2);
3537 }
3538 if (hasSpace) {
3539 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003540 }
3541 return inUrl;
3542 }
3543 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003544 // FIXME: Is this the correct place to add to searches?
3545 // what if someone else calls this function?
3546 int shortcut = parseUrlShortcut(inUrl);
3547 if (shortcut != SHORTCUT_INVALID) {
3548 Browser.addSearchUrl(mResolver, inUrl);
3549 String query = inUrl.substring(2);
3550 switch (shortcut) {
3551 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003552 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003553 case SHORTCUT_WIKIPEDIA_SEARCH:
3554 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3555 case SHORTCUT_DICTIONARY_SEARCH:
3556 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3557 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003558 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003559 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003560 }
3561 }
3562 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003563 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003564 return URLUtil.guessUrl(inUrl);
3565 }
3566 }
3567
3568 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003569 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003570 }
3571
Ben Murdochbff2d602009-07-01 20:19:05 +01003572 /* package */ void setShouldShowErrorConsole(boolean flag) {
3573 if (flag == mShouldShowErrorConsole) {
3574 // Nothing to do.
3575 return;
3576 }
3577
3578 mShouldShowErrorConsole = flag;
3579
Grace Kloba22ac16e2009-10-07 18:00:23 -07003580 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3581 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003582
3583 if (flag) {
3584 // Setting the show state of the console will cause it's the layout to be inflated.
3585 if (errorConsole.numberOfErrors() > 0) {
3586 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3587 } else {
3588 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3589 }
3590
3591 // Now we can add it to the main view.
3592 mErrorConsoleContainer.addView(errorConsole,
3593 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
3594 ViewGroup.LayoutParams.WRAP_CONTENT));
3595 } else {
3596 mErrorConsoleContainer.removeView(errorConsole);
3597 }
3598
3599 }
3600
Grace Kloba22ac16e2009-10-07 18:00:23 -07003601 boolean shouldShowErrorConsole() {
3602 return mShouldShowErrorConsole;
3603 }
3604
Andrei Popescu163ab742009-10-20 17:58:23 +01003605 private void setStatusBarVisibility(boolean visible) {
3606 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3607 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3608 }
3609
Grace Klobaeb6eef42009-09-15 17:56:32 -07003610 final static int LOCK_ICON_UNSECURE = 0;
3611 final static int LOCK_ICON_SECURE = 1;
3612 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003613
The Android Open Source Project0c908882009-03-03 19:32:16 -08003614 private BrowserSettings mSettings;
3615 private TabControl mTabControl;
3616 private ContentResolver mResolver;
3617 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003618 private View mCustomView;
3619 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003620 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003621
3622 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3623 // view, we should rewrite this.
3624 private int mCurrentMenuState = 0;
3625 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003626 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003627 private static final int EMPTY_MENU = -1;
3628 private Menu mMenu;
3629
3630 private FindDialog mFindDialog;
3631 // Used to prevent chording to result in firing two shortcuts immediately
3632 // one after another. Fixes bug 1211714.
3633 boolean mCanChord;
3634
3635 private boolean mInLoad;
3636 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003637 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003638
The Android Open Source Project0c908882009-03-03 19:32:16 -08003639 private boolean mActivityInPause = true;
3640
3641 private boolean mMenuIsDown;
3642
The Android Open Source Project0c908882009-03-03 19:32:16 -08003643 private static boolean mInTrace;
3644
3645 // Performance probe
3646 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3647 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3648 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3649 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3650 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3651 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3652 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3653 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3654 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3655 };
3656
3657 private long mStart;
3658 private long mProcessStart;
3659 private long mUserStart;
3660 private long mSystemStart;
3661 private long mIdleStart;
3662 private long mIrqStart;
3663
3664 private long mUiStart;
3665
3666 private Drawable mMixLockIcon;
3667 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003668
3669 /* hold a ref so we can auto-cancel if necessary */
3670 private AlertDialog mAlertDialog;
3671
3672 // Wait for credentials before loading google.com
3673 private ProgressDialog mCredsDlg;
3674
3675 // The up-to-date URL and title (these can be different from those stored
3676 // in WebView, since it takes some time for the information in WebView to
3677 // get updated)
3678 private String mUrl;
3679 private String mTitle;
3680
3681 // As PageInfo has different style for landscape / portrait, we have
3682 // to re-open it when configuration changed
3683 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003684 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003685 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3686 // dialog, we should not just dismiss it, but should get back to the
3687 // SSL-certificate-on-error dialog. This flag is used to store this state
3688 private Boolean mPageInfoFromShowSSLCertificateOnError;
3689
3690 // as SSLCertificateOnError has different style for landscape / portrait,
3691 // we have to re-open it when configuration changed
3692 private AlertDialog mSSLCertificateOnErrorDialog;
3693 private WebView mSSLCertificateOnErrorView;
3694 private SslErrorHandler mSSLCertificateOnErrorHandler;
3695 private SslError mSSLCertificateOnErrorError;
3696
3697 // as SSLCertificate has different style for landscape / portrait, we
3698 // have to re-open it when configuration changed
3699 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003700 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003701
3702 // as HttpAuthentication has different style for landscape / portrait, we
3703 // have to re-open it when configuration changed
3704 private AlertDialog mHttpAuthenticationDialog;
3705 private HttpAuthHandler mHttpAuthHandler;
3706
3707 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3708 new FrameLayout.LayoutParams(
3709 ViewGroup.LayoutParams.FILL_PARENT,
3710 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003711 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3712 new FrameLayout.LayoutParams(
3713 ViewGroup.LayoutParams.FILL_PARENT,
3714 ViewGroup.LayoutParams.FILL_PARENT,
3715 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003716 // Google search
3717 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003718 // Wikipedia search
3719 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3720 // Dictionary search
3721 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3722 // Google Mobile Local search
3723 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3724
3725 final static String QUERY_PLACE_HOLDER = "%s";
3726
3727 // "source" parameter for Google search through search key
3728 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3729 // "source" parameter for Google search through goto menu
3730 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3731 // "source" parameter for Google search through simplily type
3732 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3733 // "source" parameter for Google search suggested by the browser
3734 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3735 // "source" parameter for Google search from unknown source
3736 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3737
3738 private final static String LOGTAG = "browser";
3739
The Android Open Source Project0c908882009-03-03 19:32:16 -08003740 private String mLastEnteredUrl;
3741
3742 private PowerManager.WakeLock mWakeLock;
3743 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3744
3745 private Toast mStopToast;
3746
Leon Scroggins68579392009-09-15 15:31:54 -04003747 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003748
Ben Murdochbff2d602009-07-01 20:19:05 +01003749 private LinearLayout mErrorConsoleContainer = null;
3750 private boolean mShouldShowErrorConsole = false;
3751
The Android Open Source Project0c908882009-03-03 19:32:16 -08003752 // As the ids are dynamically created, we can't guarantee that they will
3753 // be in sequence, so this static array maps ids to a window number.
3754 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3755 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3756 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3757 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3758
3759 // monitor platform changes
3760 private IntentFilter mNetworkStateChangedFilter;
3761 private BroadcastReceiver mNetworkStateIntentReceiver;
3762
Grace Klobab4da0ad2009-05-14 14:45:40 -07003763 private BroadcastReceiver mPackageInstallationReceiver;
3764
The Android Open Source Project0c908882009-03-03 19:32:16 -08003765 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003766 final static int COMBO_PAGE = 1;
3767 final static int DOWNLOAD_PAGE = 2;
3768 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003769 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003770
Andrei Popescu540035d2009-09-18 18:59:20 +01003771 // the default <video> poster
3772 private Bitmap mDefaultVideoPoster;
3773 // the video progress view
3774 private View mVideoProgressView;
3775
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003776 /**
3777 * A UrlData class to abstract how the content will be set to WebView.
3778 * This base class uses loadUrl to show the content.
3779 */
3780 private static class UrlData {
3781 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07003782 byte[] mPostData;
3783
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003784 UrlData(String url) {
3785 this.mUrl = url;
3786 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003787
3788 void setPostData(byte[] postData) {
3789 mPostData = postData;
3790 }
3791
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003792 boolean isEmpty() {
3793 return mUrl == null || mUrl.length() == 0;
3794 }
3795
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003796 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07003797 if (mPostData != null) {
3798 webView.postUrl(mUrl, mPostData);
3799 } else {
3800 webView.loadUrl(mUrl);
3801 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003802 }
3803 };
3804
3805 /**
3806 * A subclass of UrlData class that can display inlined content using
3807 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
3808 */
3809 private static class InlinedUrlData extends UrlData {
3810 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
3811 super(failUrl);
3812 mInlined = inlined;
3813 mMimeType = mimeType;
3814 mEncoding = encoding;
3815 }
3816 String mMimeType;
3817 String mInlined;
3818 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003819 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003820 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01003821 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003822 }
3823
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003824 @Override
3825 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003826 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
3827 }
3828 }
3829
Leon Scroggins1f005d32009-08-10 17:36:42 -04003830 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003831}