blob: a3a871db610acfc1d18011b3c4187ad4f187b77b [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");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002226 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002227 if (url == null || url.length() == 0) {
2228 break;
2229 }
2230 HashMap focusNodeMap = (HashMap) msg.obj;
2231 WebView view = (WebView) focusNodeMap.get("webview");
2232 // Only apply the action if the top window did not change.
2233 if (getTopWindow() != view) {
2234 break;
2235 }
2236 switch (msg.arg1) {
2237 case R.id.open_context_menu_id:
2238 case R.id.view_image_context_menu_id:
2239 loadURL(getTopWindow(), url);
2240 break;
2241 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002242 final Tab parent = mTabControl.getCurrentTab();
2243 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002244 if (newTab != parent) {
2245 parent.addChildTab(newTab);
2246 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002247 break;
2248 case R.id.bookmark_context_menu_id:
2249 Intent intent = new Intent(BrowserActivity.this,
2250 AddBookmarkPage.class);
2251 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002252 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002253 startActivity(intent);
2254 break;
2255 case R.id.share_link_context_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01002256 Browser.sendString(BrowserActivity.this, url,
2257 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002258 break;
2259 case R.id.copy_link_context_menu_id:
2260 copy(url);
2261 break;
2262 case R.id.save_link_context_menu_id:
2263 case R.id.download_context_menu_id:
2264 onDownloadStartNoStream(url, null, null, null, -1);
2265 break;
2266 }
2267 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002268 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002269
2270 case LOAD_URL:
2271 loadURL(getTopWindow(), (String) msg.obj);
2272 break;
2273
2274 case STOP_LOAD:
2275 stopLoading();
2276 break;
2277
2278 case CANCEL_CREDS_REQUEST:
2279 resumeAfterCredentials();
2280 break;
2281
The Android Open Source Project0c908882009-03-03 19:32:16 -08002282 case RELEASE_WAKELOCK:
2283 if (mWakeLock.isHeld()) {
2284 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002285 // if we reach here, Browser should be still in the
2286 // background loading after WAKELOCK_TIMEOUT (5-min).
2287 // To avoid burning the battery, stop loading.
2288 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002289 }
2290 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002291
2292 case UPDATE_BOOKMARK_THUMBNAIL:
2293 WebView view = (WebView) msg.obj;
2294 if (view != null) {
2295 updateScreenshot(view);
2296 }
2297 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002298 }
2299 }
2300 };
2301
Leon Scroggins89c6d362009-07-15 16:54:37 -04002302 private void updateScreenshot(WebView view) {
2303 // If this is a bookmarked site, add a screenshot to the database.
2304 // FIXME: When should we update? Every time?
2305 // FIXME: Would like to make sure there is actually something to
2306 // draw, but the API for that (WebViewCore.pictureReady()) is not
2307 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002308
Patrick Scott3918d442009-08-04 13:22:29 -04002309 ContentResolver cr = getContentResolver();
2310 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002311 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002312 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002313 boolean succeed = c.moveToFirst();
2314 ContentValues values = null;
2315 while (succeed) {
2316 if (values == null) {
2317 final ByteArrayOutputStream os
2318 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002319 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002320 if (bm == null) {
2321 c.close();
2322 return;
2323 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002324 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2325 values = new ContentValues();
2326 values.put(Browser.BookmarkColumns.THUMBNAIL,
2327 os.toByteArray());
2328 }
2329 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2330 c.getInt(0)), values, null, null);
2331 succeed = c.moveToNext();
2332 }
2333 c.close();
2334 }
2335 }
2336
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002337 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002338 * Values for the size of the thumbnail created when taking a screenshot.
2339 * Lazily initialized. Instead of using these directly, use
2340 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002341 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002342 private static int THUMBNAIL_WIDTH = 0;
2343 private static int THUMBNAIL_HEIGHT = 0;
2344
2345 /**
2346 * Return the desired width for thumbnail screenshots, which are stored in
2347 * the database, and used on the bookmarks screen.
2348 * @param context Context for finding out the density of the screen.
2349 * @return int desired width for thumbnail screenshot.
2350 */
2351 /* package */ static int getDesiredThumbnailWidth(Context context) {
2352 if (THUMBNAIL_WIDTH == 0) {
2353 float density = context.getResources().getDisplayMetrics().density;
2354 THUMBNAIL_WIDTH = (int) (90 * density);
2355 THUMBNAIL_HEIGHT = (int) (80 * density);
2356 }
2357 return THUMBNAIL_WIDTH;
2358 }
2359
2360 /**
2361 * Return the desired height for thumbnail screenshots, which are stored in
2362 * the database, and used on the bookmarks screen.
2363 * @param context Context for finding out the density of the screen.
2364 * @return int desired height for thumbnail screenshot.
2365 */
2366 /* package */ static int getDesiredThumbnailHeight(Context context) {
2367 // To ensure that they are both initialized.
2368 getDesiredThumbnailWidth(context);
2369 return THUMBNAIL_HEIGHT;
2370 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002371
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002372 private Bitmap createScreenshot(WebView view) {
2373 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002374 if (thumbnail == null) {
2375 return null;
2376 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002377 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2378 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002379 Canvas canvas = new Canvas(bm);
2380 // May need to tweak these values to determine what is the
2381 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002382 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002383 int thumbnailHeight = thumbnail.getHeight();
2384 float scaleFactorX = 1.0f;
2385 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002386 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002387 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002388 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002389 } else {
2390 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002391 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002392
2393 if (view.getWidth() > view.getHeight() &&
2394 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2395 // If the device is in landscape and the page is shorter
2396 // than the height of the view, stretch the thumbnail to fill the
2397 // space.
2398 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2399 (float)thumbnailHeight;
2400 } else {
2401 // In the portrait case, this looks nice.
2402 scaleFactorY = scaleFactorX;
2403 }
2404
2405 canvas.scale(scaleFactorX, scaleFactorY);
2406
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002407 thumbnail.draw(canvas);
2408 return bm;
2409 }
2410
The Android Open Source Project0c908882009-03-03 19:32:16 -08002411 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002412 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002413 //-------------------------------------------------------------------------
2414
2415 // Use in overrideUrlLoading
2416 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2417 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2418 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2419 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2420
Grace Kloba22ac16e2009-10-07 18:00:23 -07002421 void onPageStarted(WebView view, String url, Bitmap favicon) {
2422 // when BrowserActivity just starts, onPageStarted may be called before
2423 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2424 // to start the timer. As we won't switch tabs while an activity is in
2425 // pause state, we can ensure calling resume and pause in pair.
2426 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002427
Grace Kloba22ac16e2009-10-07 18:00:23 -07002428 resetLockIcon(url);
2429 setUrlTitle(url, null);
2430 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002431 // Keep this initial progress in sync with initialProgressValue (* 100)
2432 // in ProgressTracker.cpp
2433 // Show some progress so that the user knows the page is beginning to
2434 // load
2435 onProgressChanged(view, 10);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002436 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002437 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002438
Grace Kloba22ac16e2009-10-07 18:00:23 -07002439 if (mSettings.isTracing()) {
2440 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002441 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002442 WebAddress uri = new WebAddress(url);
2443 host = uri.mHost;
2444 } catch (android.net.ParseException ex) {
2445 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002446 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002447 host = host.replace('.', '_');
2448 host += ".trace";
2449 mInTrace = true;
2450 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2451 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002452
Grace Kloba22ac16e2009-10-07 18:00:23 -07002453 // Performance probe
2454 if (false) {
2455 mStart = SystemClock.uptimeMillis();
2456 mProcessStart = Process.getElapsedCpuTime();
2457 long[] sysCpu = new long[7];
2458 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2459 sysCpu, null)) {
2460 mUserStart = sysCpu[0] + sysCpu[1];
2461 mSystemStart = sysCpu[2];
2462 mIdleStart = sysCpu[3];
2463 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2464 }
2465 mUiStart = SystemClock.currentThreadTimeMillis();
2466 }
2467 }
2468
2469 void onPageFinished(WebView view, String url) {
2470 // Reset the title and icon in case we stopped a provisional load.
2471 resetTitleAndIcon(view);
2472 // Update the lock icon image only once we are done loading
2473 updateLockIconToLatest();
2474 // pause the WebView timer and release the wake lock if it is finished
2475 // while BrowserActivity is in pause state.
2476 if (mActivityInPause && pauseWebViewTimers()) {
2477 if (mWakeLock.isHeld()) {
2478 mHandler.removeMessages(RELEASE_WAKELOCK);
2479 mWakeLock.release();
2480 }
2481 }
2482
2483 // Performance probe
2484 if (false) {
2485 long[] sysCpu = new long[7];
2486 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2487 sysCpu, null)) {
2488 String uiInfo = "UI thread used "
2489 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2490 + " ms";
2491 if (LOGD_ENABLED) {
2492 Log.d(LOGTAG, uiInfo);
2493 }
2494 //The string that gets written to the log
2495 String performanceString = "It took total "
2496 + (SystemClock.uptimeMillis() - mStart)
2497 + " ms clock time to load the page."
2498 + "\nbrowser process used "
2499 + (Process.getElapsedCpuTime() - mProcessStart)
2500 + " ms, user processes used "
2501 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2502 + " ms, kernel used "
2503 + (sysCpu[2] - mSystemStart) * 10
2504 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2505 + " ms and irq took "
2506 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2507 * 10 + " ms, " + uiInfo;
2508 if (LOGD_ENABLED) {
2509 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2510 }
2511 if (url != null) {
2512 // strip the url to maintain consistency
2513 String newUrl = new String(url);
2514 if (newUrl.startsWith("http://www.")) {
2515 newUrl = newUrl.substring(11);
2516 } else if (newUrl.startsWith("http://")) {
2517 newUrl = newUrl.substring(7);
2518 } else if (newUrl.startsWith("https://www.")) {
2519 newUrl = newUrl.substring(12);
2520 } else if (newUrl.startsWith("https://")) {
2521 newUrl = newUrl.substring(8);
2522 }
2523 if (LOGD_ENABLED) {
2524 Log.d(LOGTAG, newUrl + " loaded");
2525 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002526 }
2527 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002528 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002529
Grace Kloba22ac16e2009-10-07 18:00:23 -07002530 if (mInTrace) {
2531 mInTrace = false;
2532 Debug.stopMethodTracing();
2533 }
2534 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002535
Grace Kloba22ac16e2009-10-07 18:00:23 -07002536 boolean shouldOverrideUrlLoading(WebView view, String url) {
2537 if (url.startsWith(SCHEME_WTAI)) {
2538 // wtai://wp/mc;number
2539 // number=string(phone-number)
2540 if (url.startsWith(SCHEME_WTAI_MC)) {
2541 Intent intent = new Intent(Intent.ACTION_VIEW,
2542 Uri.parse(WebView.SCHEME_TEL +
2543 url.substring(SCHEME_WTAI_MC.length())));
2544 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002545 return true;
2546 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002547 // wtai://wp/sd;dtmf
2548 // dtmf=string(dialstring)
2549 if (url.startsWith(SCHEME_WTAI_SD)) {
2550 // TODO: only send when there is active voice connection
2551 return false;
2552 }
2553 // wtai://wp/ap;number;name
2554 // number=string(phone-number)
2555 // name=string
2556 if (url.startsWith(SCHEME_WTAI_AP)) {
2557 // TODO
2558 return false;
2559 }
2560 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002561
Grace Kloba22ac16e2009-10-07 18:00:23 -07002562 // The "about:" schemes are internal to the browser; don't want these to
2563 // be dispatched to other apps.
2564 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002565 return false;
2566 }
2567
Grace Kloba22ac16e2009-10-07 18:00:23 -07002568 Intent intent;
2569 // perform generic parsing of the URI to turn it into an Intent.
2570 try {
2571 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2572 } catch (URISyntaxException ex) {
2573 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2574 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002575 }
2576
Grace Kloba22ac16e2009-10-07 18:00:23 -07002577 // check whether the intent can be resolved. If not, we will see
2578 // whether we can download it from the Market.
2579 if (getPackageManager().resolveActivity(intent, 0) == null) {
2580 String packagename = intent.getPackage();
2581 if (packagename != null) {
2582 intent = new Intent(Intent.ACTION_VIEW, Uri
2583 .parse("market://search?q=pname:" + packagename));
2584 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2585 startActivity(intent);
2586 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002587 } else {
2588 return false;
2589 }
2590 }
2591
Grace Kloba22ac16e2009-10-07 18:00:23 -07002592 // sanitize the Intent, ensuring web pages can not bypass browser
2593 // security (only access to BROWSABLE activities).
2594 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2595 intent.setComponent(null);
2596 try {
2597 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002598 return true;
2599 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002600 } catch (ActivityNotFoundException ex) {
2601 // ignore the error. If no application can handle the URL,
2602 // eg about:blank, assume the browser can handle it.
2603 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002604
Grace Kloba22ac16e2009-10-07 18:00:23 -07002605 if (mMenuIsDown) {
2606 openTab(url);
2607 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002608 return true;
2609 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002610 return false;
2611 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002612
Grace Kloba22ac16e2009-10-07 18:00:23 -07002613 // -------------------------------------------------------------------------
2614 // Helper function for WebChromeClient
2615 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002616
Grace Kloba22ac16e2009-10-07 18:00:23 -07002617 void onProgressChanged(WebView view, int newProgress) {
2618 mTitleBar.setProgress(newProgress);
2619 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002620
Grace Kloba22ac16e2009-10-07 18:00:23 -07002621 if (newProgress == 100) {
2622 // onProgressChanged() may continue to be called after the main
2623 // frame has finished loading, as any remaining sub frames continue
2624 // to load. We'll only get called once though with newProgress as
2625 // 100 when everything is loaded. (onPageFinished is called once
2626 // when the main frame completes loading regardless of the state of
2627 // any sub frames so calls to onProgressChanges may continue after
2628 // onPageFinished has executed)
2629 if (mInLoad) {
2630 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002631 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002632 // If the options menu is open, leave the title bar
2633 if (!mOptionsMenuOpen || !mIconView) {
2634 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002635 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002636 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002637 } else if (!mInLoad) {
2638 // onPageFinished may have already been called but a subframe is
2639 // still loading and updating the progress. Reset mInLoad and update
2640 // the menu items.
2641 mInLoad = true;
2642 updateInLoadMenuItems();
2643 if (!mOptionsMenuOpen || mIconView) {
2644 // This page has begun to load, so show the title bar
2645 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002646 }
2647 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002648 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002649
Grace Kloba22ac16e2009-10-07 18:00:23 -07002650 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2651 if (mCustomView != null)
2652 return;
2653
2654 // Add the custom view to its container.
2655 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2656 mCustomView = view;
2657 mCustomViewCallback = callback;
2658 // Save the menu state and set it to empty while the custom
2659 // view is showing.
2660 mOldMenuState = mMenuState;
2661 mMenuState = EMPTY_MENU;
2662 // Hide the content view.
2663 mContentView.setVisibility(View.GONE);
2664 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002665 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002666 mCustomViewContainer.setVisibility(View.VISIBLE);
2667 mCustomViewContainer.bringToFront();
2668 }
2669
2670 void onHideCustomView() {
2671 if (mCustomView == null)
2672 return;
2673
2674 // Hide the custom view.
2675 mCustomView.setVisibility(View.GONE);
2676 // Remove the custom view from its container.
2677 mCustomViewContainer.removeView(mCustomView);
2678 mCustomView = null;
2679 // Reset the old menu state.
2680 mMenuState = mOldMenuState;
2681 mOldMenuState = EMPTY_MENU;
2682 mCustomViewContainer.setVisibility(View.GONE);
2683 mCustomViewCallback.onCustomViewHidden();
2684 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002685 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002686 mContentView.setVisibility(View.VISIBLE);
2687 }
2688
2689 Bitmap getDefaultVideoPoster() {
2690 if (mDefaultVideoPoster == null) {
2691 mDefaultVideoPoster = BitmapFactory.decodeResource(
2692 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002693 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002694 return mDefaultVideoPoster;
2695 }
Patrick Scott3918d442009-08-04 13:22:29 -04002696
Grace Kloba22ac16e2009-10-07 18:00:23 -07002697 View getVideoLoadingProgressView() {
2698 if (mVideoProgressView == null) {
2699 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2700 mVideoProgressView = inflater.inflate(
2701 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002702 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002703 return mVideoProgressView;
2704 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002705
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002706 /*
2707 * The Object used to inform the WebView of the file to upload.
2708 */
2709 private ValueCallback<Uri> mUploadMessage;
2710
Grace Kloba22ac16e2009-10-07 18:00:23 -07002711 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2712 if (mUploadMessage != null) return;
2713 mUploadMessage = uploadMsg;
2714 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2715 i.addCategory(Intent.CATEGORY_OPENABLE);
2716 i.setType("*/*");
2717 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2718 getString(R.string.choose_upload)), FILE_SELECTED);
2719 }
2720
2721 // -------------------------------------------------------------------------
2722 // Implement functions for DownloadListener
2723 // -------------------------------------------------------------------------
2724
The Android Open Source Project0c908882009-03-03 19:32:16 -08002725 /**
2726 * Notify the host application a download should be done, or that
2727 * the data should be streamed if a streaming viewer is available.
2728 * @param url The full url to the content that should be downloaded
2729 * @param contentDisposition Content-disposition http header, if
2730 * present.
2731 * @param mimetype The mimetype of the content reported by the server
2732 * @param contentLength The file size reported by the server
2733 */
2734 public void onDownloadStart(String url, String userAgent,
2735 String contentDisposition, String mimetype, long contentLength) {
2736 // if we're dealing wih A/V content that's not explicitly marked
2737 // for download, check if it's streamable.
2738 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002739 || !contentDisposition.regionMatches(
2740 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002741 // query the package manager to see if there's a registered handler
2742 // that matches.
2743 Intent intent = new Intent(Intent.ACTION_VIEW);
2744 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002745 ResolveInfo info = getPackageManager().resolveActivity(intent,
2746 PackageManager.MATCH_DEFAULT_ONLY);
2747 if (info != null) {
2748 ComponentName myName = getComponentName();
2749 // If we resolved to ourselves, we don't want to attempt to
2750 // load the url only to try and download it again.
2751 if (!myName.getPackageName().equals(
2752 info.activityInfo.packageName)
2753 || !myName.getClassName().equals(
2754 info.activityInfo.name)) {
2755 // someone (other than us) knows how to handle this mime
2756 // type with this scheme, don't download.
2757 try {
2758 startActivity(intent);
2759 return;
2760 } catch (ActivityNotFoundException ex) {
2761 if (LOGD_ENABLED) {
2762 Log.d(LOGTAG, "activity not found for " + mimetype
2763 + " over " + Uri.parse(url).getScheme(),
2764 ex);
2765 }
2766 // Best behavior is to fall back to a download in this
2767 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002768 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002769 }
2770 }
2771 }
2772 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2773 }
2774
2775 /**
2776 * Notify the host application a download should be done, even if there
2777 * is a streaming viewer available for thise type.
2778 * @param url The full url to the content that should be downloaded
2779 * @param contentDisposition Content-disposition http header, if
2780 * present.
2781 * @param mimetype The mimetype of the content reported by the server
2782 * @param contentLength The file size reported by the server
2783 */
2784 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2785 String contentDisposition, String mimetype, long contentLength) {
2786
2787 String filename = URLUtil.guessFileName(url,
2788 contentDisposition, mimetype);
2789
2790 // Check to see if we have an SDCard
2791 String status = Environment.getExternalStorageState();
2792 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2793 int title;
2794 String msg;
2795
2796 // Check to see if the SDCard is busy, same as the music app
2797 if (status.equals(Environment.MEDIA_SHARED)) {
2798 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2799 title = R.string.download_sdcard_busy_dlg_title;
2800 } else {
2801 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2802 title = R.string.download_no_sdcard_dlg_title;
2803 }
2804
2805 new AlertDialog.Builder(this)
2806 .setTitle(title)
2807 .setIcon(android.R.drawable.ic_dialog_alert)
2808 .setMessage(msg)
2809 .setPositiveButton(R.string.ok, null)
2810 .show();
2811 return;
2812 }
2813
2814 // java.net.URI is a lot stricter than KURL so we have to undo
2815 // KURL's percent-encoding and redo the encoding using java.net.URI.
2816 URI uri = null;
2817 try {
2818 // Undo the percent-encoding that KURL may have done.
2819 String newUrl = new String(URLUtil.decode(url.getBytes()));
2820 // Parse the url into pieces
2821 WebAddress w = new WebAddress(newUrl);
2822 String frag = null;
2823 String query = null;
2824 String path = w.mPath;
2825 // Break the path into path, query, and fragment
2826 if (path.length() > 0) {
2827 // Strip the fragment
2828 int idx = path.lastIndexOf('#');
2829 if (idx != -1) {
2830 frag = path.substring(idx + 1);
2831 path = path.substring(0, idx);
2832 }
2833 idx = path.lastIndexOf('?');
2834 if (idx != -1) {
2835 query = path.substring(idx + 1);
2836 path = path.substring(0, idx);
2837 }
2838 }
2839 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2840 query, frag);
2841 } catch (Exception e) {
2842 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2843 return;
2844 }
2845
2846 // XXX: Have to use the old url since the cookies were stored using the
2847 // old percent-encoded url.
2848 String cookies = CookieManager.getInstance().getCookie(url);
2849
2850 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002851 values.put(Downloads.COLUMN_URI, uri.toString());
2852 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
2853 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
2854 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002855 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002856 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002857 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002858 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2859 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
2860 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
2861 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002862 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002863 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002864 }
2865 if (mimetype == null) {
2866 // We must have long pressed on a link or image to download it. We
2867 // are not sure of the mimetype in this case, so do a head request
2868 new FetchUrlMimeType(this).execute(values);
2869 } else {
2870 final Uri contentUri =
2871 getContentResolver().insert(Downloads.CONTENT_URI, values);
2872 viewDownloads(contentUri);
2873 }
2874
2875 }
2876
Grace Kloba22ac16e2009-10-07 18:00:23 -07002877 // -------------------------------------------------------------------------
2878
The Android Open Source Project0c908882009-03-03 19:32:16 -08002879 /**
2880 * Resets the lock icon. This method is called when we start a new load and
2881 * know the url to be loaded.
2882 */
2883 private void resetLockIcon(String url) {
2884 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002885 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002886 updateLockIconImage(LOCK_ICON_UNSECURE);
2887 }
2888
The Android Open Source Project0c908882009-03-03 19:32:16 -08002889 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002890 * Update the lock icon to correspond to our latest state.
2891 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002892 private void updateLockIconToLatest() {
2893 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002894 }
2895
2896 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002897 * Updates the lock-icon image in the title-bar.
2898 */
2899 private void updateLockIconImage(int lockIconType) {
2900 Drawable d = null;
2901 if (lockIconType == LOCK_ICON_SECURE) {
2902 d = mSecLockIcon;
2903 } else if (lockIconType == LOCK_ICON_MIXED) {
2904 d = mMixLockIcon;
2905 }
Leon Scroggins68579392009-09-15 15:31:54 -04002906 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002907 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002908 }
2909
2910 /**
2911 * Displays a page-info dialog.
2912 * @param tab The tab to show info about
2913 * @param fromShowSSLCertificateOnError The flag that indicates whether
2914 * this dialog was opened from the SSL-certificate-on-error dialog or
2915 * not. This is important, since we need to know whether to return to
2916 * the parent dialog or simply dismiss.
2917 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002918 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002919 final boolean fromShowSSLCertificateOnError) {
2920 final LayoutInflater factory = LayoutInflater
2921 .from(this);
2922
2923 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2924
2925 final WebView view = tab.getWebView();
2926
2927 String url = null;
2928 String title = null;
2929
2930 if (view == null) {
2931 url = tab.getUrl();
2932 title = tab.getTitle();
2933 } else if (view == mTabControl.getCurrentWebView()) {
2934 // Use the cached title and url if this is the current WebView
2935 url = mUrl;
2936 title = mTitle;
2937 } else {
2938 url = view.getUrl();
2939 title = view.getTitle();
2940 }
2941
2942 if (url == null) {
2943 url = "";
2944 }
2945 if (title == null) {
2946 title = "";
2947 }
2948
2949 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
2950 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
2951
2952 mPageInfoView = tab;
2953 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
2954
2955 AlertDialog.Builder alertDialogBuilder =
2956 new AlertDialog.Builder(this)
2957 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
2958 .setView(pageInfoView)
2959 .setPositiveButton(
2960 R.string.ok,
2961 new DialogInterface.OnClickListener() {
2962 public void onClick(DialogInterface dialog,
2963 int whichButton) {
2964 mPageInfoDialog = null;
2965 mPageInfoView = null;
2966 mPageInfoFromShowSSLCertificateOnError = null;
2967
2968 // if we came here from the SSL error dialog
2969 if (fromShowSSLCertificateOnError) {
2970 // go back to the SSL error dialog
2971 showSSLCertificateOnError(
2972 mSSLCertificateOnErrorView,
2973 mSSLCertificateOnErrorHandler,
2974 mSSLCertificateOnErrorError);
2975 }
2976 }
2977 })
2978 .setOnCancelListener(
2979 new DialogInterface.OnCancelListener() {
2980 public void onCancel(DialogInterface dialog) {
2981 mPageInfoDialog = null;
2982 mPageInfoView = null;
2983 mPageInfoFromShowSSLCertificateOnError = null;
2984
2985 // if we came here from the SSL error dialog
2986 if (fromShowSSLCertificateOnError) {
2987 // go back to the SSL error dialog
2988 showSSLCertificateOnError(
2989 mSSLCertificateOnErrorView,
2990 mSSLCertificateOnErrorHandler,
2991 mSSLCertificateOnErrorError);
2992 }
2993 }
2994 });
2995
2996 // if we have a main top-level page SSL certificate set or a certificate
2997 // error
2998 if (fromShowSSLCertificateOnError ||
2999 (view != null && view.getCertificate() != null)) {
3000 // add a 'View Certificate' button
3001 alertDialogBuilder.setNeutralButton(
3002 R.string.view_certificate,
3003 new DialogInterface.OnClickListener() {
3004 public void onClick(DialogInterface dialog,
3005 int whichButton) {
3006 mPageInfoDialog = null;
3007 mPageInfoView = null;
3008 mPageInfoFromShowSSLCertificateOnError = null;
3009
3010 // if we came here from the SSL error dialog
3011 if (fromShowSSLCertificateOnError) {
3012 // go back to the SSL error dialog
3013 showSSLCertificateOnError(
3014 mSSLCertificateOnErrorView,
3015 mSSLCertificateOnErrorHandler,
3016 mSSLCertificateOnErrorError);
3017 } else {
3018 // otherwise, display the top-most certificate from
3019 // the chain
3020 if (view.getCertificate() != null) {
3021 showSSLCertificate(tab);
3022 }
3023 }
3024 }
3025 });
3026 }
3027
3028 mPageInfoDialog = alertDialogBuilder.show();
3029 }
3030
3031 /**
3032 * Displays the main top-level page SSL certificate dialog
3033 * (accessible from the Page-Info dialog).
3034 * @param tab The tab to show certificate for.
3035 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003036 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003037 final View certificateView =
3038 inflateCertificateView(tab.getWebView().getCertificate());
3039 if (certificateView == null) {
3040 return;
3041 }
3042
3043 LayoutInflater factory = LayoutInflater.from(this);
3044
3045 final LinearLayout placeholder =
3046 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3047
3048 LinearLayout ll = (LinearLayout) factory.inflate(
3049 R.layout.ssl_success, placeholder);
3050 ((TextView)ll.findViewById(R.id.success))
3051 .setText(R.string.ssl_certificate_is_valid);
3052
3053 mSSLCertificateView = tab;
3054 mSSLCertificateDialog =
3055 new AlertDialog.Builder(this)
3056 .setTitle(R.string.ssl_certificate).setIcon(
3057 R.drawable.ic_dialog_browser_certificate_secure)
3058 .setView(certificateView)
3059 .setPositiveButton(R.string.ok,
3060 new DialogInterface.OnClickListener() {
3061 public void onClick(DialogInterface dialog,
3062 int whichButton) {
3063 mSSLCertificateDialog = null;
3064 mSSLCertificateView = null;
3065
3066 showPageInfo(tab, false);
3067 }
3068 })
3069 .setOnCancelListener(
3070 new DialogInterface.OnCancelListener() {
3071 public void onCancel(DialogInterface dialog) {
3072 mSSLCertificateDialog = null;
3073 mSSLCertificateView = null;
3074
3075 showPageInfo(tab, false);
3076 }
3077 })
3078 .show();
3079 }
3080
3081 /**
3082 * Displays the SSL error certificate dialog.
3083 * @param view The target web-view.
3084 * @param handler The SSL error handler responsible for cancelling the
3085 * connection that resulted in an SSL error or proceeding per user request.
3086 * @param error The SSL error object.
3087 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003088 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003089 final WebView view, final SslErrorHandler handler, final SslError error) {
3090
3091 final View certificateView =
3092 inflateCertificateView(error.getCertificate());
3093 if (certificateView == null) {
3094 return;
3095 }
3096
3097 LayoutInflater factory = LayoutInflater.from(this);
3098
3099 final LinearLayout placeholder =
3100 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3101
3102 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3103 LinearLayout ll = (LinearLayout)factory
3104 .inflate(R.layout.ssl_warning, placeholder);
3105 ((TextView)ll.findViewById(R.id.warning))
3106 .setText(R.string.ssl_untrusted);
3107 }
3108
3109 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3110 LinearLayout ll = (LinearLayout)factory
3111 .inflate(R.layout.ssl_warning, placeholder);
3112 ((TextView)ll.findViewById(R.id.warning))
3113 .setText(R.string.ssl_mismatch);
3114 }
3115
3116 if (error.hasError(SslError.SSL_EXPIRED)) {
3117 LinearLayout ll = (LinearLayout)factory
3118 .inflate(R.layout.ssl_warning, placeholder);
3119 ((TextView)ll.findViewById(R.id.warning))
3120 .setText(R.string.ssl_expired);
3121 }
3122
3123 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3124 LinearLayout ll = (LinearLayout)factory
3125 .inflate(R.layout.ssl_warning, placeholder);
3126 ((TextView)ll.findViewById(R.id.warning))
3127 .setText(R.string.ssl_not_yet_valid);
3128 }
3129
3130 mSSLCertificateOnErrorHandler = handler;
3131 mSSLCertificateOnErrorView = view;
3132 mSSLCertificateOnErrorError = error;
3133 mSSLCertificateOnErrorDialog =
3134 new AlertDialog.Builder(this)
3135 .setTitle(R.string.ssl_certificate).setIcon(
3136 R.drawable.ic_dialog_browser_certificate_partially_secure)
3137 .setView(certificateView)
3138 .setPositiveButton(R.string.ok,
3139 new DialogInterface.OnClickListener() {
3140 public void onClick(DialogInterface dialog,
3141 int whichButton) {
3142 mSSLCertificateOnErrorDialog = null;
3143 mSSLCertificateOnErrorView = null;
3144 mSSLCertificateOnErrorHandler = null;
3145 mSSLCertificateOnErrorError = null;
3146
Grace Kloba22ac16e2009-10-07 18:00:23 -07003147 view.getWebViewClient().onReceivedSslError(
3148 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003149 }
3150 })
3151 .setNeutralButton(R.string.page_info_view,
3152 new DialogInterface.OnClickListener() {
3153 public void onClick(DialogInterface dialog,
3154 int whichButton) {
3155 mSSLCertificateOnErrorDialog = null;
3156
3157 // do not clear the dialog state: we will
3158 // need to show the dialog again once the
3159 // user is done exploring the page-info details
3160
3161 showPageInfo(mTabControl.getTabFromView(view),
3162 true);
3163 }
3164 })
3165 .setOnCancelListener(
3166 new DialogInterface.OnCancelListener() {
3167 public void onCancel(DialogInterface dialog) {
3168 mSSLCertificateOnErrorDialog = null;
3169 mSSLCertificateOnErrorView = null;
3170 mSSLCertificateOnErrorHandler = null;
3171 mSSLCertificateOnErrorError = null;
3172
Grace Kloba22ac16e2009-10-07 18:00:23 -07003173 view.getWebViewClient().onReceivedSslError(
3174 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003175 }
3176 })
3177 .show();
3178 }
3179
3180 /**
3181 * Inflates the SSL certificate view (helper method).
3182 * @param certificate The SSL certificate.
3183 * @return The resultant certificate view with issued-to, issued-by,
3184 * issued-on, expires-on, and possibly other fields set.
3185 * If the input certificate is null, returns null.
3186 */
3187 private View inflateCertificateView(SslCertificate certificate) {
3188 if (certificate == null) {
3189 return null;
3190 }
3191
3192 LayoutInflater factory = LayoutInflater.from(this);
3193
3194 View certificateView = factory.inflate(
3195 R.layout.ssl_certificate, null);
3196
3197 // issued to:
3198 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3199 if (issuedTo != null) {
3200 ((TextView) certificateView.findViewById(R.id.to_common))
3201 .setText(issuedTo.getCName());
3202 ((TextView) certificateView.findViewById(R.id.to_org))
3203 .setText(issuedTo.getOName());
3204 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3205 .setText(issuedTo.getUName());
3206 }
3207
3208 // issued by:
3209 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3210 if (issuedBy != null) {
3211 ((TextView) certificateView.findViewById(R.id.by_common))
3212 .setText(issuedBy.getCName());
3213 ((TextView) certificateView.findViewById(R.id.by_org))
3214 .setText(issuedBy.getOName());
3215 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3216 .setText(issuedBy.getUName());
3217 }
3218
3219 // issued on:
3220 String issuedOn = reformatCertificateDate(
3221 certificate.getValidNotBefore());
3222 ((TextView) certificateView.findViewById(R.id.issued_on))
3223 .setText(issuedOn);
3224
3225 // expires on:
3226 String expiresOn = reformatCertificateDate(
3227 certificate.getValidNotAfter());
3228 ((TextView) certificateView.findViewById(R.id.expires_on))
3229 .setText(expiresOn);
3230
3231 return certificateView;
3232 }
3233
3234 /**
3235 * Re-formats the certificate date (Date.toString()) string to
3236 * a properly localized date string.
3237 * @return Properly localized version of the certificate date string and
3238 * the original certificate date string if fails to localize.
3239 * If the original string is null, returns an empty string "".
3240 */
3241 private String reformatCertificateDate(String certificateDate) {
3242 String reformattedDate = null;
3243
3244 if (certificateDate != null) {
3245 Date date = null;
3246 try {
3247 date = java.text.DateFormat.getInstance().parse(certificateDate);
3248 } catch (ParseException e) {
3249 date = null;
3250 }
3251
3252 if (date != null) {
3253 reformattedDate =
3254 DateFormat.getDateFormat(this).format(date);
3255 }
3256 }
3257
3258 return reformattedDate != null ? reformattedDate :
3259 (certificateDate != null ? certificateDate : "");
3260 }
3261
3262 /**
3263 * Displays an http-authentication dialog.
3264 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003265 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003266 final String host, final String realm, final String title,
3267 final String name, final String password, int focusId) {
3268 LayoutInflater factory = LayoutInflater.from(this);
3269 final View v = factory
3270 .inflate(R.layout.http_authentication, null);
3271 if (name != null) {
3272 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3273 }
3274 if (password != null) {
3275 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3276 }
3277
3278 String titleText = title;
3279 if (titleText == null) {
3280 titleText = getText(R.string.sign_in_to).toString().replace(
3281 "%s1", host).replace("%s2", realm);
3282 }
3283
3284 mHttpAuthHandler = handler;
3285 AlertDialog dialog = new AlertDialog.Builder(this)
3286 .setTitle(titleText)
3287 .setIcon(android.R.drawable.ic_dialog_alert)
3288 .setView(v)
3289 .setPositiveButton(R.string.action,
3290 new DialogInterface.OnClickListener() {
3291 public void onClick(DialogInterface dialog,
3292 int whichButton) {
3293 String nm = ((EditText) v
3294 .findViewById(R.id.username_edit))
3295 .getText().toString();
3296 String pw = ((EditText) v
3297 .findViewById(R.id.password_edit))
3298 .getText().toString();
3299 BrowserActivity.this.setHttpAuthUsernamePassword
3300 (host, realm, nm, pw);
3301 handler.proceed(nm, pw);
3302 mHttpAuthenticationDialog = null;
3303 mHttpAuthHandler = null;
3304 }})
3305 .setNegativeButton(R.string.cancel,
3306 new DialogInterface.OnClickListener() {
3307 public void onClick(DialogInterface dialog,
3308 int whichButton) {
3309 handler.cancel();
3310 BrowserActivity.this.resetTitleAndRevertLockIcon();
3311 mHttpAuthenticationDialog = null;
3312 mHttpAuthHandler = null;
3313 }})
3314 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3315 public void onCancel(DialogInterface dialog) {
3316 handler.cancel();
3317 BrowserActivity.this.resetTitleAndRevertLockIcon();
3318 mHttpAuthenticationDialog = null;
3319 mHttpAuthHandler = null;
3320 }})
3321 .create();
3322 // Make the IME appear when the dialog is displayed if applicable.
3323 dialog.getWindow().setSoftInputMode(
3324 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3325 dialog.show();
3326 if (focusId != 0) {
3327 dialog.findViewById(focusId).requestFocus();
3328 } else {
3329 v.findViewById(R.id.username_edit).requestFocus();
3330 }
3331 mHttpAuthenticationDialog = dialog;
3332 }
3333
3334 public int getProgress() {
3335 WebView w = mTabControl.getCurrentWebView();
3336 if (w != null) {
3337 return w.getProgress();
3338 } else {
3339 return 100;
3340 }
3341 }
3342
3343 /**
3344 * Set HTTP authentication password.
3345 *
3346 * @param host The host for the password
3347 * @param realm The realm for the password
3348 * @param username The username for the password. If it is null, it means
3349 * password can't be saved.
3350 * @param password The password
3351 */
3352 public void setHttpAuthUsernamePassword(String host, String realm,
3353 String username,
3354 String password) {
3355 WebView w = mTabControl.getCurrentWebView();
3356 if (w != null) {
3357 w.setHttpAuthUsernamePassword(host, realm, username, password);
3358 }
3359 }
3360
3361 /**
3362 * connectivity manager says net has come or gone... inform the user
3363 * @param up true if net has come up, false if net has gone down
3364 */
3365 public void onNetworkToggle(boolean up) {
3366 if (up == mIsNetworkUp) {
3367 return;
3368 } else if (up) {
3369 mIsNetworkUp = true;
3370 if (mAlertDialog != null) {
3371 mAlertDialog.cancel();
3372 mAlertDialog = null;
3373 }
3374 } else {
3375 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003376 if (mInLoad) {
3377 createAndShowNetworkDialog();
3378 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003379 }
3380 WebView w = mTabControl.getCurrentWebView();
3381 if (w != null) {
3382 w.setNetworkAvailable(up);
3383 }
3384 }
3385
Grace Kloba22ac16e2009-10-07 18:00:23 -07003386 boolean isNetworkUp() {
3387 return mIsNetworkUp;
3388 }
3389
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003390 // This method shows the network dialog alerting the user that the net is
3391 // down. It will only show the dialog if mAlertDialog is null.
3392 private void createAndShowNetworkDialog() {
3393 if (mAlertDialog == null) {
3394 mAlertDialog = new AlertDialog.Builder(this)
3395 .setTitle(R.string.loadSuspendedTitle)
3396 .setMessage(R.string.loadSuspended)
3397 .setPositiveButton(R.string.ok, null)
3398 .show();
3399 }
3400 }
3401
The Android Open Source Project0c908882009-03-03 19:32:16 -08003402 @Override
3403 protected void onActivityResult(int requestCode, int resultCode,
3404 Intent intent) {
3405 switch (requestCode) {
3406 case COMBO_PAGE:
3407 if (resultCode == RESULT_OK && intent != null) {
3408 String data = intent.getAction();
3409 Bundle extras = intent.getExtras();
3410 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003411 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003412 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003413 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003414 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003415 dismissSubWindow(currentTab);
3416 if (data != null && data.length() != 0) {
3417 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003418 }
3419 }
3420 }
3421 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003422 // Choose a file from the file picker.
3423 case FILE_SELECTED:
3424 if (null == mUploadMessage) break;
3425 Uri result = intent == null || resultCode != RESULT_OK ? null
3426 : intent.getData();
3427 mUploadMessage.onReceiveValue(result);
3428 mUploadMessage = null;
3429 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003430 default:
3431 break;
3432 }
Leon Scroggins30444232009-09-04 18:36:20 -04003433 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003434 }
3435
3436 /*
3437 * This method is called as a result of the user selecting the options
3438 * menu to see the download window, or when a download changes state. It
3439 * shows the download window ontop of the current window.
3440 */
3441 /* package */ void viewDownloads(Uri downloadRecord) {
3442 Intent intent = new Intent(this,
3443 BrowserDownloadPage.class);
3444 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003445 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003446
3447 }
3448
Leon Scroggins160a7e72009-08-14 18:28:01 -04003449 /**
3450 * Open the Go page.
3451 * @param startWithHistory If true, open starting on the history tab.
3452 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003453 */
Leon Scroggins30444232009-09-04 18:36:20 -04003454 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003455 WebView current = mTabControl.getCurrentWebView();
3456 if (current == null) {
3457 return;
3458 }
3459 Intent intent = new Intent(this,
3460 CombinedBookmarkHistoryActivity.class);
3461 String title = current.getTitle();
3462 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003463 Bitmap thumbnail = createScreenshot(current);
3464
The Android Open Source Project0c908882009-03-03 19:32:16 -08003465 // Just in case the user opens bookmarks before a page finishes loading
3466 // so the current history item, and therefore the page, is null.
3467 if (null == url) {
3468 url = mLastEnteredUrl;
3469 // This can happen.
3470 if (null == url) {
3471 url = mSettings.getHomePage();
3472 }
3473 }
3474 // In case the web page has not yet received its associated title.
3475 if (title == null) {
3476 title = url;
3477 }
3478 intent.putExtra("title", title);
3479 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003480 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003481 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003482 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003483 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003484 if (startWithHistory) {
3485 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3486 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3487 }
3488 startActivityForResult(intent, COMBO_PAGE);
3489 }
3490
3491 // Called when loading from context menu or LOAD_URL message
3492 private void loadURL(WebView view, String url) {
3493 // In case the user enters nothing.
3494 if (url != null && url.length() != 0 && view != null) {
3495 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003496 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003497 view.loadUrl(url);
3498 }
3499 }
3500 }
3501
The Android Open Source Project0c908882009-03-03 19:32:16 -08003502 private String smartUrlFilter(Uri inUri) {
3503 if (inUri != null) {
3504 return smartUrlFilter(inUri.toString());
3505 }
3506 return null;
3507 }
3508
Feng Qianb34f87a2009-03-24 21:27:26 -07003509 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003510 "(?i)" + // switch on case insensitive matching
3511 "(" + // begin group for schema
3512 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003513 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003514 ")" +
3515 "(.*)" );
3516
3517 /**
3518 * Attempts to determine whether user input is a URL or search
3519 * terms. Anything with a space is passed to search.
3520 *
3521 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3522 * "Http://" converts to "http://"
3523 *
3524 * @return Original or modified URL
3525 *
3526 */
3527 String smartUrlFilter(String url) {
3528
3529 String inUrl = url.trim();
3530 boolean hasSpace = inUrl.indexOf(' ') != -1;
3531
3532 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3533 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003534 // force scheme to lowercase
3535 String scheme = matcher.group(1);
3536 String lcScheme = scheme.toLowerCase();
3537 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003538 inUrl = lcScheme + matcher.group(2);
3539 }
3540 if (hasSpace) {
3541 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003542 }
3543 return inUrl;
3544 }
3545 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003546 // FIXME: Is this the correct place to add to searches?
3547 // what if someone else calls this function?
3548 int shortcut = parseUrlShortcut(inUrl);
3549 if (shortcut != SHORTCUT_INVALID) {
3550 Browser.addSearchUrl(mResolver, inUrl);
3551 String query = inUrl.substring(2);
3552 switch (shortcut) {
3553 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003554 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003555 case SHORTCUT_WIKIPEDIA_SEARCH:
3556 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3557 case SHORTCUT_DICTIONARY_SEARCH:
3558 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3559 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003560 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003561 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003562 }
3563 }
3564 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003565 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003566 return URLUtil.guessUrl(inUrl);
3567 }
3568 }
3569
3570 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003571 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003572 }
3573
Ben Murdochbff2d602009-07-01 20:19:05 +01003574 /* package */ void setShouldShowErrorConsole(boolean flag) {
3575 if (flag == mShouldShowErrorConsole) {
3576 // Nothing to do.
3577 return;
3578 }
3579
3580 mShouldShowErrorConsole = flag;
3581
Grace Kloba22ac16e2009-10-07 18:00:23 -07003582 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3583 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003584
3585 if (flag) {
3586 // Setting the show state of the console will cause it's the layout to be inflated.
3587 if (errorConsole.numberOfErrors() > 0) {
3588 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3589 } else {
3590 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3591 }
3592
3593 // Now we can add it to the main view.
3594 mErrorConsoleContainer.addView(errorConsole,
3595 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
3596 ViewGroup.LayoutParams.WRAP_CONTENT));
3597 } else {
3598 mErrorConsoleContainer.removeView(errorConsole);
3599 }
3600
3601 }
3602
Grace Kloba22ac16e2009-10-07 18:00:23 -07003603 boolean shouldShowErrorConsole() {
3604 return mShouldShowErrorConsole;
3605 }
3606
Andrei Popescu163ab742009-10-20 17:58:23 +01003607 private void setStatusBarVisibility(boolean visible) {
3608 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3609 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3610 }
3611
Grace Klobaeb6eef42009-09-15 17:56:32 -07003612 final static int LOCK_ICON_UNSECURE = 0;
3613 final static int LOCK_ICON_SECURE = 1;
3614 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003615
The Android Open Source Project0c908882009-03-03 19:32:16 -08003616 private BrowserSettings mSettings;
3617 private TabControl mTabControl;
3618 private ContentResolver mResolver;
3619 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003620 private View mCustomView;
3621 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003622 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003623
3624 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3625 // view, we should rewrite this.
3626 private int mCurrentMenuState = 0;
3627 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003628 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003629 private static final int EMPTY_MENU = -1;
3630 private Menu mMenu;
3631
3632 private FindDialog mFindDialog;
3633 // Used to prevent chording to result in firing two shortcuts immediately
3634 // one after another. Fixes bug 1211714.
3635 boolean mCanChord;
3636
3637 private boolean mInLoad;
3638 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003639 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003640
The Android Open Source Project0c908882009-03-03 19:32:16 -08003641 private boolean mActivityInPause = true;
3642
3643 private boolean mMenuIsDown;
3644
The Android Open Source Project0c908882009-03-03 19:32:16 -08003645 private static boolean mInTrace;
3646
3647 // Performance probe
3648 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3649 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3650 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3651 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3652 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3653 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3654 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3655 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3656 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3657 };
3658
3659 private long mStart;
3660 private long mProcessStart;
3661 private long mUserStart;
3662 private long mSystemStart;
3663 private long mIdleStart;
3664 private long mIrqStart;
3665
3666 private long mUiStart;
3667
3668 private Drawable mMixLockIcon;
3669 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003670
3671 /* hold a ref so we can auto-cancel if necessary */
3672 private AlertDialog mAlertDialog;
3673
3674 // Wait for credentials before loading google.com
3675 private ProgressDialog mCredsDlg;
3676
3677 // The up-to-date URL and title (these can be different from those stored
3678 // in WebView, since it takes some time for the information in WebView to
3679 // get updated)
3680 private String mUrl;
3681 private String mTitle;
3682
3683 // As PageInfo has different style for landscape / portrait, we have
3684 // to re-open it when configuration changed
3685 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003686 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003687 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3688 // dialog, we should not just dismiss it, but should get back to the
3689 // SSL-certificate-on-error dialog. This flag is used to store this state
3690 private Boolean mPageInfoFromShowSSLCertificateOnError;
3691
3692 // as SSLCertificateOnError has different style for landscape / portrait,
3693 // we have to re-open it when configuration changed
3694 private AlertDialog mSSLCertificateOnErrorDialog;
3695 private WebView mSSLCertificateOnErrorView;
3696 private SslErrorHandler mSSLCertificateOnErrorHandler;
3697 private SslError mSSLCertificateOnErrorError;
3698
3699 // as SSLCertificate has different style for landscape / portrait, we
3700 // have to re-open it when configuration changed
3701 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003702 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003703
3704 // as HttpAuthentication has different style for landscape / portrait, we
3705 // have to re-open it when configuration changed
3706 private AlertDialog mHttpAuthenticationDialog;
3707 private HttpAuthHandler mHttpAuthHandler;
3708
3709 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3710 new FrameLayout.LayoutParams(
3711 ViewGroup.LayoutParams.FILL_PARENT,
3712 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003713 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3714 new FrameLayout.LayoutParams(
3715 ViewGroup.LayoutParams.FILL_PARENT,
3716 ViewGroup.LayoutParams.FILL_PARENT,
3717 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003718 // Google search
3719 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003720 // Wikipedia search
3721 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3722 // Dictionary search
3723 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3724 // Google Mobile Local search
3725 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3726
3727 final static String QUERY_PLACE_HOLDER = "%s";
3728
3729 // "source" parameter for Google search through search key
3730 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3731 // "source" parameter for Google search through goto menu
3732 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3733 // "source" parameter for Google search through simplily type
3734 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3735 // "source" parameter for Google search suggested by the browser
3736 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3737 // "source" parameter for Google search from unknown source
3738 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3739
3740 private final static String LOGTAG = "browser";
3741
The Android Open Source Project0c908882009-03-03 19:32:16 -08003742 private String mLastEnteredUrl;
3743
3744 private PowerManager.WakeLock mWakeLock;
3745 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3746
3747 private Toast mStopToast;
3748
Leon Scroggins68579392009-09-15 15:31:54 -04003749 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003750
Ben Murdochbff2d602009-07-01 20:19:05 +01003751 private LinearLayout mErrorConsoleContainer = null;
3752 private boolean mShouldShowErrorConsole = false;
3753
The Android Open Source Project0c908882009-03-03 19:32:16 -08003754 // As the ids are dynamically created, we can't guarantee that they will
3755 // be in sequence, so this static array maps ids to a window number.
3756 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3757 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3758 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3759 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3760
3761 // monitor platform changes
3762 private IntentFilter mNetworkStateChangedFilter;
3763 private BroadcastReceiver mNetworkStateIntentReceiver;
3764
Grace Klobab4da0ad2009-05-14 14:45:40 -07003765 private BroadcastReceiver mPackageInstallationReceiver;
3766
The Android Open Source Project0c908882009-03-03 19:32:16 -08003767 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003768 final static int COMBO_PAGE = 1;
3769 final static int DOWNLOAD_PAGE = 2;
3770 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003771 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003772
Andrei Popescu540035d2009-09-18 18:59:20 +01003773 // the default <video> poster
3774 private Bitmap mDefaultVideoPoster;
3775 // the video progress view
3776 private View mVideoProgressView;
3777
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003778 /**
3779 * A UrlData class to abstract how the content will be set to WebView.
3780 * This base class uses loadUrl to show the content.
3781 */
3782 private static class UrlData {
3783 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07003784 byte[] mPostData;
3785
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003786 UrlData(String url) {
3787 this.mUrl = url;
3788 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003789
3790 void setPostData(byte[] postData) {
3791 mPostData = postData;
3792 }
3793
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003794 boolean isEmpty() {
3795 return mUrl == null || mUrl.length() == 0;
3796 }
3797
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003798 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07003799 if (mPostData != null) {
3800 webView.postUrl(mUrl, mPostData);
3801 } else {
3802 webView.loadUrl(mUrl);
3803 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003804 }
3805 };
3806
3807 /**
3808 * A subclass of UrlData class that can display inlined content using
3809 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
3810 */
3811 private static class InlinedUrlData extends UrlData {
3812 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
3813 super(failUrl);
3814 mInlined = inlined;
3815 mMimeType = mimeType;
3816 mEncoding = encoding;
3817 }
3818 String mMimeType;
3819 String mInlined;
3820 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003821 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003822 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01003823 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003824 }
3825
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003826 @Override
3827 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003828 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
3829 }
3830 }
3831
Leon Scroggins1f005d32009-08-10 17:36:42 -04003832 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003833}