blob: 7c3b3fc66314331e8526d200f57f1df37a40db59 [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 {
Grace Kloba638d3f42009-11-23 10:35:04 -0800524 if (!urlData.isEmpty()
525 && urlData.mUrl.startsWith("about:debug")) {
526 if ("about:debug.dom".equals(urlData.mUrl)) {
527 current.getWebView().dumpDomTree(false);
528 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
529 current.getWebView().dumpDomTree(true);
530 } else if ("about:debug.render".equals(urlData.mUrl)) {
531 current.getWebView().dumpRenderTree(false);
532 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
533 current.getWebView().dumpRenderTree(true);
534 } else if ("about:debug.display".equals(urlData.mUrl)) {
535 current.getWebView().dumpDisplayTree();
536 } else {
537 mSettings.toggleDebugSettings();
538 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800539 return;
540 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400541 // Get rid of the subwindow if it exists
542 dismissSubWindow(current);
543 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800544 }
545 }
546 }
547
Satish Sampath565505b2009-05-29 15:37:27 +0100548 private int parseUrlShortcut(String url) {
549 if (url == null) return SHORTCUT_INVALID;
550
551 // FIXME: quick search, need to be customized by setting
552 if (url.length() > 2 && url.charAt(1) == ' ') {
553 switch (url.charAt(0)) {
554 case 'g': return SHORTCUT_GOOGLE_SEARCH;
555 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
556 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
557 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
558 }
559 }
560 return SHORTCUT_INVALID;
561 }
562
563 /**
564 * Launches the default web search activity with the query parameters if the given intent's data
565 * are identified as plain search terms and not URLs/shortcuts.
566 * @return true if the intent was handled and web search activity was launched, false if not.
567 */
568 private boolean handleWebSearchIntent(Intent intent) {
569 if (intent == null) return false;
570
571 String url = null;
572 final String action = intent.getAction();
573 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700574 Uri data = intent.getData();
575 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100576 } else if (Intent.ACTION_SEARCH.equals(action)
577 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
578 || Intent.ACTION_WEB_SEARCH.equals(action)) {
579 url = intent.getStringExtra(SearchManager.QUERY);
580 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100581 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
582 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100583 }
584
585 /**
586 * Launches the default web search activity with the query parameters if the given url string
587 * was identified as plain search terms and not URL/shortcut.
588 * @return true if the request was handled and web search activity was launched, false if not.
589 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100590 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100591 if (inUrl == null) return false;
592
593 // In general, we shouldn't modify URL from Intent.
594 // But currently, we get the user-typed URL from search box as well.
595 String url = fixUrl(inUrl).trim();
596
597 // URLs and site specific search shortcuts are handled by the regular flow of control, so
598 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800599 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100600 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100601 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
602 return false;
603 }
604
605 Browser.updateVisitedHistory(mResolver, url, false);
606 Browser.addSearchUrl(mResolver, url);
607
608 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
609 intent.addCategory(Intent.CATEGORY_DEFAULT);
610 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100611 if (appData != null) {
612 intent.putExtra(SearchManager.APP_DATA, appData);
613 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100614 if (extraData != null) {
615 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
616 }
Grace Klobacc634032009-07-28 15:58:19 -0700617 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100618 startActivity(intent);
619
620 return true;
621 }
622
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700623 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800624 String url = null;
625 if (intent != null) {
626 final String action = intent.getAction();
627 if (Intent.ACTION_VIEW.equals(action)) {
628 url = smartUrlFilter(intent.getData());
629 if (url != null && url.startsWith("content:")) {
630 /* Append mimetype so webview knows how to display */
631 String mimeType = intent.resolveType(getContentResolver());
632 if (mimeType != null) {
633 url += "?" + mimeType;
634 }
635 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700636 if ("inline:".equals(url)) {
637 return new InlinedUrlData(
638 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
639 intent.getType(),
640 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
641 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
642 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800643 } else if (Intent.ACTION_SEARCH.equals(action)
644 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
645 || Intent.ACTION_WEB_SEARCH.equals(action)) {
646 url = intent.getStringExtra(SearchManager.QUERY);
647 if (url != null) {
648 mLastEnteredUrl = url;
Leon Scrogginsb4464432009-11-25 12:37:50 -0500649 Browser.updateVisitedHistory(mResolver, url, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800650 // In general, we shouldn't modify URL from Intent.
651 // But currently, we get the user-typed URL from search box as well.
652 url = fixUrl(url);
653 url = smartUrlFilter(url);
654 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
655 if (url.contains(searchSource)) {
656 String source = null;
657 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
658 if (appData != null) {
659 source = appData.getString(SearchManager.SOURCE);
660 }
661 if (TextUtils.isEmpty(source)) {
662 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
663 }
664 url = url.replace(searchSource, "&source=android-"+source+"&");
665 }
666 }
667 }
668 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700669 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800670 }
671
672 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400673 // FIXME: Converting the url to lower case
674 // duplicates functionality in smartUrlFilter().
675 // However, changing all current callers of fixUrl to
676 // call smartUrlFilter in addition may have unwanted
677 // consequences, and is deferred for now.
678 int colon = inUrl.indexOf(':');
679 boolean allLower = true;
680 for (int index = 0; index < colon; index++) {
681 char ch = inUrl.charAt(index);
682 if (!Character.isLetter(ch)) {
683 break;
684 }
685 allLower &= Character.isLowerCase(ch);
686 if (index == colon - 1 && !allLower) {
687 inUrl = inUrl.substring(0, colon).toLowerCase()
688 + inUrl.substring(colon);
689 }
690 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800691 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
692 return inUrl;
693 if (inUrl.startsWith("http:") ||
694 inUrl.startsWith("https:")) {
695 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
696 inUrl = inUrl.replaceFirst("/", "//");
697 } else inUrl = inUrl.replaceFirst(":", "://");
698 }
699 return inUrl;
700 }
701
Grace Kloba22ac16e2009-10-07 18:00:23 -0700702 @Override
703 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800704 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700705 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800706 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
707 }
708
709 if (!mActivityInPause) {
710 Log.e(LOGTAG, "BrowserActivity is already resumed.");
711 return;
712 }
713
Mike Reed7bfa63b2009-05-28 11:08:32 -0400714 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800715 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400716 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800717
718 if (mWakeLock.isHeld()) {
719 mHandler.removeMessages(RELEASE_WAKELOCK);
720 mWakeLock.release();
721 }
722
723 if (mCredsDlg != null) {
724 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
725 // In case credential request never comes back
726 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
727 }
728 }
729
730 registerReceiver(mNetworkStateIntentReceiver,
731 mNetworkStateChangedFilter);
732 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800733 }
734
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400735 /**
736 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400737 * would change its appearance, use a different TitleBar to show overlayed
738 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400739 */
740 private TitleBar mFakeTitleBar;
741
742 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400743 * Holder for the fake title bar. It will have a foreground shadow, as well
744 * as a white background, so the fake title bar looks like the real one.
745 */
746 private ViewGroup mFakeTitleBarHolder;
747
748 /**
749 * Layout parameters for the fake title bar within mFakeTitleBarHolder
750 */
751 private FrameLayout.LayoutParams mFakeTitleBarParams
752 = new FrameLayout.LayoutParams(
Leon Scrogginsc01e4a82009-09-16 14:41:00 -0400753 ViewGroup.LayoutParams.FILL_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400754 ViewGroup.LayoutParams.WRAP_CONTENT);
755 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400756 * Keeps track of whether the options menu is open. This is important in
757 * determining whether to show or hide the title bar overlay.
758 */
759 private boolean mOptionsMenuOpen;
760
761 /**
762 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
763 * of whether the configuration has changed. The first onMenuOpened call
764 * after a configuration change is simply a reopening of the same menu
765 * (i.e. mIconView did not change).
766 */
767 private boolean mConfigChanged;
768
769 /**
770 * Whether or not the options menu is in its smaller, icon menu form. When
771 * true, we want the title bar overlay to be up. When false, we do not.
772 * Only meaningful if mOptionsMenuOpen is true.
773 */
774 private boolean mIconView;
775
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400776 @Override
777 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400778 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
779 if (mOptionsMenuOpen) {
780 if (mConfigChanged) {
781 // We do not need to make any changes to the state of the
782 // title bar, since the only thing that happened was a
783 // change in orientation
784 mConfigChanged = false;
785 } else {
786 if (mIconView) {
787 // Switching the menu to expanded view, so hide the
788 // title bar.
789 hideFakeTitleBar();
790 mIconView = false;
791 } else {
792 // Switching the menu back to icon view, so show the
793 // title bar once again.
794 showFakeTitleBar();
795 mIconView = true;
796 }
797 }
798 } else {
799 // The options menu is closed, so open it, and show the title
800 showFakeTitleBar();
801 mOptionsMenuOpen = true;
802 mConfigChanged = false;
803 mIconView = true;
804 }
805 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400806 return true;
807 }
808
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400809 /**
810 * Special class used exclusively for the shadow drawn underneath the fake
811 * title bar. The shadow does not need to be drawn if the WebView
812 * underneath is scrolled to the top, because it will draw directly on top
813 * of the embedded shadow.
814 */
815 private static class Shadow extends View {
816 private WebView mWebView;
817
818 public Shadow(Context context, AttributeSet attrs) {
819 super(context, attrs);
820 }
821
822 public void setWebView(WebView view) {
823 mWebView = view;
824 }
825
826 @Override
827 public void draw(Canvas canvas) {
828 // In general onDraw is the method to override, but we care about
829 // whether or not the background gets drawn, which happens in draw()
830 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
831 super.draw(canvas);
832 }
833 // Need to invalidate so that if the scroll position changes, we
834 // still draw as appropriate.
835 invalidate();
836 }
837 }
838
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400839 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400840 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400841 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400842 && !mActivityInPause && decor != null
843 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400844 Rect visRect = new Rect();
845 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
846 if (LOGD_ENABLED) {
847 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
848 }
849 return;
850 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400851
852 WindowManager manager
853 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
854
855 // Add the title bar to the window manager so it can receive touches
856 // while the menu is up
857 WindowManager.LayoutParams params
858 = new WindowManager.LayoutParams(
859 ViewGroup.LayoutParams.FILL_PARENT,
860 ViewGroup.LayoutParams.WRAP_CONTENT,
861 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
862 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400863 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400864 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400865 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400866 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400867 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400868 // XXX : Without providing an offset, the fake title bar will be
869 // placed underneath the status bar. Use the global visible rect
870 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400871 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400872 // Add a holder for the title bar. It also holds a shadow to show
873 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400874 if (mFakeTitleBarHolder == null) {
875 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
876 .inflate(R.layout.title_bar_bg, null);
877 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400878 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
879 R.id.shadow);
880 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400881 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400882 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400883 }
884 }
885
886 @Override
887 public void onOptionsMenuClosed(Menu menu) {
888 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400889 if (!mInLoad) {
890 hideFakeTitleBar();
891 } else if (!mIconView) {
892 // The page is currently loading, and we are in expanded mode, so
893 // we were not showing the menu. Show it once again. It will be
894 // removed when the page finishes.
895 showFakeTitleBar();
896 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400897 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700898
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400899 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400900 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400901 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
902 mFakeTitleBarHolder.getLayoutParams();
903 WebView mainView = mTabControl.getCurrentWebView();
904 // Although we decided whether or not to animate based on the current
905 // scroll position, the scroll position may have changed since the
906 // fake title bar was displayed. Make sure it has the appropriate
907 // animation/lack thereof before removing.
908 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400909 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400910 WindowManager manager
911 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -0400912 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400913 mFakeTitleBarHolder.removeView(mFakeTitleBar);
914 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400915 }
916
The Android Open Source Project0c908882009-03-03 19:32:16 -0800917 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400918 * Special method for the fake title bar to call when displaying its context
919 * menu, since it is in its own Window, and its parent does not show a
920 * context menu.
921 */
922 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400923 if (null == mTitleBar.getParent()) {
924 return;
925 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400926 openContextMenu(mTitleBar);
927 }
928
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400929 @Override
930 public void onContextMenuClosed(Menu menu) {
931 super.onContextMenuClosed(menu);
932 if (mInLoad) {
933 showFakeTitleBar();
934 }
935 }
936
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400937 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800938 * onSaveInstanceState(Bundle map)
939 * onSaveInstanceState is called right before onStop(). The map contains
940 * the saved state.
941 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700942 @Override
943 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700944 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800945 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
946 }
947 // the default implementation requires each view to have an id. As the
948 // browser handles the state itself and it doesn't use id for the views,
949 // don't call the default implementation. Otherwise it will trigger the
950 // warning like this, "couldn't save which view has focus because the
951 // focused view XXX has no id".
952
953 // Save all the tabs
954 mTabControl.saveState(outState);
955 }
956
Grace Kloba22ac16e2009-10-07 18:00:23 -0700957 @Override
958 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800959 super.onPause();
960
961 if (mActivityInPause) {
962 Log.e(LOGTAG, "BrowserActivity is already paused.");
963 return;
964 }
965
Mike Reed7bfa63b2009-05-28 11:08:32 -0400966 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800967 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400968 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800969 mWakeLock.acquire();
970 mHandler.sendMessageDelayed(mHandler
971 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
972 }
973
974 // Clear the credentials toast if it is up
975 if (mCredsDlg != null && mCredsDlg.isShowing()) {
976 mCredsDlg.dismiss();
977 }
978 mCredsDlg = null;
979
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400980 // FIXME: This removes the active tabs page and resets the menu to
981 // MAIN_MENU. A better solution might be to do this work in onNewIntent
982 // but then we would need to save it in onSaveInstanceState and restore
983 // it in onCreate/onRestoreInstanceState
984 if (mActiveTabsPage != null) {
985 removeActiveTabPage(true);
986 }
987
The Android Open Source Project0c908882009-03-03 19:32:16 -0800988 cancelStopToast();
989
990 // unregister network state listener
991 unregisterReceiver(mNetworkStateIntentReceiver);
992 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800993 }
994
Grace Kloba22ac16e2009-10-07 18:00:23 -0700995 @Override
996 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700997 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800998 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
999 }
1000 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001001
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001002 if (mUploadMessage != null) {
1003 mUploadMessage.onReceiveValue(null);
1004 mUploadMessage = null;
1005 }
1006
Grace Kloba0923d692009-09-23 21:37:25 -07001007 if (mTabControl == null) return;
1008
Grace Kloba1fc98a32009-10-21 13:23:08 -07001009 // Remove the fake title bar if it is there
1010 hideFakeTitleBar();
1011
The Android Open Source Project0c908882009-03-03 19:32:16 -08001012 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001013 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001014 if (t != null) {
1015 dismissSubWindow(t);
1016 removeTabFromContentView(t);
1017 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001018 // Destroy all the tabs
1019 mTabControl.destroy();
1020 WebIconDatabase.getInstance().close();
1021 if (mGlsConnection != null) {
1022 unbindService(mGlsConnection);
1023 mGlsConnection = null;
1024 }
1025
Grace Klobab4da0ad2009-05-14 14:45:40 -07001026 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001027 }
1028
1029 @Override
1030 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001031 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001032 super.onConfigurationChanged(newConfig);
1033
1034 if (mPageInfoDialog != null) {
1035 mPageInfoDialog.dismiss();
1036 showPageInfo(
1037 mPageInfoView,
1038 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1039 }
1040 if (mSSLCertificateDialog != null) {
1041 mSSLCertificateDialog.dismiss();
1042 showSSLCertificate(
1043 mSSLCertificateView);
1044 }
1045 if (mSSLCertificateOnErrorDialog != null) {
1046 mSSLCertificateOnErrorDialog.dismiss();
1047 showSSLCertificateOnError(
1048 mSSLCertificateOnErrorView,
1049 mSSLCertificateOnErrorHandler,
1050 mSSLCertificateOnErrorError);
1051 }
1052 if (mHttpAuthenticationDialog != null) {
1053 String title = ((TextView) mHttpAuthenticationDialog
1054 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1055 .toString();
1056 String name = ((TextView) mHttpAuthenticationDialog
1057 .findViewById(R.id.username_edit)).getText().toString();
1058 String password = ((TextView) mHttpAuthenticationDialog
1059 .findViewById(R.id.password_edit)).getText().toString();
1060 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1061 .getId();
1062 mHttpAuthenticationDialog.dismiss();
1063 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1064 name, password, focusId);
1065 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001066 }
1067
Grace Kloba22ac16e2009-10-07 18:00:23 -07001068 @Override
1069 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001070 super.onLowMemory();
1071 mTabControl.freeMemory();
1072 }
1073
Mike Reed7bfa63b2009-05-28 11:08:32 -04001074 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001075 Tab tab = mTabControl.getCurrentTab();
1076 boolean inLoad = tab.inLoad();
1077 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001078 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001079 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001080 if (w != null) {
1081 w.resumeTimers();
1082 }
1083 return true;
1084 } else {
1085 return false;
1086 }
1087 }
1088
Mike Reed7bfa63b2009-05-28 11:08:32 -04001089 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001090 Tab tab = mTabControl.getCurrentTab();
1091 boolean inLoad = tab.inLoad();
1092 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001093 CookieSyncManager.getInstance().stopSync();
1094 WebView w = mTabControl.getCurrentWebView();
1095 if (w != null) {
1096 w.pauseTimers();
1097 }
1098 return true;
1099 } else {
1100 return false;
1101 }
1102 }
1103
Leon Scroggins1f005d32009-08-10 17:36:42 -04001104 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001105 /*
1106 * This function is called when we are launching for the first time. We
1107 * are waiting for the login credentials before loading Google home
1108 * pages. This way the user will be logged in straight away.
1109 */
1110 private void waitForCredentials() {
1111 // Show a toast
1112 mCredsDlg = new ProgressDialog(this);
1113 mCredsDlg.setIndeterminate(true);
1114 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1115 // If the user cancels the operation, then cancel the Google
1116 // Credentials request.
1117 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1118 mCredsDlg.show();
1119
1120 // We set a timeout for the retrieval of credentials in onResume()
1121 // as that is when we have freed up some CPU time to get
1122 // the login credentials.
1123 }
1124
1125 /*
1126 * If we have received the credentials or we have timed out and we are
1127 * showing the credentials dialog, then it is time to move on.
1128 */
1129 private void resumeAfterCredentials() {
1130 if (mCredsDlg == null) {
1131 return;
1132 }
1133
1134 // Clear the toast
1135 if (mCredsDlg.isShowing()) {
1136 mCredsDlg.dismiss();
1137 }
1138 mCredsDlg = null;
1139
1140 // Clear any pending timeout
1141 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1142
1143 // Load the page
1144 WebView w = mTabControl.getCurrentWebView();
1145 if (w != null) {
1146 w.loadUrl(mSettings.getHomePage());
1147 }
1148
1149 // Update the settings, need to do this last as it can take a moment
1150 // to persist the settings. In the mean time we could be loading
1151 // content.
1152 mSettings.setLoginInitialized(this);
1153 }
1154
1155 // Open the icon database and retain all the icons for visited sites.
1156 private void retainIconsOnStartup() {
1157 final WebIconDatabase db = WebIconDatabase.getInstance();
1158 db.open(getDir("icons", 0).getPath());
1159 try {
1160 Cursor c = Browser.getAllBookmarks(mResolver);
1161 if (!c.moveToFirst()) {
1162 c.deactivate();
1163 return;
1164 }
1165 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1166 do {
1167 String url = c.getString(urlIndex);
1168 db.retainIconForPageUrl(url);
1169 } while (c.moveToNext());
1170 c.deactivate();
1171 } catch (IllegalStateException e) {
1172 Log.e(LOGTAG, "retainIconsOnStartup", e);
1173 }
1174 }
1175
1176 // Helper method for getting the top window.
1177 WebView getTopWindow() {
1178 return mTabControl.getCurrentTopWebView();
1179 }
1180
Grace Kloba22ac16e2009-10-07 18:00:23 -07001181 TabControl getTabControl() {
1182 return mTabControl;
1183 }
1184
The Android Open Source Project0c908882009-03-03 19:32:16 -08001185 @Override
1186 public boolean onCreateOptionsMenu(Menu menu) {
1187 super.onCreateOptionsMenu(menu);
1188
1189 MenuInflater inflater = getMenuInflater();
1190 inflater.inflate(R.menu.browser, menu);
1191 mMenu = menu;
1192 updateInLoadMenuItems();
1193 return true;
1194 }
1195
1196 /**
1197 * As the menu can be open when loading state changes
1198 * we must manually update the state of the stop/reload menu
1199 * item
1200 */
1201 private void updateInLoadMenuItems() {
1202 if (mMenu == null) {
1203 return;
1204 }
1205 MenuItem src = mInLoad ?
1206 mMenu.findItem(R.id.stop_menu_id):
1207 mMenu.findItem(R.id.reload_menu_id);
1208 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1209 dest.setIcon(src.getIcon());
1210 dest.setTitle(src.getTitle());
1211 }
1212
1213 @Override
1214 public boolean onContextItemSelected(MenuItem item) {
1215 // chording is not an issue with context menus, but we use the same
1216 // options selector, so set mCanChord to true so we can access them.
1217 mCanChord = true;
1218 int id = item.getItemId();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001219 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001220 // For the context menu from the title bar
1221 case R.id.title_bar_share_page_url:
1222 case R.id.title_bar_copy_page_url:
1223 WebView mainView = mTabControl.getCurrentWebView();
1224 if (null == mainView) {
1225 return false;
1226 }
1227 if (id == R.id.title_bar_share_page_url) {
1228 Browser.sendString(this, mainView.getUrl());
1229 } else {
1230 copy(mainView.getUrl());
1231 }
1232 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001233 // -- Browser context menu
1234 case R.id.open_context_menu_id:
1235 case R.id.open_newtab_context_menu_id:
1236 case R.id.bookmark_context_menu_id:
1237 case R.id.save_link_context_menu_id:
1238 case R.id.share_link_context_menu_id:
1239 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001240 final WebView webView = getTopWindow();
1241 if (null == webView) {
1242 return false;
1243 }
1244 final HashMap hrefMap = new HashMap();
1245 hrefMap.put("webview", webView);
1246 final Message msg = mHandler.obtainMessage(
1247 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001248 webView.requestFocusNodeHref(msg);
1249 break;
1250
1251 default:
1252 // For other context menus
1253 return onOptionsItemSelected(item);
1254 }
1255 mCanChord = false;
1256 return true;
1257 }
1258
1259 private Bundle createGoogleSearchSourceBundle(String source) {
1260 Bundle bundle = new Bundle();
1261 bundle.putString(SearchManager.SOURCE, source);
1262 return bundle;
1263 }
1264
1265 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001266 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001267 */
1268 @Override
1269 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001270 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001271 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001272 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001273 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001274 return true;
1275 }
1276
1277 @Override
1278 public void startSearch(String initialQuery, boolean selectInitialQuery,
1279 Bundle appSearchData, boolean globalSearch) {
1280 if (appSearchData == null) {
1281 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1282 }
1283 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1284 }
1285
Leon Scroggins1f005d32009-08-10 17:36:42 -04001286 /**
1287 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1288 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001289 * @param index Index of the tab to change to, as defined by
1290 * mTabControl.getTabIndex(Tab t).
1291 * @return boolean True if we successfully switched to a different tab. If
1292 * the indexth tab is null, or if that tab is the same as
1293 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001294 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001295 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001296 Tab tab = mTabControl.getTab(index);
1297 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001298 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001299 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001300 }
1301 if (currentTab != null) {
1302 // currentTab may be null if it was just removed. In that case,
1303 // we do not need to remove it
1304 removeTabFromContentView(currentTab);
1305 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001306 mTabControl.setCurrentTab(tab);
1307 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001308 resetTitleIconAndProgress();
1309 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001310 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001311 }
1312
Grace Kloba22ac16e2009-10-07 18:00:23 -07001313 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001314 return openTabAndShow(mSettings.getHomePage(), false, null);
1315 }
1316
Leon Scroggins1f005d32009-08-10 17:36:42 -04001317 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001318 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001319 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001320 // This is the last tab. Open a new one, with the home
1321 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001322 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001323 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001324 return;
1325 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001326 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001327 int indexToShow = -1;
1328 if (parent != null) {
1329 indexToShow = mTabControl.getTabIndex(parent);
1330 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001331 final int currentIndex = mTabControl.getCurrentIndex();
1332 // Try to move to the tab to the right
1333 indexToShow = currentIndex + 1;
1334 if (indexToShow > mTabControl.getTabCount() - 1) {
1335 // Try to move to the tab to the left
1336 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001337 }
1338 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001339 if (switchToTab(indexToShow)) {
1340 // Close window
1341 closeTab(current);
1342 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001343 }
1344
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001345 private ActiveTabsPage mActiveTabsPage;
1346
1347 /**
1348 * Remove the active tabs page.
1349 * @param needToAttach If true, the active tabs page did not attach a tab
1350 * to the content view, so we need to do that here.
1351 */
1352 /* package */ void removeActiveTabPage(boolean needToAttach) {
1353 mContentView.removeView(mActiveTabsPage);
1354 mActiveTabsPage = null;
1355 mMenuState = R.id.MAIN_MENU;
1356 if (needToAttach) {
1357 attachTabToContentView(mTabControl.getCurrentTab());
1358 }
1359 getTopWindow().requestFocus();
1360 }
1361
The Android Open Source Project0c908882009-03-03 19:32:16 -08001362 @Override
1363 public boolean onOptionsItemSelected(MenuItem item) {
1364 if (!mCanChord) {
1365 // The user has already fired a shortcut with this hold down of the
1366 // menu key.
1367 return false;
1368 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001369 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001370 return false;
1371 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001372 if (mMenuIsDown) {
1373 // The shortcut action consumes the MENU. Even if it is still down,
1374 // it won't trigger the next shortcut action. In the case of the
1375 // shortcut action triggering a new activity, like Bookmarks, we
1376 // won't get onKeyUp for MENU. So it is important to reset it here.
1377 mMenuIsDown = false;
1378 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001379 switch (item.getItemId()) {
1380 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001381 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001382 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001383 break;
1384
Leon Scroggins64b80f32009-08-07 12:03:34 -04001385 case R.id.goto_menu_id:
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001386 onSearchRequested();
1387 break;
1388
1389 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001390 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001391 break;
1392
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001393 case R.id.active_tabs_menu_id:
1394 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1395 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001396 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001397 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1398 mActiveTabsPage.requestFocus();
1399 mMenuState = EMPTY_MENU;
1400 break;
1401
Leon Scroggins1f005d32009-08-10 17:36:42 -04001402 case R.id.add_bookmark_menu_id:
1403 Intent i = new Intent(BrowserActivity.this,
1404 AddBookmarkPage.class);
1405 WebView w = getTopWindow();
1406 i.putExtra("url", w.getUrl());
1407 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001408 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001409 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001410 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001411 break;
1412
1413 case R.id.stop_reload_menu_id:
1414 if (mInLoad) {
1415 stopLoading();
1416 } else {
1417 getTopWindow().reload();
1418 }
1419 break;
1420
1421 case R.id.back_menu_id:
1422 getTopWindow().goBack();
1423 break;
1424
1425 case R.id.forward_menu_id:
1426 getTopWindow().goForward();
1427 break;
1428
1429 case R.id.close_menu_id:
1430 // Close the subwindow if it exists.
1431 if (mTabControl.getCurrentSubWindow() != null) {
1432 dismissSubWindow(mTabControl.getCurrentTab());
1433 break;
1434 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001435 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001436 break;
1437
1438 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001439 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001440 if (current != null) {
1441 dismissSubWindow(current);
1442 current.getWebView().loadUrl(mSettings.getHomePage());
1443 }
1444 break;
1445
1446 case R.id.preferences_menu_id:
1447 Intent intent = new Intent(this,
1448 BrowserPreferencesPage.class);
1449 startActivityForResult(intent, PREFERENCES_PAGE);
1450 break;
1451
1452 case R.id.find_menu_id:
1453 if (null == mFindDialog) {
1454 mFindDialog = new FindDialog(this);
1455 }
1456 mFindDialog.setWebView(getTopWindow());
1457 mFindDialog.show();
1458 mMenuState = EMPTY_MENU;
1459 break;
1460
1461 case R.id.select_text_id:
1462 getTopWindow().emulateShiftHeld();
1463 break;
1464 case R.id.page_info_menu_id:
1465 showPageInfo(mTabControl.getCurrentTab(), false);
1466 break;
1467
1468 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001469 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001470 break;
1471
1472 case R.id.share_page_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01001473 Browser.sendString(this, getTopWindow().getUrl(),
1474 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001475 break;
1476
1477 case R.id.dump_nav_menu_id:
1478 getTopWindow().debugDump();
1479 break;
1480
1481 case R.id.zoom_in_menu_id:
1482 getTopWindow().zoomIn();
1483 break;
1484
1485 case R.id.zoom_out_menu_id:
1486 getTopWindow().zoomOut();
1487 break;
1488
1489 case R.id.view_downloads_menu_id:
1490 viewDownloads(null);
1491 break;
1492
The Android Open Source Project0c908882009-03-03 19:32:16 -08001493 case R.id.window_one_menu_id:
1494 case R.id.window_two_menu_id:
1495 case R.id.window_three_menu_id:
1496 case R.id.window_four_menu_id:
1497 case R.id.window_five_menu_id:
1498 case R.id.window_six_menu_id:
1499 case R.id.window_seven_menu_id:
1500 case R.id.window_eight_menu_id:
1501 {
1502 int menuid = item.getItemId();
1503 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1504 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001505 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001506 if (desiredTab != null &&
1507 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001508 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001509 }
1510 break;
1511 }
1512 }
1513 }
1514 break;
1515
1516 default:
1517 if (!super.onOptionsItemSelected(item)) {
1518 return false;
1519 }
1520 // Otherwise fall through.
1521 }
1522 mCanChord = false;
1523 return true;
1524 }
1525
1526 public void closeFind() {
1527 mMenuState = R.id.MAIN_MENU;
1528 }
1529
Grace Kloba22ac16e2009-10-07 18:00:23 -07001530 @Override
1531 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001532 // This happens when the user begins to hold down the menu key, so
1533 // allow them to chord to get a shortcut.
1534 mCanChord = true;
1535 // Note: setVisible will decide whether an item is visible; while
1536 // setEnabled() will decide whether an item is enabled, which also means
1537 // whether the matching shortcut key will function.
1538 super.onPrepareOptionsMenu(menu);
1539 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001540 case EMPTY_MENU:
1541 if (mCurrentMenuState != mMenuState) {
1542 menu.setGroupVisible(R.id.MAIN_MENU, false);
1543 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1544 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001545 }
1546 break;
1547 default:
1548 if (mCurrentMenuState != mMenuState) {
1549 menu.setGroupVisible(R.id.MAIN_MENU, true);
1550 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1551 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001552 }
1553 final WebView w = getTopWindow();
1554 boolean canGoBack = false;
1555 boolean canGoForward = false;
1556 boolean isHome = false;
1557 if (w != null) {
1558 canGoBack = w.canGoBack();
1559 canGoForward = w.canGoForward();
1560 isHome = mSettings.getHomePage().equals(w.getUrl());
1561 }
1562 final MenuItem back = menu.findItem(R.id.back_menu_id);
1563 back.setEnabled(canGoBack);
1564
1565 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1566 home.setEnabled(!isHome);
1567
1568 menu.findItem(R.id.forward_menu_id)
1569 .setEnabled(canGoForward);
1570
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001571 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001572 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001573
The Android Open Source Project0c908882009-03-03 19:32:16 -08001574 // decide whether to show the share link option
1575 PackageManager pm = getPackageManager();
1576 Intent send = new Intent(Intent.ACTION_SEND);
1577 send.setType("text/plain");
1578 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1579 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1580
The Android Open Source Project0c908882009-03-03 19:32:16 -08001581 boolean isNavDump = mSettings.isNavDump();
1582 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1583 nav.setVisible(isNavDump);
1584 nav.setEnabled(isNavDump);
1585 break;
1586 }
1587 mCurrentMenuState = mMenuState;
1588 return true;
1589 }
1590
1591 @Override
1592 public void onCreateContextMenu(ContextMenu menu, View v,
1593 ContextMenuInfo menuInfo) {
1594 WebView webview = (WebView) v;
1595 WebView.HitTestResult result = webview.getHitTestResult();
1596 if (result == null) {
1597 return;
1598 }
1599
1600 int type = result.getType();
1601 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1602 Log.w(LOGTAG,
1603 "We should not show context menu when nothing is touched");
1604 return;
1605 }
1606 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1607 // let TextView handles context menu
1608 return;
1609 }
1610
1611 // Note, http://b/issue?id=1106666 is requesting that
1612 // an inflated menu can be used again. This is not available
1613 // yet, so inflate each time (yuk!)
1614 MenuInflater inflater = getMenuInflater();
1615 inflater.inflate(R.menu.browsercontext, menu);
1616
1617 // Show the correct menu group
1618 String extra = result.getExtra();
1619 menu.setGroupVisible(R.id.PHONE_MENU,
1620 type == WebView.HitTestResult.PHONE_TYPE);
1621 menu.setGroupVisible(R.id.EMAIL_MENU,
1622 type == WebView.HitTestResult.EMAIL_TYPE);
1623 menu.setGroupVisible(R.id.GEO_MENU,
1624 type == WebView.HitTestResult.GEO_TYPE);
1625 menu.setGroupVisible(R.id.IMAGE_MENU,
1626 type == WebView.HitTestResult.IMAGE_TYPE
1627 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1628 menu.setGroupVisible(R.id.ANCHOR_MENU,
1629 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1630 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1631
1632 // Setup custom handling depending on the type
1633 switch (type) {
1634 case WebView.HitTestResult.PHONE_TYPE:
1635 menu.setHeaderTitle(Uri.decode(extra));
1636 menu.findItem(R.id.dial_context_menu_id).setIntent(
1637 new Intent(Intent.ACTION_VIEW, Uri
1638 .parse(WebView.SCHEME_TEL + extra)));
1639 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1640 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001641 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001642 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1643 addIntent);
1644 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1645 new Copy(extra));
1646 break;
1647
1648 case WebView.HitTestResult.EMAIL_TYPE:
1649 menu.setHeaderTitle(extra);
1650 menu.findItem(R.id.email_context_menu_id).setIntent(
1651 new Intent(Intent.ACTION_VIEW, Uri
1652 .parse(WebView.SCHEME_MAILTO + extra)));
1653 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1654 new Copy(extra));
1655 break;
1656
1657 case WebView.HitTestResult.GEO_TYPE:
1658 menu.setHeaderTitle(extra);
1659 menu.findItem(R.id.map_context_menu_id).setIntent(
1660 new Intent(Intent.ACTION_VIEW, Uri
1661 .parse(WebView.SCHEME_GEO
1662 + URLEncoder.encode(extra))));
1663 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1664 new Copy(extra));
1665 break;
1666
1667 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1668 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1669 TextView titleView = (TextView) LayoutInflater.from(this)
1670 .inflate(android.R.layout.browser_link_context_header,
1671 null);
1672 titleView.setText(extra);
1673 menu.setHeaderView(titleView);
1674 // decide whether to show the open link in new tab option
1675 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001676 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001677 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1678 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001679 PackageManager pm = getPackageManager();
1680 Intent send = new Intent(Intent.ACTION_SEND);
1681 send.setType("text/plain");
1682 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1683 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1684 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1685 break;
1686 }
1687 // otherwise fall through to handle image part
1688 case WebView.HitTestResult.IMAGE_TYPE:
1689 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1690 menu.setHeaderTitle(extra);
1691 }
1692 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1693 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1694 menu.findItem(R.id.download_context_menu_id).
1695 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001696 menu.findItem(R.id.set_wallpaper_context_menu_id).
1697 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001698 break;
1699
1700 default:
1701 Log.w(LOGTAG, "We should not get here.");
1702 break;
1703 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001704 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001705 }
1706
The Android Open Source Project0c908882009-03-03 19:32:16 -08001707 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001708 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001709 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001710 // Attach the container that contains the main WebView and any other UI
1711 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001712 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001713
1714 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001715 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001716 if (errorConsole.numberOfErrors() == 0) {
1717 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1718 } else {
1719 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1720 }
1721
1722 mErrorConsoleContainer.addView(errorConsole,
1723 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1724 ViewGroup.LayoutParams.WRAP_CONTENT));
1725 }
1726
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001727 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001728 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001729 // Request focus on the top window.
1730 t.getTopWindow().requestFocus();
1731 }
1732
1733 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001734 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001735 t.attachSubWindow(mContentView);
1736 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001737 }
1738
1739 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001740 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001741 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001742 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001743
Grace Kloba22ac16e2009-10-07 18:00:23 -07001744 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1745 if (errorConsole != null) {
1746 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001747 }
1748
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001749 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001750 if (view != null) {
1751 view.setEmbeddedTitleBar(null);
1752 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001753 }
1754
1755 // Remove the sub window if it exists. Also called by TabControl when the
1756 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001757 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001758 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001759 // dismiss the subwindow. This will destroy the WebView.
1760 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001761 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001762 }
1763
Leon Scroggins1f005d32009-08-10 17:36:42 -04001764 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001765 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001766 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001767 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001768 }
1769
1770 // This method does a ton of stuff. It will attempt to create a new tab
1771 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001772 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001773 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1774 String appId) {
1775 final Tab currentTab = mTabControl.getCurrentTab();
1776 if (mTabControl.canCreateNewTab()) {
1777 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1778 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001779 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001780 // If the last tab was removed from the active tabs page, currentTab
1781 // will be null.
1782 if (currentTab != null) {
1783 removeTabFromContentView(currentTab);
1784 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001785 // We must set the new tab as the current tab to reflect the old
1786 // animation behavior.
1787 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001788 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001789 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001790 urlData.loadIn(webview);
1791 }
1792 return tab;
1793 } else {
1794 // Get rid of the subwindow if it exists
1795 dismissSubWindow(currentTab);
1796 if (!urlData.isEmpty()) {
1797 // Load the given url.
1798 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001799 }
1800 }
Grace Klobac9181842009-04-14 08:53:22 -07001801 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001802 }
1803
Grace Kloba22ac16e2009-10-07 18:00:23 -07001804 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001805 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001806 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001807 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001808 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001809 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001810 }
Grace Klobac9181842009-04-14 08:53:22 -07001811 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001812 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001813 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001814 }
1815 }
1816
1817 private class Copy implements OnMenuItemClickListener {
1818 private CharSequence mText;
1819
1820 public boolean onMenuItemClick(MenuItem item) {
1821 copy(mText);
1822 return true;
1823 }
1824
1825 public Copy(CharSequence toCopy) {
1826 mText = toCopy;
1827 }
1828 }
1829
1830 private class Download implements OnMenuItemClickListener {
1831 private String mText;
1832
1833 public boolean onMenuItemClick(MenuItem item) {
1834 onDownloadStartNoStream(mText, null, null, null, -1);
1835 return true;
1836 }
1837
1838 public Download(String toDownload) {
1839 mText = toDownload;
1840 }
1841 }
1842
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001843 private class SetAsWallpaper extends Thread implements
1844 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1845 private URL mUrl;
1846 private ProgressDialog mWallpaperProgress;
1847 private boolean mCanceled = false;
1848
1849 public SetAsWallpaper(String url) {
1850 try {
1851 mUrl = new URL(url);
1852 } catch (MalformedURLException e) {
1853 mUrl = null;
1854 }
1855 }
1856
1857 public void onCancel(DialogInterface dialog) {
1858 mCanceled = true;
1859 }
1860
1861 public boolean onMenuItemClick(MenuItem item) {
1862 if (mUrl != null) {
1863 // The user may have tried to set a image with a large file size as their
1864 // background so it may take a few moments to perform the operation. Display
1865 // a progress spinner while it is working.
1866 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1867 mWallpaperProgress.setIndeterminate(true);
1868 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1869 mWallpaperProgress.setCancelable(true);
1870 mWallpaperProgress.setOnCancelListener(this);
1871 mWallpaperProgress.show();
1872 start();
1873 }
1874 return true;
1875 }
1876
1877 public void run() {
1878 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1879 try {
1880 // TODO: This will cause the resource to be downloaded again, when we
1881 // should in most cases be able to grab it from the cache. To fix this
1882 // we should query WebCore to see if we can access a cached version and
1883 // instead open an input stream on that. This pattern could also be used
1884 // in the download manager where the same problem exists.
1885 InputStream inputstream = mUrl.openStream();
1886 if (inputstream != null) {
1887 setWallpaper(inputstream);
1888 }
1889 } catch (IOException e) {
1890 Log.e(LOGTAG, "Unable to set new wallpaper");
1891 // Act as though the user canceled the operation so we try to
1892 // restore the old wallpaper.
1893 mCanceled = true;
1894 }
1895
1896 if (mCanceled) {
1897 // Restore the old wallpaper if the user cancelled whilst we were setting
1898 // the new wallpaper.
1899 int width = oldWallpaper.getIntrinsicWidth();
1900 int height = oldWallpaper.getIntrinsicHeight();
1901 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1902 Canvas canvas = new Canvas(bm);
1903 oldWallpaper.setBounds(0, 0, width, height);
1904 oldWallpaper.draw(canvas);
1905 try {
1906 setWallpaper(bm);
1907 } catch (IOException e) {
1908 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1909 }
1910 mCanceled = false;
1911 }
1912
1913 if (mWallpaperProgress.isShowing()) {
1914 mWallpaperProgress.dismiss();
1915 }
1916 }
1917 }
1918
The Android Open Source Project0c908882009-03-03 19:32:16 -08001919 private void copy(CharSequence text) {
1920 try {
1921 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1922 if (clip != null) {
1923 clip.setClipboardText(text);
1924 }
1925 } catch (android.os.RemoteException e) {
1926 Log.e(LOGTAG, "Copy failed", e);
1927 }
1928 }
1929
1930 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001931 * Resets the browser title-view to whatever it must be
1932 * (for example, if we had a loading error)
1933 * When we have a new page, we call resetTitle, when we
1934 * have to reset the titlebar to whatever it used to be
1935 * (for example, if the user chose to stop loading), we
1936 * call resetTitleAndRevertLockIcon.
1937 */
1938 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001939 mTabControl.getCurrentTab().revertLockIcon();
1940 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001941 resetTitleIconAndProgress();
1942 }
1943
1944 /**
1945 * Reset the title, favicon, and progress.
1946 */
1947 private void resetTitleIconAndProgress() {
1948 WebView current = mTabControl.getCurrentWebView();
1949 if (current == null) {
1950 return;
1951 }
1952 resetTitleAndIcon(current);
1953 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001954 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001955 }
1956
1957 // Reset the title and the icon based on the given item.
1958 private void resetTitleAndIcon(WebView view) {
1959 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1960 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001961 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001962 setFavicon(item.getFavicon());
1963 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001964 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001965 setFavicon(null);
1966 }
1967 }
1968
1969 /**
1970 * Sets a title composed of the URL and the title string.
1971 * @param url The URL of the site being loaded.
1972 * @param title The title of the site being loaded.
1973 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001974 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001975 mUrl = url;
1976 mTitle = title;
1977
Leon Scroggins68579392009-09-15 15:31:54 -04001978 mTitleBar.setTitleAndUrl(title, url);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001979 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001980 }
1981
1982 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001983 * @param url The URL to build a title version of the URL from.
1984 * @return The title version of the URL or null if fails.
1985 * The title version of the URL can be either the URL hostname,
1986 * or the hostname with an "https://" prefix (for secure URLs),
1987 * or an empty string if, for example, the URL in question is a
1988 * file:// URL with no hostname.
1989 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001990 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001991 String titleUrl = null;
1992
1993 if (url != null) {
1994 try {
1995 // parse the url string
1996 URL urlObj = new URL(url);
1997 if (urlObj != null) {
1998 titleUrl = "";
1999
2000 String protocol = urlObj.getProtocol();
2001 String host = urlObj.getHost();
2002
2003 if (host != null && 0 < host.length()) {
2004 titleUrl = host;
2005 if (protocol != null) {
2006 // if a secure site, add an "https://" prefix!
2007 if (protocol.equalsIgnoreCase("https")) {
2008 titleUrl = protocol + "://" + host;
2009 }
2010 }
2011 }
2012 }
2013 } catch (MalformedURLException e) {}
2014 }
2015
2016 return titleUrl;
2017 }
2018
2019 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002020 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002021 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002022 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002023 }
2024
2025 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002026 * Close the tab, remove its associated title bar, and adjust mTabControl's
2027 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002028 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002029 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002030 int currentIndex = mTabControl.getCurrentIndex();
2031 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002032 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002033 if (currentIndex >= removeIndex && currentIndex != 0) {
2034 currentIndex--;
2035 }
2036 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002037 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002038 }
2039
2040 private void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002041 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002042 if (current == null) {
2043 /*
2044 * Instead of finishing the activity, simply push this to the back
2045 * of the stack and let ActivityManager to choose the foreground
2046 * activity. As BrowserActivity is singleTask, it will be always the
2047 * root of the task. So we can use either true or false for
2048 * moveTaskToBack().
2049 */
2050 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002051 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002052 }
2053 WebView w = current.getWebView();
2054 if (w.canGoBack()) {
2055 w.goBack();
2056 } else {
2057 // Check to see if we are closing a window that was created by
2058 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002059 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002060 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002061 switchToTab(mTabControl.getTabIndex(parent));
2062 // Now we close the other tab
2063 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002064 } else {
2065 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002066 // force the tab's inLoad() to be false as we are going to
2067 // either finish the activity or remove the tab. This will
2068 // ensure pauseWebViewTimers() taking action.
2069 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002070 if (mTabControl.getTabCount() == 1) {
2071 finish();
2072 return;
2073 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002074 // call pauseWebViewTimers() now, we won't be able to call
2075 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002076 // Temporarily change mActivityInPause to be true as
2077 // pauseWebViewTimers() will do nothing if mActivityInPause
2078 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002079 boolean savedState = mActivityInPause;
2080 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002081 Log.e(LOGTAG, "BrowserActivity is already paused "
2082 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002083 }
2084 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002085 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002086 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002087 removeTabFromContentView(current);
2088 mTabControl.removeTab(current);
2089 }
2090 /*
2091 * Instead of finishing the activity, simply push this to the back
2092 * of the stack and let ActivityManager to choose the foreground
2093 * activity. As BrowserActivity is singleTask, it will be always the
2094 * root of the task. So we can use either true or false for
2095 * moveTaskToBack().
2096 */
2097 moveTaskToBack(true);
2098 }
2099 }
2100 }
2101
Grace Kloba22ac16e2009-10-07 18:00:23 -07002102 boolean isMenuDown() {
2103 return mMenuIsDown;
2104 }
2105
Grace Kloba5942df02009-09-18 11:48:29 -07002106 @Override
2107 public boolean onKeyDown(int keyCode, KeyEvent event) {
2108 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2109 // still down, we don't want to trigger the search. Pretend to consume
2110 // the key and do nothing.
2111 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002112
Grace Kloba5942df02009-09-18 11:48:29 -07002113 switch(keyCode) {
2114 case KeyEvent.KEYCODE_MENU:
2115 mMenuIsDown = true;
2116 break;
2117 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002118 // WebView/WebTextView handle the keys in the KeyDown. As
2119 // the Activity's shortcut keys are only handled when WebView
2120 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2121 if (event.isShiftPressed()) {
2122 getTopWindow().pageUp(false);
2123 } else {
2124 getTopWindow().pageDown(false);
2125 }
Grace Kloba5942df02009-09-18 11:48:29 -07002126 return true;
2127 case KeyEvent.KEYCODE_BACK:
2128 if (event.getRepeatCount() == 0) {
2129 event.startTracking();
2130 return true;
2131 } else if (mCustomView == null && mActiveTabsPage == null
2132 && event.isLongPress()) {
2133 bookmarksOrHistoryPicker(true);
2134 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002135 }
Grace Kloba5942df02009-09-18 11:48:29 -07002136 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002137 }
Grace Kloba5942df02009-09-18 11:48:29 -07002138 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002139 }
2140
Grace Kloba5942df02009-09-18 11:48:29 -07002141 @Override
2142 public boolean onKeyUp(int keyCode, KeyEvent event) {
2143 switch(keyCode) {
2144 case KeyEvent.KEYCODE_MENU:
2145 mMenuIsDown = false;
2146 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002147 case KeyEvent.KEYCODE_BACK:
2148 if (event.isTracking() && !event.isCanceled()) {
2149 if (mCustomView != null) {
2150 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002151 mTabControl.getCurrentWebView().getWebChromeClient()
2152 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002153 } else if (mActiveTabsPage != null) {
2154 // if tab page is showing, hide it
2155 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002156 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002157 WebView subwindow = mTabControl.getCurrentSubWindow();
2158 if (subwindow != null) {
2159 if (subwindow.canGoBack()) {
2160 subwindow.goBack();
2161 } else {
2162 dismissSubWindow(mTabControl.getCurrentTab());
2163 }
2164 } else {
2165 goBackOnePageOrQuit();
2166 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002167 }
Grace Kloba5942df02009-09-18 11:48:29 -07002168 return true;
2169 }
2170 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002171 }
Grace Kloba5942df02009-09-18 11:48:29 -07002172 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002173 }
2174
Leon Scroggins68579392009-09-15 15:31:54 -04002175 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002176 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002177 resetTitleAndRevertLockIcon();
2178 WebView w = getTopWindow();
2179 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002180 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2181 // same logic here. But for subwindow case, should we call into the main
2182 // WebView's onPageFinished as we never call its onPageStarted and if
2183 // the page finishes itself, we don't call onPageFinished.
2184 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2185 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002186
2187 cancelStopToast();
2188 mStopToast = Toast
2189 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2190 mStopToast.show();
2191 }
2192
Grace Kloba22ac16e2009-10-07 18:00:23 -07002193 boolean didUserStopLoading() {
2194 return mDidStopLoad;
2195 }
2196
The Android Open Source Project0c908882009-03-03 19:32:16 -08002197 private void cancelStopToast() {
2198 if (mStopToast != null) {
2199 mStopToast.cancel();
2200 mStopToast = null;
2201 }
2202 }
2203
Grace Kloba22ac16e2009-10-07 18:00:23 -07002204 // called by a UI or non-UI thread to post the message
2205 public void postMessage(int what, int arg1, int arg2, Object obj,
2206 long delayMillis) {
2207 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2208 obj), delayMillis);
2209 }
2210
2211 // called by a UI or non-UI thread to remove the message
2212 void removeMessages(int what, Object object) {
2213 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002214 }
2215
2216 // public message ids
2217 public final static int LOAD_URL = 1001;
2218 public final static int STOP_LOAD = 1002;
2219
2220 // Message Ids
2221 private static final int FOCUS_NODE_HREF = 102;
2222 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002223 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002224
Grace Kloba22ac16e2009-10-07 18:00:23 -07002225 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002226
The Android Open Source Project0c908882009-03-03 19:32:16 -08002227 // Private handler for handling javascript and saving passwords
2228 private Handler mHandler = new Handler() {
2229
2230 public void handleMessage(Message msg) {
2231 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002232 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002233 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002234 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002235 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002236 if (url == null || url.length() == 0) {
2237 break;
2238 }
2239 HashMap focusNodeMap = (HashMap) msg.obj;
2240 WebView view = (WebView) focusNodeMap.get("webview");
2241 // Only apply the action if the top window did not change.
2242 if (getTopWindow() != view) {
2243 break;
2244 }
2245 switch (msg.arg1) {
2246 case R.id.open_context_menu_id:
2247 case R.id.view_image_context_menu_id:
2248 loadURL(getTopWindow(), url);
2249 break;
2250 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002251 final Tab parent = mTabControl.getCurrentTab();
2252 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002253 if (newTab != parent) {
2254 parent.addChildTab(newTab);
2255 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002256 break;
2257 case R.id.bookmark_context_menu_id:
2258 Intent intent = new Intent(BrowserActivity.this,
2259 AddBookmarkPage.class);
2260 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002261 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002262 startActivity(intent);
2263 break;
2264 case R.id.share_link_context_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01002265 Browser.sendString(BrowserActivity.this, url,
2266 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002267 break;
2268 case R.id.copy_link_context_menu_id:
2269 copy(url);
2270 break;
2271 case R.id.save_link_context_menu_id:
2272 case R.id.download_context_menu_id:
2273 onDownloadStartNoStream(url, null, null, null, -1);
2274 break;
2275 }
2276 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002277 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002278
2279 case LOAD_URL:
2280 loadURL(getTopWindow(), (String) msg.obj);
2281 break;
2282
2283 case STOP_LOAD:
2284 stopLoading();
2285 break;
2286
2287 case CANCEL_CREDS_REQUEST:
2288 resumeAfterCredentials();
2289 break;
2290
The Android Open Source Project0c908882009-03-03 19:32:16 -08002291 case RELEASE_WAKELOCK:
2292 if (mWakeLock.isHeld()) {
2293 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002294 // if we reach here, Browser should be still in the
2295 // background loading after WAKELOCK_TIMEOUT (5-min).
2296 // To avoid burning the battery, stop loading.
2297 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002298 }
2299 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002300
2301 case UPDATE_BOOKMARK_THUMBNAIL:
2302 WebView view = (WebView) msg.obj;
2303 if (view != null) {
2304 updateScreenshot(view);
2305 }
2306 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002307 }
2308 }
2309 };
2310
Leon Scroggins89c6d362009-07-15 16:54:37 -04002311 private void updateScreenshot(WebView view) {
2312 // If this is a bookmarked site, add a screenshot to the database.
2313 // FIXME: When should we update? Every time?
2314 // FIXME: Would like to make sure there is actually something to
2315 // draw, but the API for that (WebViewCore.pictureReady()) is not
2316 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002317
Patrick Scott3918d442009-08-04 13:22:29 -04002318 ContentResolver cr = getContentResolver();
2319 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002320 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002321 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002322 boolean succeed = c.moveToFirst();
2323 ContentValues values = null;
2324 while (succeed) {
2325 if (values == null) {
2326 final ByteArrayOutputStream os
2327 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002328 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002329 if (bm == null) {
2330 c.close();
2331 return;
2332 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002333 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2334 values = new ContentValues();
2335 values.put(Browser.BookmarkColumns.THUMBNAIL,
2336 os.toByteArray());
2337 }
2338 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2339 c.getInt(0)), values, null, null);
2340 succeed = c.moveToNext();
2341 }
2342 c.close();
2343 }
2344 }
2345
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002346 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002347 * Values for the size of the thumbnail created when taking a screenshot.
2348 * Lazily initialized. Instead of using these directly, use
2349 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002350 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002351 private static int THUMBNAIL_WIDTH = 0;
2352 private static int THUMBNAIL_HEIGHT = 0;
2353
2354 /**
2355 * Return the desired width for thumbnail screenshots, which are stored in
2356 * the database, and used on the bookmarks screen.
2357 * @param context Context for finding out the density of the screen.
2358 * @return int desired width for thumbnail screenshot.
2359 */
2360 /* package */ static int getDesiredThumbnailWidth(Context context) {
2361 if (THUMBNAIL_WIDTH == 0) {
2362 float density = context.getResources().getDisplayMetrics().density;
2363 THUMBNAIL_WIDTH = (int) (90 * density);
2364 THUMBNAIL_HEIGHT = (int) (80 * density);
2365 }
2366 return THUMBNAIL_WIDTH;
2367 }
2368
2369 /**
2370 * Return the desired height for thumbnail screenshots, which are stored in
2371 * the database, and used on the bookmarks screen.
2372 * @param context Context for finding out the density of the screen.
2373 * @return int desired height for thumbnail screenshot.
2374 */
2375 /* package */ static int getDesiredThumbnailHeight(Context context) {
2376 // To ensure that they are both initialized.
2377 getDesiredThumbnailWidth(context);
2378 return THUMBNAIL_HEIGHT;
2379 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002380
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002381 private Bitmap createScreenshot(WebView view) {
2382 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002383 if (thumbnail == null) {
2384 return null;
2385 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002386 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2387 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002388 Canvas canvas = new Canvas(bm);
2389 // May need to tweak these values to determine what is the
2390 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002391 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002392 int thumbnailHeight = thumbnail.getHeight();
2393 float scaleFactorX = 1.0f;
2394 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002395 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002396 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002397 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002398 } else {
2399 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002400 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002401
2402 if (view.getWidth() > view.getHeight() &&
2403 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2404 // If the device is in landscape and the page is shorter
2405 // than the height of the view, stretch the thumbnail to fill the
2406 // space.
2407 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2408 (float)thumbnailHeight;
2409 } else {
2410 // In the portrait case, this looks nice.
2411 scaleFactorY = scaleFactorX;
2412 }
2413
2414 canvas.scale(scaleFactorX, scaleFactorY);
2415
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002416 thumbnail.draw(canvas);
2417 return bm;
2418 }
2419
The Android Open Source Project0c908882009-03-03 19:32:16 -08002420 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002421 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002422 //-------------------------------------------------------------------------
2423
2424 // Use in overrideUrlLoading
2425 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2426 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2427 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2428 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2429
Grace Kloba22ac16e2009-10-07 18:00:23 -07002430 void onPageStarted(WebView view, String url, Bitmap favicon) {
2431 // when BrowserActivity just starts, onPageStarted may be called before
2432 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2433 // to start the timer. As we won't switch tabs while an activity is in
2434 // pause state, we can ensure calling resume and pause in pair.
2435 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002436
Grace Kloba22ac16e2009-10-07 18:00:23 -07002437 resetLockIcon(url);
2438 setUrlTitle(url, null);
2439 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002440 // Keep this initial progress in sync with initialProgressValue (* 100)
2441 // in ProgressTracker.cpp
2442 // Show some progress so that the user knows the page is beginning to
2443 // load
2444 onProgressChanged(view, 10);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002445 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002446 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002447
Grace Kloba22ac16e2009-10-07 18:00:23 -07002448 if (mSettings.isTracing()) {
2449 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002450 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002451 WebAddress uri = new WebAddress(url);
2452 host = uri.mHost;
2453 } catch (android.net.ParseException ex) {
2454 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002455 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002456 host = host.replace('.', '_');
2457 host += ".trace";
2458 mInTrace = true;
2459 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2460 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002461
Grace Kloba22ac16e2009-10-07 18:00:23 -07002462 // Performance probe
2463 if (false) {
2464 mStart = SystemClock.uptimeMillis();
2465 mProcessStart = Process.getElapsedCpuTime();
2466 long[] sysCpu = new long[7];
2467 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2468 sysCpu, null)) {
2469 mUserStart = sysCpu[0] + sysCpu[1];
2470 mSystemStart = sysCpu[2];
2471 mIdleStart = sysCpu[3];
2472 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2473 }
2474 mUiStart = SystemClock.currentThreadTimeMillis();
2475 }
2476 }
2477
2478 void onPageFinished(WebView view, String url) {
2479 // Reset the title and icon in case we stopped a provisional load.
2480 resetTitleAndIcon(view);
2481 // Update the lock icon image only once we are done loading
2482 updateLockIconToLatest();
2483 // pause the WebView timer and release the wake lock if it is finished
2484 // while BrowserActivity is in pause state.
2485 if (mActivityInPause && pauseWebViewTimers()) {
2486 if (mWakeLock.isHeld()) {
2487 mHandler.removeMessages(RELEASE_WAKELOCK);
2488 mWakeLock.release();
2489 }
2490 }
2491
2492 // Performance probe
2493 if (false) {
2494 long[] sysCpu = new long[7];
2495 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2496 sysCpu, null)) {
2497 String uiInfo = "UI thread used "
2498 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2499 + " ms";
2500 if (LOGD_ENABLED) {
2501 Log.d(LOGTAG, uiInfo);
2502 }
2503 //The string that gets written to the log
2504 String performanceString = "It took total "
2505 + (SystemClock.uptimeMillis() - mStart)
2506 + " ms clock time to load the page."
2507 + "\nbrowser process used "
2508 + (Process.getElapsedCpuTime() - mProcessStart)
2509 + " ms, user processes used "
2510 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2511 + " ms, kernel used "
2512 + (sysCpu[2] - mSystemStart) * 10
2513 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2514 + " ms and irq took "
2515 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2516 * 10 + " ms, " + uiInfo;
2517 if (LOGD_ENABLED) {
2518 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2519 }
2520 if (url != null) {
2521 // strip the url to maintain consistency
2522 String newUrl = new String(url);
2523 if (newUrl.startsWith("http://www.")) {
2524 newUrl = newUrl.substring(11);
2525 } else if (newUrl.startsWith("http://")) {
2526 newUrl = newUrl.substring(7);
2527 } else if (newUrl.startsWith("https://www.")) {
2528 newUrl = newUrl.substring(12);
2529 } else if (newUrl.startsWith("https://")) {
2530 newUrl = newUrl.substring(8);
2531 }
2532 if (LOGD_ENABLED) {
2533 Log.d(LOGTAG, newUrl + " loaded");
2534 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002535 }
2536 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002537 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002538
Grace Kloba22ac16e2009-10-07 18:00:23 -07002539 if (mInTrace) {
2540 mInTrace = false;
2541 Debug.stopMethodTracing();
2542 }
2543 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002544
Grace Kloba22ac16e2009-10-07 18:00:23 -07002545 boolean shouldOverrideUrlLoading(WebView view, String url) {
2546 if (url.startsWith(SCHEME_WTAI)) {
2547 // wtai://wp/mc;number
2548 // number=string(phone-number)
2549 if (url.startsWith(SCHEME_WTAI_MC)) {
2550 Intent intent = new Intent(Intent.ACTION_VIEW,
2551 Uri.parse(WebView.SCHEME_TEL +
2552 url.substring(SCHEME_WTAI_MC.length())));
2553 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002554 return true;
2555 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002556 // wtai://wp/sd;dtmf
2557 // dtmf=string(dialstring)
2558 if (url.startsWith(SCHEME_WTAI_SD)) {
2559 // TODO: only send when there is active voice connection
2560 return false;
2561 }
2562 // wtai://wp/ap;number;name
2563 // number=string(phone-number)
2564 // name=string
2565 if (url.startsWith(SCHEME_WTAI_AP)) {
2566 // TODO
2567 return false;
2568 }
2569 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002570
Grace Kloba22ac16e2009-10-07 18:00:23 -07002571 // The "about:" schemes are internal to the browser; don't want these to
2572 // be dispatched to other apps.
2573 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002574 return false;
2575 }
2576
Grace Kloba22ac16e2009-10-07 18:00:23 -07002577 Intent intent;
2578 // perform generic parsing of the URI to turn it into an Intent.
2579 try {
2580 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2581 } catch (URISyntaxException ex) {
2582 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2583 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002584 }
2585
Grace Kloba22ac16e2009-10-07 18:00:23 -07002586 // check whether the intent can be resolved. If not, we will see
2587 // whether we can download it from the Market.
2588 if (getPackageManager().resolveActivity(intent, 0) == null) {
2589 String packagename = intent.getPackage();
2590 if (packagename != null) {
2591 intent = new Intent(Intent.ACTION_VIEW, Uri
2592 .parse("market://search?q=pname:" + packagename));
2593 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2594 startActivity(intent);
2595 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002596 } else {
2597 return false;
2598 }
2599 }
2600
Grace Kloba22ac16e2009-10-07 18:00:23 -07002601 // sanitize the Intent, ensuring web pages can not bypass browser
2602 // security (only access to BROWSABLE activities).
2603 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2604 intent.setComponent(null);
2605 try {
2606 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002607 return true;
2608 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002609 } catch (ActivityNotFoundException ex) {
2610 // ignore the error. If no application can handle the URL,
2611 // eg about:blank, assume the browser can handle it.
2612 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002613
Grace Kloba22ac16e2009-10-07 18:00:23 -07002614 if (mMenuIsDown) {
2615 openTab(url);
2616 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002617 return true;
2618 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002619 return false;
2620 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002621
Grace Kloba22ac16e2009-10-07 18:00:23 -07002622 // -------------------------------------------------------------------------
2623 // Helper function for WebChromeClient
2624 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002625
Grace Kloba22ac16e2009-10-07 18:00:23 -07002626 void onProgressChanged(WebView view, int newProgress) {
2627 mTitleBar.setProgress(newProgress);
2628 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002629
Grace Kloba22ac16e2009-10-07 18:00:23 -07002630 if (newProgress == 100) {
2631 // onProgressChanged() may continue to be called after the main
2632 // frame has finished loading, as any remaining sub frames continue
2633 // to load. We'll only get called once though with newProgress as
2634 // 100 when everything is loaded. (onPageFinished is called once
2635 // when the main frame completes loading regardless of the state of
2636 // any sub frames so calls to onProgressChanges may continue after
2637 // onPageFinished has executed)
2638 if (mInLoad) {
2639 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002640 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002641 // If the options menu is open, leave the title bar
2642 if (!mOptionsMenuOpen || !mIconView) {
2643 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002644 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002645 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002646 } else if (!mInLoad) {
2647 // onPageFinished may have already been called but a subframe is
2648 // still loading and updating the progress. Reset mInLoad and update
2649 // the menu items.
2650 mInLoad = true;
2651 updateInLoadMenuItems();
2652 if (!mOptionsMenuOpen || mIconView) {
2653 // This page has begun to load, so show the title bar
2654 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002655 }
2656 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002657 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002658
Grace Kloba22ac16e2009-10-07 18:00:23 -07002659 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2660 if (mCustomView != null)
2661 return;
2662
2663 // Add the custom view to its container.
2664 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2665 mCustomView = view;
2666 mCustomViewCallback = callback;
2667 // Save the menu state and set it to empty while the custom
2668 // view is showing.
2669 mOldMenuState = mMenuState;
2670 mMenuState = EMPTY_MENU;
2671 // Hide the content view.
2672 mContentView.setVisibility(View.GONE);
2673 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002674 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002675 mCustomViewContainer.setVisibility(View.VISIBLE);
2676 mCustomViewContainer.bringToFront();
2677 }
2678
2679 void onHideCustomView() {
2680 if (mCustomView == null)
2681 return;
2682
2683 // Hide the custom view.
2684 mCustomView.setVisibility(View.GONE);
2685 // Remove the custom view from its container.
2686 mCustomViewContainer.removeView(mCustomView);
2687 mCustomView = null;
2688 // Reset the old menu state.
2689 mMenuState = mOldMenuState;
2690 mOldMenuState = EMPTY_MENU;
2691 mCustomViewContainer.setVisibility(View.GONE);
2692 mCustomViewCallback.onCustomViewHidden();
2693 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002694 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002695 mContentView.setVisibility(View.VISIBLE);
2696 }
2697
2698 Bitmap getDefaultVideoPoster() {
2699 if (mDefaultVideoPoster == null) {
2700 mDefaultVideoPoster = BitmapFactory.decodeResource(
2701 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002702 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002703 return mDefaultVideoPoster;
2704 }
Patrick Scott3918d442009-08-04 13:22:29 -04002705
Grace Kloba22ac16e2009-10-07 18:00:23 -07002706 View getVideoLoadingProgressView() {
2707 if (mVideoProgressView == null) {
2708 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2709 mVideoProgressView = inflater.inflate(
2710 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002711 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002712 return mVideoProgressView;
2713 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002714
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002715 /*
2716 * The Object used to inform the WebView of the file to upload.
2717 */
2718 private ValueCallback<Uri> mUploadMessage;
2719
Grace Kloba22ac16e2009-10-07 18:00:23 -07002720 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2721 if (mUploadMessage != null) return;
2722 mUploadMessage = uploadMsg;
2723 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2724 i.addCategory(Intent.CATEGORY_OPENABLE);
2725 i.setType("*/*");
2726 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2727 getString(R.string.choose_upload)), FILE_SELECTED);
2728 }
2729
2730 // -------------------------------------------------------------------------
2731 // Implement functions for DownloadListener
2732 // -------------------------------------------------------------------------
2733
The Android Open Source Project0c908882009-03-03 19:32:16 -08002734 /**
2735 * Notify the host application a download should be done, or that
2736 * the data should be streamed if a streaming viewer is available.
2737 * @param url The full url to the content that should be downloaded
2738 * @param contentDisposition Content-disposition http header, if
2739 * present.
2740 * @param mimetype The mimetype of the content reported by the server
2741 * @param contentLength The file size reported by the server
2742 */
2743 public void onDownloadStart(String url, String userAgent,
2744 String contentDisposition, String mimetype, long contentLength) {
2745 // if we're dealing wih A/V content that's not explicitly marked
2746 // for download, check if it's streamable.
2747 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002748 || !contentDisposition.regionMatches(
2749 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002750 // query the package manager to see if there's a registered handler
2751 // that matches.
2752 Intent intent = new Intent(Intent.ACTION_VIEW);
2753 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002754 ResolveInfo info = getPackageManager().resolveActivity(intent,
2755 PackageManager.MATCH_DEFAULT_ONLY);
2756 if (info != null) {
2757 ComponentName myName = getComponentName();
2758 // If we resolved to ourselves, we don't want to attempt to
2759 // load the url only to try and download it again.
2760 if (!myName.getPackageName().equals(
2761 info.activityInfo.packageName)
2762 || !myName.getClassName().equals(
2763 info.activityInfo.name)) {
2764 // someone (other than us) knows how to handle this mime
2765 // type with this scheme, don't download.
2766 try {
2767 startActivity(intent);
2768 return;
2769 } catch (ActivityNotFoundException ex) {
2770 if (LOGD_ENABLED) {
2771 Log.d(LOGTAG, "activity not found for " + mimetype
2772 + " over " + Uri.parse(url).getScheme(),
2773 ex);
2774 }
2775 // Best behavior is to fall back to a download in this
2776 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002777 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002778 }
2779 }
2780 }
2781 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2782 }
2783
2784 /**
2785 * Notify the host application a download should be done, even if there
2786 * is a streaming viewer available for thise type.
2787 * @param url The full url to the content that should be downloaded
2788 * @param contentDisposition Content-disposition http header, if
2789 * present.
2790 * @param mimetype The mimetype of the content reported by the server
2791 * @param contentLength The file size reported by the server
2792 */
2793 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2794 String contentDisposition, String mimetype, long contentLength) {
2795
2796 String filename = URLUtil.guessFileName(url,
2797 contentDisposition, mimetype);
2798
2799 // Check to see if we have an SDCard
2800 String status = Environment.getExternalStorageState();
2801 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2802 int title;
2803 String msg;
2804
2805 // Check to see if the SDCard is busy, same as the music app
2806 if (status.equals(Environment.MEDIA_SHARED)) {
2807 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2808 title = R.string.download_sdcard_busy_dlg_title;
2809 } else {
2810 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2811 title = R.string.download_no_sdcard_dlg_title;
2812 }
2813
2814 new AlertDialog.Builder(this)
2815 .setTitle(title)
2816 .setIcon(android.R.drawable.ic_dialog_alert)
2817 .setMessage(msg)
2818 .setPositiveButton(R.string.ok, null)
2819 .show();
2820 return;
2821 }
2822
2823 // java.net.URI is a lot stricter than KURL so we have to undo
2824 // KURL's percent-encoding and redo the encoding using java.net.URI.
2825 URI uri = null;
2826 try {
2827 // Undo the percent-encoding that KURL may have done.
2828 String newUrl = new String(URLUtil.decode(url.getBytes()));
2829 // Parse the url into pieces
2830 WebAddress w = new WebAddress(newUrl);
2831 String frag = null;
2832 String query = null;
2833 String path = w.mPath;
2834 // Break the path into path, query, and fragment
2835 if (path.length() > 0) {
2836 // Strip the fragment
2837 int idx = path.lastIndexOf('#');
2838 if (idx != -1) {
2839 frag = path.substring(idx + 1);
2840 path = path.substring(0, idx);
2841 }
2842 idx = path.lastIndexOf('?');
2843 if (idx != -1) {
2844 query = path.substring(idx + 1);
2845 path = path.substring(0, idx);
2846 }
2847 }
2848 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2849 query, frag);
2850 } catch (Exception e) {
2851 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2852 return;
2853 }
2854
2855 // XXX: Have to use the old url since the cookies were stored using the
2856 // old percent-encoded url.
2857 String cookies = CookieManager.getInstance().getCookie(url);
2858
2859 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002860 values.put(Downloads.COLUMN_URI, uri.toString());
2861 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
2862 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
2863 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002864 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002865 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002866 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002867 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2868 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
2869 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
2870 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002871 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002872 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002873 }
2874 if (mimetype == null) {
2875 // We must have long pressed on a link or image to download it. We
2876 // are not sure of the mimetype in this case, so do a head request
2877 new FetchUrlMimeType(this).execute(values);
2878 } else {
2879 final Uri contentUri =
2880 getContentResolver().insert(Downloads.CONTENT_URI, values);
2881 viewDownloads(contentUri);
2882 }
2883
2884 }
2885
Grace Kloba22ac16e2009-10-07 18:00:23 -07002886 // -------------------------------------------------------------------------
2887
The Android Open Source Project0c908882009-03-03 19:32:16 -08002888 /**
2889 * Resets the lock icon. This method is called when we start a new load and
2890 * know the url to be loaded.
2891 */
2892 private void resetLockIcon(String url) {
2893 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002894 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002895 updateLockIconImage(LOCK_ICON_UNSECURE);
2896 }
2897
The Android Open Source Project0c908882009-03-03 19:32:16 -08002898 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002899 * Update the lock icon to correspond to our latest state.
2900 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002901 private void updateLockIconToLatest() {
2902 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002903 }
2904
2905 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002906 * Updates the lock-icon image in the title-bar.
2907 */
2908 private void updateLockIconImage(int lockIconType) {
2909 Drawable d = null;
2910 if (lockIconType == LOCK_ICON_SECURE) {
2911 d = mSecLockIcon;
2912 } else if (lockIconType == LOCK_ICON_MIXED) {
2913 d = mMixLockIcon;
2914 }
Leon Scroggins68579392009-09-15 15:31:54 -04002915 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002916 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002917 }
2918
2919 /**
2920 * Displays a page-info dialog.
2921 * @param tab The tab to show info about
2922 * @param fromShowSSLCertificateOnError The flag that indicates whether
2923 * this dialog was opened from the SSL-certificate-on-error dialog or
2924 * not. This is important, since we need to know whether to return to
2925 * the parent dialog or simply dismiss.
2926 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002927 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002928 final boolean fromShowSSLCertificateOnError) {
2929 final LayoutInflater factory = LayoutInflater
2930 .from(this);
2931
2932 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2933
2934 final WebView view = tab.getWebView();
2935
2936 String url = null;
2937 String title = null;
2938
2939 if (view == null) {
2940 url = tab.getUrl();
2941 title = tab.getTitle();
2942 } else if (view == mTabControl.getCurrentWebView()) {
2943 // Use the cached title and url if this is the current WebView
2944 url = mUrl;
2945 title = mTitle;
2946 } else {
2947 url = view.getUrl();
2948 title = view.getTitle();
2949 }
2950
2951 if (url == null) {
2952 url = "";
2953 }
2954 if (title == null) {
2955 title = "";
2956 }
2957
2958 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
2959 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
2960
2961 mPageInfoView = tab;
2962 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
2963
2964 AlertDialog.Builder alertDialogBuilder =
2965 new AlertDialog.Builder(this)
2966 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
2967 .setView(pageInfoView)
2968 .setPositiveButton(
2969 R.string.ok,
2970 new DialogInterface.OnClickListener() {
2971 public void onClick(DialogInterface dialog,
2972 int whichButton) {
2973 mPageInfoDialog = null;
2974 mPageInfoView = null;
2975 mPageInfoFromShowSSLCertificateOnError = null;
2976
2977 // if we came here from the SSL error dialog
2978 if (fromShowSSLCertificateOnError) {
2979 // go back to the SSL error dialog
2980 showSSLCertificateOnError(
2981 mSSLCertificateOnErrorView,
2982 mSSLCertificateOnErrorHandler,
2983 mSSLCertificateOnErrorError);
2984 }
2985 }
2986 })
2987 .setOnCancelListener(
2988 new DialogInterface.OnCancelListener() {
2989 public void onCancel(DialogInterface dialog) {
2990 mPageInfoDialog = null;
2991 mPageInfoView = null;
2992 mPageInfoFromShowSSLCertificateOnError = null;
2993
2994 // if we came here from the SSL error dialog
2995 if (fromShowSSLCertificateOnError) {
2996 // go back to the SSL error dialog
2997 showSSLCertificateOnError(
2998 mSSLCertificateOnErrorView,
2999 mSSLCertificateOnErrorHandler,
3000 mSSLCertificateOnErrorError);
3001 }
3002 }
3003 });
3004
3005 // if we have a main top-level page SSL certificate set or a certificate
3006 // error
3007 if (fromShowSSLCertificateOnError ||
3008 (view != null && view.getCertificate() != null)) {
3009 // add a 'View Certificate' button
3010 alertDialogBuilder.setNeutralButton(
3011 R.string.view_certificate,
3012 new DialogInterface.OnClickListener() {
3013 public void onClick(DialogInterface dialog,
3014 int whichButton) {
3015 mPageInfoDialog = null;
3016 mPageInfoView = null;
3017 mPageInfoFromShowSSLCertificateOnError = null;
3018
3019 // if we came here from the SSL error dialog
3020 if (fromShowSSLCertificateOnError) {
3021 // go back to the SSL error dialog
3022 showSSLCertificateOnError(
3023 mSSLCertificateOnErrorView,
3024 mSSLCertificateOnErrorHandler,
3025 mSSLCertificateOnErrorError);
3026 } else {
3027 // otherwise, display the top-most certificate from
3028 // the chain
3029 if (view.getCertificate() != null) {
3030 showSSLCertificate(tab);
3031 }
3032 }
3033 }
3034 });
3035 }
3036
3037 mPageInfoDialog = alertDialogBuilder.show();
3038 }
3039
3040 /**
3041 * Displays the main top-level page SSL certificate dialog
3042 * (accessible from the Page-Info dialog).
3043 * @param tab The tab to show certificate for.
3044 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003045 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003046 final View certificateView =
3047 inflateCertificateView(tab.getWebView().getCertificate());
3048 if (certificateView == null) {
3049 return;
3050 }
3051
3052 LayoutInflater factory = LayoutInflater.from(this);
3053
3054 final LinearLayout placeholder =
3055 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3056
3057 LinearLayout ll = (LinearLayout) factory.inflate(
3058 R.layout.ssl_success, placeholder);
3059 ((TextView)ll.findViewById(R.id.success))
3060 .setText(R.string.ssl_certificate_is_valid);
3061
3062 mSSLCertificateView = tab;
3063 mSSLCertificateDialog =
3064 new AlertDialog.Builder(this)
3065 .setTitle(R.string.ssl_certificate).setIcon(
3066 R.drawable.ic_dialog_browser_certificate_secure)
3067 .setView(certificateView)
3068 .setPositiveButton(R.string.ok,
3069 new DialogInterface.OnClickListener() {
3070 public void onClick(DialogInterface dialog,
3071 int whichButton) {
3072 mSSLCertificateDialog = null;
3073 mSSLCertificateView = null;
3074
3075 showPageInfo(tab, false);
3076 }
3077 })
3078 .setOnCancelListener(
3079 new DialogInterface.OnCancelListener() {
3080 public void onCancel(DialogInterface dialog) {
3081 mSSLCertificateDialog = null;
3082 mSSLCertificateView = null;
3083
3084 showPageInfo(tab, false);
3085 }
3086 })
3087 .show();
3088 }
3089
3090 /**
3091 * Displays the SSL error certificate dialog.
3092 * @param view The target web-view.
3093 * @param handler The SSL error handler responsible for cancelling the
3094 * connection that resulted in an SSL error or proceeding per user request.
3095 * @param error The SSL error object.
3096 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003097 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003098 final WebView view, final SslErrorHandler handler, final SslError error) {
3099
3100 final View certificateView =
3101 inflateCertificateView(error.getCertificate());
3102 if (certificateView == null) {
3103 return;
3104 }
3105
3106 LayoutInflater factory = LayoutInflater.from(this);
3107
3108 final LinearLayout placeholder =
3109 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3110
3111 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3112 LinearLayout ll = (LinearLayout)factory
3113 .inflate(R.layout.ssl_warning, placeholder);
3114 ((TextView)ll.findViewById(R.id.warning))
3115 .setText(R.string.ssl_untrusted);
3116 }
3117
3118 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3119 LinearLayout ll = (LinearLayout)factory
3120 .inflate(R.layout.ssl_warning, placeholder);
3121 ((TextView)ll.findViewById(R.id.warning))
3122 .setText(R.string.ssl_mismatch);
3123 }
3124
3125 if (error.hasError(SslError.SSL_EXPIRED)) {
3126 LinearLayout ll = (LinearLayout)factory
3127 .inflate(R.layout.ssl_warning, placeholder);
3128 ((TextView)ll.findViewById(R.id.warning))
3129 .setText(R.string.ssl_expired);
3130 }
3131
3132 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3133 LinearLayout ll = (LinearLayout)factory
3134 .inflate(R.layout.ssl_warning, placeholder);
3135 ((TextView)ll.findViewById(R.id.warning))
3136 .setText(R.string.ssl_not_yet_valid);
3137 }
3138
3139 mSSLCertificateOnErrorHandler = handler;
3140 mSSLCertificateOnErrorView = view;
3141 mSSLCertificateOnErrorError = error;
3142 mSSLCertificateOnErrorDialog =
3143 new AlertDialog.Builder(this)
3144 .setTitle(R.string.ssl_certificate).setIcon(
3145 R.drawable.ic_dialog_browser_certificate_partially_secure)
3146 .setView(certificateView)
3147 .setPositiveButton(R.string.ok,
3148 new DialogInterface.OnClickListener() {
3149 public void onClick(DialogInterface dialog,
3150 int whichButton) {
3151 mSSLCertificateOnErrorDialog = null;
3152 mSSLCertificateOnErrorView = null;
3153 mSSLCertificateOnErrorHandler = null;
3154 mSSLCertificateOnErrorError = null;
3155
Grace Kloba22ac16e2009-10-07 18:00:23 -07003156 view.getWebViewClient().onReceivedSslError(
3157 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003158 }
3159 })
3160 .setNeutralButton(R.string.page_info_view,
3161 new DialogInterface.OnClickListener() {
3162 public void onClick(DialogInterface dialog,
3163 int whichButton) {
3164 mSSLCertificateOnErrorDialog = null;
3165
3166 // do not clear the dialog state: we will
3167 // need to show the dialog again once the
3168 // user is done exploring the page-info details
3169
3170 showPageInfo(mTabControl.getTabFromView(view),
3171 true);
3172 }
3173 })
3174 .setOnCancelListener(
3175 new DialogInterface.OnCancelListener() {
3176 public void onCancel(DialogInterface dialog) {
3177 mSSLCertificateOnErrorDialog = null;
3178 mSSLCertificateOnErrorView = null;
3179 mSSLCertificateOnErrorHandler = null;
3180 mSSLCertificateOnErrorError = null;
3181
Grace Kloba22ac16e2009-10-07 18:00:23 -07003182 view.getWebViewClient().onReceivedSslError(
3183 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003184 }
3185 })
3186 .show();
3187 }
3188
3189 /**
3190 * Inflates the SSL certificate view (helper method).
3191 * @param certificate The SSL certificate.
3192 * @return The resultant certificate view with issued-to, issued-by,
3193 * issued-on, expires-on, and possibly other fields set.
3194 * If the input certificate is null, returns null.
3195 */
3196 private View inflateCertificateView(SslCertificate certificate) {
3197 if (certificate == null) {
3198 return null;
3199 }
3200
3201 LayoutInflater factory = LayoutInflater.from(this);
3202
3203 View certificateView = factory.inflate(
3204 R.layout.ssl_certificate, null);
3205
3206 // issued to:
3207 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3208 if (issuedTo != null) {
3209 ((TextView) certificateView.findViewById(R.id.to_common))
3210 .setText(issuedTo.getCName());
3211 ((TextView) certificateView.findViewById(R.id.to_org))
3212 .setText(issuedTo.getOName());
3213 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3214 .setText(issuedTo.getUName());
3215 }
3216
3217 // issued by:
3218 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3219 if (issuedBy != null) {
3220 ((TextView) certificateView.findViewById(R.id.by_common))
3221 .setText(issuedBy.getCName());
3222 ((TextView) certificateView.findViewById(R.id.by_org))
3223 .setText(issuedBy.getOName());
3224 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3225 .setText(issuedBy.getUName());
3226 }
3227
3228 // issued on:
3229 String issuedOn = reformatCertificateDate(
3230 certificate.getValidNotBefore());
3231 ((TextView) certificateView.findViewById(R.id.issued_on))
3232 .setText(issuedOn);
3233
3234 // expires on:
3235 String expiresOn = reformatCertificateDate(
3236 certificate.getValidNotAfter());
3237 ((TextView) certificateView.findViewById(R.id.expires_on))
3238 .setText(expiresOn);
3239
3240 return certificateView;
3241 }
3242
3243 /**
3244 * Re-formats the certificate date (Date.toString()) string to
3245 * a properly localized date string.
3246 * @return Properly localized version of the certificate date string and
3247 * the original certificate date string if fails to localize.
3248 * If the original string is null, returns an empty string "".
3249 */
3250 private String reformatCertificateDate(String certificateDate) {
3251 String reformattedDate = null;
3252
3253 if (certificateDate != null) {
3254 Date date = null;
3255 try {
3256 date = java.text.DateFormat.getInstance().parse(certificateDate);
3257 } catch (ParseException e) {
3258 date = null;
3259 }
3260
3261 if (date != null) {
3262 reformattedDate =
3263 DateFormat.getDateFormat(this).format(date);
3264 }
3265 }
3266
3267 return reformattedDate != null ? reformattedDate :
3268 (certificateDate != null ? certificateDate : "");
3269 }
3270
3271 /**
3272 * Displays an http-authentication dialog.
3273 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003274 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003275 final String host, final String realm, final String title,
3276 final String name, final String password, int focusId) {
3277 LayoutInflater factory = LayoutInflater.from(this);
3278 final View v = factory
3279 .inflate(R.layout.http_authentication, null);
3280 if (name != null) {
3281 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3282 }
3283 if (password != null) {
3284 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3285 }
3286
3287 String titleText = title;
3288 if (titleText == null) {
3289 titleText = getText(R.string.sign_in_to).toString().replace(
3290 "%s1", host).replace("%s2", realm);
3291 }
3292
3293 mHttpAuthHandler = handler;
3294 AlertDialog dialog = new AlertDialog.Builder(this)
3295 .setTitle(titleText)
3296 .setIcon(android.R.drawable.ic_dialog_alert)
3297 .setView(v)
3298 .setPositiveButton(R.string.action,
3299 new DialogInterface.OnClickListener() {
3300 public void onClick(DialogInterface dialog,
3301 int whichButton) {
3302 String nm = ((EditText) v
3303 .findViewById(R.id.username_edit))
3304 .getText().toString();
3305 String pw = ((EditText) v
3306 .findViewById(R.id.password_edit))
3307 .getText().toString();
3308 BrowserActivity.this.setHttpAuthUsernamePassword
3309 (host, realm, nm, pw);
3310 handler.proceed(nm, pw);
3311 mHttpAuthenticationDialog = null;
3312 mHttpAuthHandler = null;
3313 }})
3314 .setNegativeButton(R.string.cancel,
3315 new DialogInterface.OnClickListener() {
3316 public void onClick(DialogInterface dialog,
3317 int whichButton) {
3318 handler.cancel();
3319 BrowserActivity.this.resetTitleAndRevertLockIcon();
3320 mHttpAuthenticationDialog = null;
3321 mHttpAuthHandler = null;
3322 }})
3323 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3324 public void onCancel(DialogInterface dialog) {
3325 handler.cancel();
3326 BrowserActivity.this.resetTitleAndRevertLockIcon();
3327 mHttpAuthenticationDialog = null;
3328 mHttpAuthHandler = null;
3329 }})
3330 .create();
3331 // Make the IME appear when the dialog is displayed if applicable.
3332 dialog.getWindow().setSoftInputMode(
3333 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3334 dialog.show();
3335 if (focusId != 0) {
3336 dialog.findViewById(focusId).requestFocus();
3337 } else {
3338 v.findViewById(R.id.username_edit).requestFocus();
3339 }
3340 mHttpAuthenticationDialog = dialog;
3341 }
3342
3343 public int getProgress() {
3344 WebView w = mTabControl.getCurrentWebView();
3345 if (w != null) {
3346 return w.getProgress();
3347 } else {
3348 return 100;
3349 }
3350 }
3351
3352 /**
3353 * Set HTTP authentication password.
3354 *
3355 * @param host The host for the password
3356 * @param realm The realm for the password
3357 * @param username The username for the password. If it is null, it means
3358 * password can't be saved.
3359 * @param password The password
3360 */
3361 public void setHttpAuthUsernamePassword(String host, String realm,
3362 String username,
3363 String password) {
3364 WebView w = mTabControl.getCurrentWebView();
3365 if (w != null) {
3366 w.setHttpAuthUsernamePassword(host, realm, username, password);
3367 }
3368 }
3369
3370 /**
3371 * connectivity manager says net has come or gone... inform the user
3372 * @param up true if net has come up, false if net has gone down
3373 */
3374 public void onNetworkToggle(boolean up) {
3375 if (up == mIsNetworkUp) {
3376 return;
3377 } else if (up) {
3378 mIsNetworkUp = true;
3379 if (mAlertDialog != null) {
3380 mAlertDialog.cancel();
3381 mAlertDialog = null;
3382 }
3383 } else {
3384 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003385 if (mInLoad) {
3386 createAndShowNetworkDialog();
3387 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003388 }
3389 WebView w = mTabControl.getCurrentWebView();
3390 if (w != null) {
3391 w.setNetworkAvailable(up);
3392 }
3393 }
3394
Grace Kloba22ac16e2009-10-07 18:00:23 -07003395 boolean isNetworkUp() {
3396 return mIsNetworkUp;
3397 }
3398
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003399 // This method shows the network dialog alerting the user that the net is
3400 // down. It will only show the dialog if mAlertDialog is null.
3401 private void createAndShowNetworkDialog() {
3402 if (mAlertDialog == null) {
3403 mAlertDialog = new AlertDialog.Builder(this)
3404 .setTitle(R.string.loadSuspendedTitle)
3405 .setMessage(R.string.loadSuspended)
3406 .setPositiveButton(R.string.ok, null)
3407 .show();
3408 }
3409 }
3410
The Android Open Source Project0c908882009-03-03 19:32:16 -08003411 @Override
3412 protected void onActivityResult(int requestCode, int resultCode,
3413 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003414 if (getTopWindow() == null) return;
3415
The Android Open Source Project0c908882009-03-03 19:32:16 -08003416 switch (requestCode) {
3417 case COMBO_PAGE:
3418 if (resultCode == RESULT_OK && intent != null) {
3419 String data = intent.getAction();
3420 Bundle extras = intent.getExtras();
3421 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003422 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003423 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003424 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003425 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003426 dismissSubWindow(currentTab);
3427 if (data != null && data.length() != 0) {
3428 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003429 }
3430 }
3431 }
3432 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003433 // Choose a file from the file picker.
3434 case FILE_SELECTED:
3435 if (null == mUploadMessage) break;
3436 Uri result = intent == null || resultCode != RESULT_OK ? null
3437 : intent.getData();
3438 mUploadMessage.onReceiveValue(result);
3439 mUploadMessage = null;
3440 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003441 default:
3442 break;
3443 }
Leon Scroggins30444232009-09-04 18:36:20 -04003444 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003445 }
3446
3447 /*
3448 * This method is called as a result of the user selecting the options
3449 * menu to see the download window, or when a download changes state. It
3450 * shows the download window ontop of the current window.
3451 */
3452 /* package */ void viewDownloads(Uri downloadRecord) {
3453 Intent intent = new Intent(this,
3454 BrowserDownloadPage.class);
3455 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003456 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003457
3458 }
3459
Leon Scroggins160a7e72009-08-14 18:28:01 -04003460 /**
3461 * Open the Go page.
3462 * @param startWithHistory If true, open starting on the history tab.
3463 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003464 */
Leon Scroggins30444232009-09-04 18:36:20 -04003465 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003466 WebView current = mTabControl.getCurrentWebView();
3467 if (current == null) {
3468 return;
3469 }
3470 Intent intent = new Intent(this,
3471 CombinedBookmarkHistoryActivity.class);
3472 String title = current.getTitle();
3473 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003474 Bitmap thumbnail = createScreenshot(current);
3475
The Android Open Source Project0c908882009-03-03 19:32:16 -08003476 // Just in case the user opens bookmarks before a page finishes loading
3477 // so the current history item, and therefore the page, is null.
3478 if (null == url) {
3479 url = mLastEnteredUrl;
3480 // This can happen.
3481 if (null == url) {
3482 url = mSettings.getHomePage();
3483 }
3484 }
3485 // In case the web page has not yet received its associated title.
3486 if (title == null) {
3487 title = url;
3488 }
3489 intent.putExtra("title", title);
3490 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003491 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003492 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003493 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003494 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003495 if (startWithHistory) {
3496 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3497 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3498 }
3499 startActivityForResult(intent, COMBO_PAGE);
3500 }
3501
3502 // Called when loading from context menu or LOAD_URL message
3503 private void loadURL(WebView view, String url) {
3504 // In case the user enters nothing.
3505 if (url != null && url.length() != 0 && view != null) {
3506 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003507 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003508 view.loadUrl(url);
3509 }
3510 }
3511 }
3512
The Android Open Source Project0c908882009-03-03 19:32:16 -08003513 private String smartUrlFilter(Uri inUri) {
3514 if (inUri != null) {
3515 return smartUrlFilter(inUri.toString());
3516 }
3517 return null;
3518 }
3519
Feng Qianb34f87a2009-03-24 21:27:26 -07003520 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003521 "(?i)" + // switch on case insensitive matching
3522 "(" + // begin group for schema
3523 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003524 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003525 ")" +
3526 "(.*)" );
3527
3528 /**
3529 * Attempts to determine whether user input is a URL or search
3530 * terms. Anything with a space is passed to search.
3531 *
3532 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3533 * "Http://" converts to "http://"
3534 *
3535 * @return Original or modified URL
3536 *
3537 */
3538 String smartUrlFilter(String url) {
3539
3540 String inUrl = url.trim();
3541 boolean hasSpace = inUrl.indexOf(' ') != -1;
3542
3543 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3544 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003545 // force scheme to lowercase
3546 String scheme = matcher.group(1);
3547 String lcScheme = scheme.toLowerCase();
3548 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003549 inUrl = lcScheme + matcher.group(2);
3550 }
3551 if (hasSpace) {
3552 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003553 }
3554 return inUrl;
3555 }
3556 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003557 // FIXME: Is this the correct place to add to searches?
3558 // what if someone else calls this function?
3559 int shortcut = parseUrlShortcut(inUrl);
3560 if (shortcut != SHORTCUT_INVALID) {
3561 Browser.addSearchUrl(mResolver, inUrl);
3562 String query = inUrl.substring(2);
3563 switch (shortcut) {
3564 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003565 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003566 case SHORTCUT_WIKIPEDIA_SEARCH:
3567 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3568 case SHORTCUT_DICTIONARY_SEARCH:
3569 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3570 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003571 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003572 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003573 }
3574 }
3575 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003576 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003577 return URLUtil.guessUrl(inUrl);
3578 }
3579 }
3580
3581 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003582 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003583 }
3584
Ben Murdochbff2d602009-07-01 20:19:05 +01003585 /* package */ void setShouldShowErrorConsole(boolean flag) {
3586 if (flag == mShouldShowErrorConsole) {
3587 // Nothing to do.
3588 return;
3589 }
3590
3591 mShouldShowErrorConsole = flag;
3592
Grace Kloba22ac16e2009-10-07 18:00:23 -07003593 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3594 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003595
3596 if (flag) {
3597 // Setting the show state of the console will cause it's the layout to be inflated.
3598 if (errorConsole.numberOfErrors() > 0) {
3599 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3600 } else {
3601 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3602 }
3603
3604 // Now we can add it to the main view.
3605 mErrorConsoleContainer.addView(errorConsole,
3606 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
3607 ViewGroup.LayoutParams.WRAP_CONTENT));
3608 } else {
3609 mErrorConsoleContainer.removeView(errorConsole);
3610 }
3611
3612 }
3613
Grace Kloba22ac16e2009-10-07 18:00:23 -07003614 boolean shouldShowErrorConsole() {
3615 return mShouldShowErrorConsole;
3616 }
3617
Andrei Popescu163ab742009-10-20 17:58:23 +01003618 private void setStatusBarVisibility(boolean visible) {
3619 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3620 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3621 }
3622
Grace Klobaeb6eef42009-09-15 17:56:32 -07003623 final static int LOCK_ICON_UNSECURE = 0;
3624 final static int LOCK_ICON_SECURE = 1;
3625 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003626
The Android Open Source Project0c908882009-03-03 19:32:16 -08003627 private BrowserSettings mSettings;
3628 private TabControl mTabControl;
3629 private ContentResolver mResolver;
3630 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003631 private View mCustomView;
3632 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003633 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003634
3635 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3636 // view, we should rewrite this.
3637 private int mCurrentMenuState = 0;
3638 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003639 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003640 private static final int EMPTY_MENU = -1;
3641 private Menu mMenu;
3642
3643 private FindDialog mFindDialog;
3644 // Used to prevent chording to result in firing two shortcuts immediately
3645 // one after another. Fixes bug 1211714.
3646 boolean mCanChord;
3647
3648 private boolean mInLoad;
3649 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003650 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003651
The Android Open Source Project0c908882009-03-03 19:32:16 -08003652 private boolean mActivityInPause = true;
3653
3654 private boolean mMenuIsDown;
3655
The Android Open Source Project0c908882009-03-03 19:32:16 -08003656 private static boolean mInTrace;
3657
3658 // Performance probe
3659 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3660 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3661 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3662 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3663 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3664 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3665 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3666 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3667 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3668 };
3669
3670 private long mStart;
3671 private long mProcessStart;
3672 private long mUserStart;
3673 private long mSystemStart;
3674 private long mIdleStart;
3675 private long mIrqStart;
3676
3677 private long mUiStart;
3678
3679 private Drawable mMixLockIcon;
3680 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003681
3682 /* hold a ref so we can auto-cancel if necessary */
3683 private AlertDialog mAlertDialog;
3684
3685 // Wait for credentials before loading google.com
3686 private ProgressDialog mCredsDlg;
3687
3688 // The up-to-date URL and title (these can be different from those stored
3689 // in WebView, since it takes some time for the information in WebView to
3690 // get updated)
3691 private String mUrl;
3692 private String mTitle;
3693
3694 // As PageInfo has different style for landscape / portrait, we have
3695 // to re-open it when configuration changed
3696 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003697 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003698 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3699 // dialog, we should not just dismiss it, but should get back to the
3700 // SSL-certificate-on-error dialog. This flag is used to store this state
3701 private Boolean mPageInfoFromShowSSLCertificateOnError;
3702
3703 // as SSLCertificateOnError has different style for landscape / portrait,
3704 // we have to re-open it when configuration changed
3705 private AlertDialog mSSLCertificateOnErrorDialog;
3706 private WebView mSSLCertificateOnErrorView;
3707 private SslErrorHandler mSSLCertificateOnErrorHandler;
3708 private SslError mSSLCertificateOnErrorError;
3709
3710 // as SSLCertificate has different style for landscape / portrait, we
3711 // have to re-open it when configuration changed
3712 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003713 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003714
3715 // as HttpAuthentication has different style for landscape / portrait, we
3716 // have to re-open it when configuration changed
3717 private AlertDialog mHttpAuthenticationDialog;
3718 private HttpAuthHandler mHttpAuthHandler;
3719
3720 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3721 new FrameLayout.LayoutParams(
3722 ViewGroup.LayoutParams.FILL_PARENT,
3723 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003724 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3725 new FrameLayout.LayoutParams(
3726 ViewGroup.LayoutParams.FILL_PARENT,
3727 ViewGroup.LayoutParams.FILL_PARENT,
3728 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003729 // Google search
3730 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003731 // Wikipedia search
3732 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3733 // Dictionary search
3734 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3735 // Google Mobile Local search
3736 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3737
3738 final static String QUERY_PLACE_HOLDER = "%s";
3739
3740 // "source" parameter for Google search through search key
3741 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3742 // "source" parameter for Google search through goto menu
3743 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3744 // "source" parameter for Google search through simplily type
3745 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3746 // "source" parameter for Google search suggested by the browser
3747 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3748 // "source" parameter for Google search from unknown source
3749 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3750
3751 private final static String LOGTAG = "browser";
3752
The Android Open Source Project0c908882009-03-03 19:32:16 -08003753 private String mLastEnteredUrl;
3754
3755 private PowerManager.WakeLock mWakeLock;
3756 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3757
3758 private Toast mStopToast;
3759
Leon Scroggins68579392009-09-15 15:31:54 -04003760 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003761
Ben Murdochbff2d602009-07-01 20:19:05 +01003762 private LinearLayout mErrorConsoleContainer = null;
3763 private boolean mShouldShowErrorConsole = false;
3764
The Android Open Source Project0c908882009-03-03 19:32:16 -08003765 // As the ids are dynamically created, we can't guarantee that they will
3766 // be in sequence, so this static array maps ids to a window number.
3767 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3768 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3769 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3770 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3771
3772 // monitor platform changes
3773 private IntentFilter mNetworkStateChangedFilter;
3774 private BroadcastReceiver mNetworkStateIntentReceiver;
3775
Grace Klobab4da0ad2009-05-14 14:45:40 -07003776 private BroadcastReceiver mPackageInstallationReceiver;
3777
The Android Open Source Project0c908882009-03-03 19:32:16 -08003778 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003779 final static int COMBO_PAGE = 1;
3780 final static int DOWNLOAD_PAGE = 2;
3781 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003782 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003783
Andrei Popescu540035d2009-09-18 18:59:20 +01003784 // the default <video> poster
3785 private Bitmap mDefaultVideoPoster;
3786 // the video progress view
3787 private View mVideoProgressView;
3788
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003789 /**
3790 * A UrlData class to abstract how the content will be set to WebView.
3791 * This base class uses loadUrl to show the content.
3792 */
3793 private static class UrlData {
3794 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07003795 byte[] mPostData;
3796
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003797 UrlData(String url) {
3798 this.mUrl = url;
3799 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003800
3801 void setPostData(byte[] postData) {
3802 mPostData = postData;
3803 }
3804
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003805 boolean isEmpty() {
3806 return mUrl == null || mUrl.length() == 0;
3807 }
3808
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003809 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07003810 if (mPostData != null) {
3811 webView.postUrl(mUrl, mPostData);
3812 } else {
3813 webView.loadUrl(mUrl);
3814 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003815 }
3816 };
3817
3818 /**
3819 * A subclass of UrlData class that can display inlined content using
3820 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
3821 */
3822 private static class InlinedUrlData extends UrlData {
3823 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
3824 super(failUrl);
3825 mInlined = inlined;
3826 mMimeType = mimeType;
3827 mEncoding = encoding;
3828 }
3829 String mMimeType;
3830 String mInlined;
3831 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003832 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003833 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01003834 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003835 }
3836
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003837 @Override
3838 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003839 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
3840 }
3841 }
3842
Leon Scroggins1f005d32009-08-10 17:36:42 -04003843 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003844}