blob: 8afd3b4c6ced0edd6c17c7875ae0adee9e44a255 [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;
Leon Scroggins58d56c62010-01-28 15:12:40 -050026import android.content.ContentProvider;
27import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080028import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040029import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080030import android.content.ContentValues;
31import android.content.Context;
32import android.content.DialogInterface;
33import android.content.Intent;
34import android.content.IntentFilter;
Grace Klobab4da0ad2009-05-14 14:45:40 -070035import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080036import android.content.pm.PackageManager;
37import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080038import android.content.res.Configuration;
39import android.content.res.Resources;
40import android.database.Cursor;
The Android Open Source Project0c908882009-03-03 19:32:16 -080041import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010042import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080043import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080044import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040045import android.graphics.PixelFormat;
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;
Andrei Popescu56199cc2010-01-12 22:39:16 +000048import 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;
The Android Open Source Project0c908882009-03-03 19:32:16 -080058import android.os.Message;
59import android.os.PowerManager;
60import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080061import android.os.ServiceManager;
62import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080063import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040064import android.provider.ContactsContract;
The Android Open Source Project0c908882009-03-03 19:32:16 -080065import android.provider.Downloads;
66import android.provider.MediaStore;
Michael Kolbe0a36662010-06-29 10:37:12 -070067import android.provider.ContactsContract.Intents.Insert;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050068import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080069import android.text.IClipboard;
70import android.text.TextUtils;
71import android.text.format.DateFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080072import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080073import android.util.Patterns;
The Android Open Source Project0c908882009-03-03 19:32:16 -080074import android.view.ContextMenu;
75import android.view.Gravity;
76import android.view.KeyEvent;
77import android.view.LayoutInflater;
78import android.view.Menu;
79import android.view.MenuInflater;
80import android.view.MenuItem;
81import android.view.View;
82import android.view.ViewGroup;
83import android.view.Window;
84import android.view.WindowManager;
85import android.view.ContextMenu.ContextMenuInfo;
86import android.view.MenuItem.OnMenuItemClickListener;
Svetoslav Ganov2b345992010-05-06 06:13:54 -070087import android.view.accessibility.AccessibilityManager;
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
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000106import com.android.common.Search;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500107import com.android.common.speech.LoggingEvents;
Dan Egnor5ee906c2009-11-18 12:11:49 -0800108
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400109import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800110import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000111import java.io.IOException;
112import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800113import java.net.MalformedURLException;
Dianne Hackborn99189432009-06-17 18:06:18 -0700114import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800115import java.net.URL;
116import java.net.URLEncoder;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800117import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800118import java.util.HashMap;
Andrei Popescu30995e72010-02-09 16:59:58 +0000119import java.util.HashSet;
Grace Kloba00f54c52010-01-27 14:53:51 -0800120import java.util.Iterator;
Andrei Popescu30995e72010-02-09 16:59:58 +0000121import java.util.List;
Grace Kloba068e48b2010-01-26 18:11:27 -0800122import java.util.Map;
Andrei Popescu30995e72010-02-09 16:59:58 +0000123import java.util.Set;
Michael Kolbfe251992010-07-08 15:41:55 -0700124import java.util.Vector;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800125import java.util.regex.Matcher;
126import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800127
128public class BrowserActivity extends Activity
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700129 implements View.OnCreateContextMenuListener, DownloadListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800130
Dave Bort31a6d1c2009-04-13 15:56:49 -0700131 /* Define some aliases to make these debugging flags easier to refer to.
132 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
133 */
134 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
135 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
136 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
137
Satish Sampath565505b2009-05-29 15:37:27 +0100138 // These are single-character shortcuts for searching popular sources.
139 private static final int SHORTCUT_INVALID = 0;
140 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
141 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
142 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
143 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
144
Cary Clarka9771242009-08-11 16:42:26 -0400145 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800146 @Override
147 public Void doInBackground(File... files) {
148 if (files != null) {
149 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400150 if (!f.delete()) {
151 Log.e(LOGTAG, f.getPath() + " was not deleted");
152 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800153 }
154 }
155 return null;
156 }
157 }
158
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400159 /**
160 * This layout holds everything you see below the status bar, including the
161 * error console, the custom view container, and the webviews.
162 */
163 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400164
Leon Scrogginsd746a942010-05-19 13:21:44 -0400165 private boolean mXLargeScreenSize;
166
Grace Kloba22ac16e2009-10-07 18:00:23 -0700167 @Override
168 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700169 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800170 Log.v(LOGTAG, this + " onStart");
171 }
172 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800173 // test the browser in OpenGL
174 // requestWindowFeature(Window.FEATURE_OPENGL);
175
Mike Reedd334bf52010-01-26 15:21:44 -0500176 // enable this to test the browser in 32bit
177 if (false) {
178 getWindow().setFormat(PixelFormat.RGBX_8888);
179 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
180 }
181
Svetoslav Ganov2b345992010-05-06 06:13:54 -0700182 if (AccessibilityManager.getInstance(this).isEnabled()) {
183 setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
184 } else {
185 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
186 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800187
188 mResolver = getContentResolver();
189
Grace Kloba0923d692009-09-23 21:37:25 -0700190 // If this was a web search request, pass it on to the default web
191 // search provider and finish this activity.
192 if (handleWebSearchIntent(getIntent())) {
193 finish();
194 return;
195 }
196
The Android Open Source Project0c908882009-03-03 19:32:16 -0800197 mSecLockIcon = Resources.getSystem().getDrawable(
198 android.R.drawable.ic_secure);
199 mMixLockIcon = Resources.getSystem().getDrawable(
200 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800201
Leon Scroggins81db3662009-06-04 17:45:11 -0400202 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
203 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400204 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
205 .inflate(R.layout.custom_screen, null);
206 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
207 R.id.main_content);
208 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
209 .findViewById(R.id.error_console);
210 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
211 .findViewById(R.id.fullscreen_custom_content);
212 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400213 mXLargeScreenSize = (getResources().getConfiguration().screenLayout
214 & Configuration.SCREENLAYOUT_SIZE_MASK)
215 == Configuration.SCREENLAYOUT_SIZE_XLARGE;
Michael Kolbe0a36662010-06-29 10:37:12 -0700216
Michael Kolbfe251992010-07-08 15:41:55 -0700217 // Create the tab control and our initial tab
218 mTabControl = new TabControl(this);
219
220
Leon Scrogginsd746a942010-05-19 13:21:44 -0400221 if (mXLargeScreenSize) {
Michael Kolbfe251992010-07-08 15:41:55 -0700222 mTitleBar = new TitleBarXLarge(this, mTabControl);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400223 LinearLayout layout = (LinearLayout) mBrowserFrameLayout.
224 findViewById(R.id.vertical_layout);
225 layout.addView(mTitleBar, 0, new LinearLayout.LayoutParams(
226 ViewGroup.LayoutParams.MATCH_PARENT,
227 ViewGroup.LayoutParams.WRAP_CONTENT));
228 } else {
Leon Scroggins571b3762010-05-26 10:25:01 -0400229 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400230 // mTitleBar will be always be shown in the fully loaded mode on
231 // phone
232 mTitleBar.setProgress(100);
233 // Fake title bar is not needed in xlarge layout
234 mFakeTitleBar = new TitleBar(this);
235 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800236
The Android Open Source Project0c908882009-03-03 19:32:16 -0800237
238 // Open the icon database and retain all the bookmark urls for favicons
239 retainIconsOnStartup();
240
241 // Keep a settings instance handy.
242 mSettings = BrowserSettings.getInstance();
243 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800244
245 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
246 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
247
Patrick Scott6adacc92010-03-05 08:24:51 -0500248 // Find out if the network is currently up.
249 ConnectivityManager cm = (ConnectivityManager) getSystemService(
250 Context.CONNECTIVITY_SERVICE);
251 NetworkInfo info = cm.getActiveNetworkInfo();
252 if (info != null) {
253 mIsNetworkUp = info.isAvailable();
254 }
255
Grace Klobaa34f6862009-07-31 16:28:17 -0700256 /* enables registration for changes in network status from
257 http stack */
258 mNetworkStateChangedFilter = new IntentFilter();
259 mNetworkStateChangedFilter.addAction(
260 ConnectivityManager.CONNECTIVITY_ACTION);
261 mNetworkStateIntentReceiver = new BroadcastReceiver() {
262 @Override
263 public void onReceive(Context context, Intent intent) {
264 if (intent.getAction().equals(
265 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000266
267 NetworkInfo info = intent.getParcelableExtra(
268 ConnectivityManager.EXTRA_NETWORK_INFO);
269 String typeName = info.getTypeName();
270 String subtypeName = info.getSubtypeName();
271 sendNetworkType(typeName.toLowerCase(),
272 (subtypeName != null ? subtypeName.toLowerCase() : ""));
273
274 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700275 }
276 }
277 };
278
Grace Kloba615c6c92009-08-03 10:22:44 -0700279 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
280 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
281 filter.addDataScheme("package");
282 mPackageInstallationReceiver = new BroadcastReceiver() {
283 @Override
284 public void onReceive(Context context, Intent intent) {
285 final String action = intent.getAction();
286 final String packageName = intent.getData()
287 .getSchemeSpecificPart();
288 final boolean replacing = intent.getBooleanExtra(
289 Intent.EXTRA_REPLACING, false);
290 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
291 // if it is replacing, refreshPlugins() when adding
292 return;
293 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000294
295 if (sGoogleApps.contains(packageName)) {
296 BrowserActivity.this.packageChanged(packageName,
297 Intent.ACTION_PACKAGE_ADDED.equals(action));
298 }
299
Grace Kloba615c6c92009-08-03 10:22:44 -0700300 PackageManager pm = BrowserActivity.this.getPackageManager();
301 PackageInfo pkgInfo = null;
302 try {
303 pkgInfo = pm.getPackageInfo(packageName,
304 PackageManager.GET_PERMISSIONS);
305 } catch (PackageManager.NameNotFoundException e) {
306 return;
307 }
308 if (pkgInfo != null) {
309 String permissions[] = pkgInfo.requestedPermissions;
310 if (permissions == null) {
311 return;
312 }
313 boolean permissionOk = false;
314 for (String permit : permissions) {
315 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
316 permissionOk = true;
317 break;
318 }
319 }
320 if (permissionOk) {
321 PluginManager.getInstance(BrowserActivity.this)
Grace Klobae56a0f22010-05-26 17:31:02 -0700322 .refreshPlugins(true);
Grace Kloba615c6c92009-08-03 10:22:44 -0700323 }
324 }
325 }
326 };
327 registerReceiver(mPackageInstallationReceiver, filter);
328
The Android Open Source Project0c908882009-03-03 19:32:16 -0800329 if (!mTabControl.restoreState(icicle)) {
330 // clear up the thumbnail directory if we can't restore the state as
331 // none of the files in the directory are referenced any more.
332 new ClearThumbnails().execute(
333 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700334 // there is no quit on Android. But if we can't restore the state,
335 // we can treat it as a new Browser, remove the old session cookies.
336 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800337 final Intent intent = getIntent();
338 final Bundle extra = intent.getExtras();
339 // Create an initial tab.
340 // If the intent is ACTION_VIEW and data is not null, the Browser is
341 // invoked to view the content by another application. In this case,
342 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700343 UrlData urlData = getUrlDataFromIntent(intent);
344
Leon Scroggins58d56c62010-01-28 15:12:40 -0500345 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700346 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500347 (Intent.ACTION_VIEW.equals(action) &&
348 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500349 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
350 .equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700351 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800352 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800353 attachTabToContentView(t);
354 WebView webView = t.getWebView();
355 if (extra != null) {
356 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
357 if (scale > 0 && scale <= 1000) {
358 webView.setInitialScale(scale);
359 }
360 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800361
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700362 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700363 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800364 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500365 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800366 }
367 } else {
368 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400369 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800370 attachTabToContentView(mTabControl.getCurrentTab());
371 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700372
Cary Clarkb4b83182010-07-01 12:36:56 -0400373 // Delete old thumbnails to save space
374 File dir = mTabControl.getThumbnailDir();
375 if (dir.exists()) {
376 for (String child : dir.list()) {
377 File f = new File(dir, child);
378 f.delete();
379 }
380 }
381
Feng Qianb3c02da2009-06-29 15:58:08 -0700382 // Read JavaScript flags if it exists.
383 String jsFlags = mSettings.getJsFlags();
384 if (jsFlags.trim().length() != 0) {
385 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
386 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000387 // Work out which packages are installed on the system.
388 getInstalledPackages();
Bjorn Bringerta7611812010-03-24 11:12:02 +0000389
390 // Start watching the default geolocation permissions
391 mSystemAllowGeolocationOrigins
392 = new SystemAllowGeolocationOrigins(getApplicationContext());
393 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800394 }
395
Leon Scroggins58d56c62010-01-28 15:12:40 -0500396 /**
397 * Feed the previously stored results strings to the BrowserProvider so that
398 * the SearchDialog will show them instead of the standard searches.
399 * @param result String to show on the editable line of the SearchDialog.
400 */
401 /* package */ void showVoiceSearchResults(String result) {
402 ContentProviderClient client = mResolver.acquireContentProviderClient(
403 Browser.BOOKMARKS_URI);
404 ContentProvider prov = client.getLocalContentProvider();
405 BrowserProvider bp = (BrowserProvider) prov;
406 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
407 client.release();
408
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500409 Bundle bundle = createGoogleSearchSourceBundle(
410 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
411 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
412 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500413 }
414
The Android Open Source Project0c908882009-03-03 19:32:16 -0800415 @Override
416 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700417 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800418 // When a tab is closed on exit, the current tab index is set to -1.
419 // Reset before proceed as Browser requires the current tab to be set.
420 if (current == null) {
421 // Try to reset the tab in case the index was incorrect.
422 current = mTabControl.getTab(0);
423 if (current == null) {
424 // No tabs at all so just ignore this intent.
425 return;
426 }
427 mTabControl.setCurrentTab(current);
428 attachTabToContentView(current);
429 resetTitleAndIcon(current.getWebView());
430 }
431 final String action = intent.getAction();
432 final int flags = intent.getFlags();
433 if (Intent.ACTION_MAIN.equals(action) ||
434 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
435 // just resume the browser
436 return;
437 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400438 // In case the SearchDialog is open.
439 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
440 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500441 boolean activateVoiceSearch = RecognizerResultsIntent
442 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800443 if (Intent.ACTION_VIEW.equals(action)
444 || Intent.ACTION_SEARCH.equals(action)
445 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500446 || Intent.ACTION_WEB_SEARCH.equals(action)
447 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500448 if (current.isInVoiceSearchMode()) {
449 String title = current.getVoiceDisplayTitle();
450 if (title != null && title.equals(intent.getStringExtra(
451 SearchManager.QUERY))) {
452 // The user submitted the same search as the last voice
453 // search, so do nothing.
454 return;
455 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500456 if (Intent.ACTION_SEARCH.equals(action)
457 && current.voiceSearchSourceIsGoogle()) {
458 Intent logIntent = new Intent(
459 LoggingEvents.ACTION_LOG_EVENT);
460 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
461 LoggingEvents.VoiceSearch.QUERY_UPDATED);
462 logIntent.putExtra(
463 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
464 intent.getDataString());
465 sendBroadcast(logIntent);
466 // Note, onPageStarted will revert the voice title bar
467 // When http://b/issue?id=2379215 is fixed, we should update
468 // the title bar here.
469 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500470 }
Satish Sampath565505b2009-05-29 15:37:27 +0100471 // If this was a search request (e.g. search query directly typed into the address bar),
472 // pass it on to the default web search provider.
473 if (handleWebSearchIntent(intent)) {
474 return;
475 }
476
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700477 UrlData urlData = getUrlDataFromIntent(intent);
478 if (urlData.isEmpty()) {
479 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800480 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700481
Grace Klobacc634032009-07-28 15:58:19 -0700482 final String appId = intent
483 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400484 if ((Intent.ACTION_VIEW.equals(action)
485 // If a voice search has no appId, it means that it came
486 // from the browser. In that case, reuse the current tab.
487 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700488 && !getPackageName().equals(appId)
489 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700490 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700491 if (appTab != null) {
492 Log.i(LOGTAG, "Reusing tab for " + appId);
493 // Dismiss the subwindow if applicable.
494 dismissSubWindow(appTab);
495 // Since we might kill the WebView, remove it from the
496 // content view first.
497 removeTabFromContentView(appTab);
498 // Recreate the main WebView after destroying the old one.
499 // If the WebView has the same original url and is on that
500 // page, it can be reused.
501 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400502 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100503
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700504 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400505 switchToTab(mTabControl.getTabIndex(appTab));
506 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500507 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400508 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700509 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400510 // If the tab was the current tab, we have to attach
511 // it to the view system again.
512 attachTabToContentView(appTab);
513 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500514 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700515 }
516 }
517 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400518 } else {
519 // No matching application tab, try to find a regular tab
520 // with a matching url.
521 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400522 if (appTab != null) {
523 if (current != appTab) {
524 switchToTab(mTabControl.getTabIndex(appTab));
525 }
526 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400527 } else {
528 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
529 // will be opened in a new tab unless we have reached
530 // MAX_TABS. Then the url will be opened in the current
531 // tab. If a new tab is created, it will have "true" for
532 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400533 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400534 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700535 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800536 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800537 if (!urlData.isEmpty()
538 && urlData.mUrl.startsWith("about:debug")) {
539 if ("about:debug.dom".equals(urlData.mUrl)) {
540 current.getWebView().dumpDomTree(false);
541 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
542 current.getWebView().dumpDomTree(true);
543 } else if ("about:debug.render".equals(urlData.mUrl)) {
544 current.getWebView().dumpRenderTree(false);
545 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
546 current.getWebView().dumpRenderTree(true);
547 } else if ("about:debug.display".equals(urlData.mUrl)) {
548 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800549 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
550 int index = urlData.mUrl.codePointAt(16) - '0';
551 if (index <= 0 || index > 9) {
552 current.getWebView().setDragTracker(null);
553 } else {
554 current.getWebView().setDragTracker(new MeshTracker(index));
555 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800556 } else {
557 mSettings.toggleDebugSettings();
558 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800559 return;
560 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400561 // Get rid of the subwindow if it exists
562 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400563 // If the current Tab is being used as an application tab,
564 // remove the association, since the new Intent means that it is
565 // no longer associated with that application.
566 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500567 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800568 }
569 }
570 }
571
Satish Sampath565505b2009-05-29 15:37:27 +0100572 private int parseUrlShortcut(String url) {
573 if (url == null) return SHORTCUT_INVALID;
574
575 // FIXME: quick search, need to be customized by setting
576 if (url.length() > 2 && url.charAt(1) == ' ') {
577 switch (url.charAt(0)) {
578 case 'g': return SHORTCUT_GOOGLE_SEARCH;
579 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
580 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
581 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
582 }
583 }
584 return SHORTCUT_INVALID;
585 }
586
587 /**
588 * Launches the default web search activity with the query parameters if the given intent's data
589 * are identified as plain search terms and not URLs/shortcuts.
590 * @return true if the intent was handled and web search activity was launched, false if not.
591 */
592 private boolean handleWebSearchIntent(Intent intent) {
593 if (intent == null) return false;
594
595 String url = null;
596 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500597 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
598 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500599 return false;
600 }
Satish Sampath565505b2009-05-29 15:37:27 +0100601 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700602 Uri data = intent.getData();
603 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100604 } else if (Intent.ACTION_SEARCH.equals(action)
605 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
606 || Intent.ACTION_WEB_SEARCH.equals(action)) {
607 url = intent.getStringExtra(SearchManager.QUERY);
608 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100609 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
610 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100611 }
612
613 /**
614 * Launches the default web search activity with the query parameters if the given url string
615 * was identified as plain search terms and not URL/shortcut.
616 * @return true if the request was handled and web search activity was launched, false if not.
617 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100618 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100619 if (inUrl == null) return false;
620
621 // In general, we shouldn't modify URL from Intent.
622 // But currently, we get the user-typed URL from search box as well.
623 String url = fixUrl(inUrl).trim();
624
625 // URLs and site specific search shortcuts are handled by the regular flow of control, so
626 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800627 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100628 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100629 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
630 return false;
631 }
632
Leon Scroggins8d06e362010-03-24 14:45:57 -0400633 final ContentResolver cr = mResolver;
634 final String newUrl = url;
635 new AsyncTask<Void, Void, Void>() {
Michael Kolbe0a36662010-06-29 10:37:12 -0700636 @Override
Leon Scroggins8d06e362010-03-24 14:45:57 -0400637 protected Void doInBackground(Void... unused) {
638 Browser.updateVisitedHistory(cr, newUrl, false);
639 Browser.addSearchUrl(cr, newUrl);
640 return null;
641 }
642 }.execute();
Satish Sampath565505b2009-05-29 15:37:27 +0100643
644 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
645 intent.addCategory(Intent.CATEGORY_DEFAULT);
646 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100647 if (appData != null) {
648 intent.putExtra(SearchManager.APP_DATA, appData);
649 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100650 if (extraData != null) {
651 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
652 }
Grace Klobacc634032009-07-28 15:58:19 -0700653 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100654 startActivity(intent);
655
656 return true;
657 }
658
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700659 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500660 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800661 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800662 if (intent != null) {
663 final String action = intent.getAction();
664 if (Intent.ACTION_VIEW.equals(action)) {
665 url = smartUrlFilter(intent.getData());
666 if (url != null && url.startsWith("content:")) {
667 /* Append mimetype so webview knows how to display */
668 String mimeType = intent.resolveType(getContentResolver());
669 if (mimeType != null) {
670 url += "?" + mimeType;
671 }
672 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800673 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800674 final Bundle pairs = intent
675 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800676 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800677 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800678 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800679 while (iter.hasNext()) {
680 String key = iter.next();
681 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800682 }
683 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700684 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800685 } else if (Intent.ACTION_SEARCH.equals(action)
686 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
687 || Intent.ACTION_WEB_SEARCH.equals(action)) {
688 url = intent.getStringExtra(SearchManager.QUERY);
689 if (url != null) {
690 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800691 // In general, we shouldn't modify URL from Intent.
692 // But currently, we get the user-typed URL from search box as well.
693 url = fixUrl(url);
694 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400695 final ContentResolver cr = mResolver;
696 final String newUrl = url;
697 new AsyncTask<Void, Void, Void>() {
Michael Kolbe0a36662010-06-29 10:37:12 -0700698 @Override
Leon Scroggins8d06e362010-03-24 14:45:57 -0400699 protected Void doInBackground(Void... unused) {
700 Browser.updateVisitedHistory(cr, newUrl, false);
701 return null;
702 }
703 }.execute();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800704 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
705 if (url.contains(searchSource)) {
706 String source = null;
707 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
708 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000709 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800710 }
711 if (TextUtils.isEmpty(source)) {
712 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
713 }
714 url = url.replace(searchSource, "&source=android-"+source+"&");
715 }
716 }
717 }
718 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500719 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800720 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500721 /* package */ void showVoiceTitleBar(String title) {
722 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500723 mTitleBar.setDisplayTitle(title);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400724
725 if (!mXLargeScreenSize) {
726 mFakeTitleBar.setInVoiceMode(true);
727 mFakeTitleBar.setDisplayTitle(title);
728 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500729 }
730 /* package */ void revertVoiceTitleBar() {
731 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500732 mTitleBar.setDisplayTitle(mUrl);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400733
734 if (!mXLargeScreenSize) {
735 mFakeTitleBar.setInVoiceMode(false);
736 mFakeTitleBar.setDisplayTitle(mUrl);
737 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500738 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800739 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400740 // FIXME: Converting the url to lower case
741 // duplicates functionality in smartUrlFilter().
742 // However, changing all current callers of fixUrl to
743 // call smartUrlFilter in addition may have unwanted
744 // consequences, and is deferred for now.
745 int colon = inUrl.indexOf(':');
746 boolean allLower = true;
747 for (int index = 0; index < colon; index++) {
748 char ch = inUrl.charAt(index);
749 if (!Character.isLetter(ch)) {
750 break;
751 }
752 allLower &= Character.isLowerCase(ch);
753 if (index == colon - 1 && !allLower) {
754 inUrl = inUrl.substring(0, colon).toLowerCase()
755 + inUrl.substring(colon);
756 }
757 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800758 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
759 return inUrl;
760 if (inUrl.startsWith("http:") ||
761 inUrl.startsWith("https:")) {
762 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
763 inUrl = inUrl.replaceFirst("/", "//");
764 } else inUrl = inUrl.replaceFirst(":", "://");
765 }
766 return inUrl;
767 }
768
Grace Kloba22ac16e2009-10-07 18:00:23 -0700769 @Override
770 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800771 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700772 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800773 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
774 }
775
776 if (!mActivityInPause) {
777 Log.e(LOGTAG, "BrowserActivity is already resumed.");
778 return;
779 }
780
Mike Reed7bfa63b2009-05-28 11:08:32 -0400781 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800782 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400783 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800784
785 if (mWakeLock.isHeld()) {
786 mHandler.removeMessages(RELEASE_WAKELOCK);
787 mWakeLock.release();
788 }
789
The Android Open Source Project0c908882009-03-03 19:32:16 -0800790 registerReceiver(mNetworkStateIntentReceiver,
791 mNetworkStateChangedFilter);
792 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800793 }
794
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400795 /**
796 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400797 * would change its appearance, use a different TitleBar to show overlayed
798 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400799 */
800 private TitleBar mFakeTitleBar;
801
802 /**
803 * Keeps track of whether the options menu is open. This is important in
804 * determining whether to show or hide the title bar overlay.
805 */
806 private boolean mOptionsMenuOpen;
807
808 /**
809 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
810 * of whether the configuration has changed. The first onMenuOpened call
811 * after a configuration change is simply a reopening of the same menu
812 * (i.e. mIconView did not change).
813 */
814 private boolean mConfigChanged;
815
816 /**
817 * Whether or not the options menu is in its smaller, icon menu form. When
818 * true, we want the title bar overlay to be up. When false, we do not.
819 * Only meaningful if mOptionsMenuOpen is true.
820 */
821 private boolean mIconView;
822
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400823 @Override
824 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400825 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
826 if (mOptionsMenuOpen) {
827 if (mConfigChanged) {
828 // We do not need to make any changes to the state of the
829 // title bar, since the only thing that happened was a
830 // change in orientation
831 mConfigChanged = false;
832 } else {
833 if (mIconView) {
834 // Switching the menu to expanded view, so hide the
835 // title bar.
836 hideFakeTitleBar();
837 mIconView = false;
838 } else {
839 // Switching the menu back to icon view, so show the
840 // title bar once again.
841 showFakeTitleBar();
842 mIconView = true;
843 }
844 }
845 } else {
846 // The options menu is closed, so open it, and show the title
847 showFakeTitleBar();
848 mOptionsMenuOpen = true;
849 mConfigChanged = false;
850 mIconView = true;
851 }
852 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400853 return true;
854 }
855
Michael Kolbfe251992010-07-08 15:41:55 -0700856 private void rebuildTitleBar() {
857 if (mXLargeScreenSize) {
858 ((TitleBarXLarge) mTitleBar).rebuildLayout();
859 }
860 }
861
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400862 private void showFakeTitleBar() {
Leon Scrogginsd746a942010-05-19 13:21:44 -0400863 if (mXLargeScreenSize) return;
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400864 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Grace Kloba847c25b2010-03-30 16:00:26 -0700865 && !mActivityInPause) {
866 WebView mainView = mTabControl.getCurrentWebView();
867 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700868 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400869 return;
870 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100871 // Do not need to check for null, since the current tab will have
872 // at least a main WebView, or we would have returned above.
Cary Clark01cfcdd2010-06-04 16:36:45 -0400873 if (dialogIsUp()) {
Leon Scroggins79e36d92010-04-29 16:01:46 +0100874 // Do not show the fake title bar, which would cover up the
Cary Clark01cfcdd2010-06-04 16:36:45 -0400875 // find or select dialog.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100876 return;
877 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400878
879 WindowManager manager
880 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
881
882 // Add the title bar to the window manager so it can receive touches
883 // while the menu is up
884 WindowManager.LayoutParams params
885 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800886 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400887 ViewGroup.LayoutParams.WRAP_CONTENT,
Grace Kloba847c25b2010-03-30 16:00:26 -0700888 WindowManager.LayoutParams.TYPE_APPLICATION,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400889 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400890 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400891 params.gravity = Gravity.TOP;
Grace Kloba847c25b2010-03-30 16:00:26 -0700892 boolean atTop = mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400893 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Grace Kloba13f9ace2010-03-18 21:44:14 -0700894 manager.addView(mFakeTitleBar, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400895 }
896 }
897
898 @Override
899 public void onOptionsMenuClosed(Menu menu) {
900 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400901 if (!mInLoad) {
902 hideFakeTitleBar();
903 } else if (!mIconView) {
904 // The page is currently loading, and we are in expanded mode, so
905 // we were not showing the menu. Show it once again. It will be
906 // removed when the page finishes.
907 showFakeTitleBar();
908 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400909 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700910
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400911 private void hideFakeTitleBar() {
Leon Scrogginsd746a942010-05-19 13:21:44 -0400912 if (mXLargeScreenSize || mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400913 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
Grace Kloba13f9ace2010-03-18 21:44:14 -0700914 mFakeTitleBar.getLayoutParams();
Leon Scroggins20329572009-09-23 17:42:41 -0400915 WebView mainView = mTabControl.getCurrentWebView();
916 // Although we decided whether or not to animate based on the current
917 // scroll position, the scroll position may have changed since the
918 // fake title bar was displayed. Make sure it has the appropriate
919 // animation/lack thereof before removing.
920 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400921 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400922 WindowManager manager
923 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Grace Kloba13f9ace2010-03-18 21:44:14 -0700924 manager.updateViewLayout(mFakeTitleBar, params);
925 manager.removeView(mFakeTitleBar);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400926 }
927
The Android Open Source Project0c908882009-03-03 19:32:16 -0800928 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400929 * Special method for the fake title bar to call when displaying its context
930 * menu, since it is in its own Window, and its parent does not show a
931 * context menu.
932 */
933 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400934 if (null == mTitleBar.getParent()) {
935 return;
936 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400937 openContextMenu(mTitleBar);
938 }
939
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400940 @Override
941 public void onContextMenuClosed(Menu menu) {
942 super.onContextMenuClosed(menu);
943 if (mInLoad) {
944 showFakeTitleBar();
945 }
946 }
947
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400948 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800949 * onSaveInstanceState(Bundle map)
950 * onSaveInstanceState is called right before onStop(). The map contains
951 * the saved state.
952 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700953 @Override
954 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700955 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800956 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
957 }
958 // the default implementation requires each view to have an id. As the
959 // browser handles the state itself and it doesn't use id for the views,
960 // don't call the default implementation. Otherwise it will trigger the
961 // warning like this, "couldn't save which view has focus because the
962 // focused view XXX has no id".
963
964 // Save all the tabs
965 mTabControl.saveState(outState);
966 }
967
Grace Kloba22ac16e2009-10-07 18:00:23 -0700968 @Override
969 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800970 super.onPause();
971
972 if (mActivityInPause) {
973 Log.e(LOGTAG, "BrowserActivity is already paused.");
974 return;
975 }
976
Mike Reed7bfa63b2009-05-28 11:08:32 -0400977 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800978 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400979 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800980 mWakeLock.acquire();
981 mHandler.sendMessageDelayed(mHandler
982 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
983 }
984
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400985 // FIXME: This removes the active tabs page and resets the menu to
986 // MAIN_MENU. A better solution might be to do this work in onNewIntent
987 // but then we would need to save it in onSaveInstanceState and restore
988 // it in onCreate/onRestoreInstanceState
989 if (mActiveTabsPage != null) {
990 removeActiveTabPage(true);
991 }
992
The Android Open Source Project0c908882009-03-03 19:32:16 -0800993 cancelStopToast();
994
995 // unregister network state listener
996 unregisterReceiver(mNetworkStateIntentReceiver);
997 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800998 }
999
Grace Kloba22ac16e2009-10-07 18:00:23 -07001000 @Override
1001 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001002 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001003 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1004 }
1005 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001006
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001007 if (mUploadMessage != null) {
1008 mUploadMessage.onReceiveValue(null);
1009 mUploadMessage = null;
1010 }
1011
Grace Kloba0923d692009-09-23 21:37:25 -07001012 if (mTabControl == null) return;
1013
Grace Kloba1fc98a32009-10-21 13:23:08 -07001014 // Remove the fake title bar if it is there
1015 hideFakeTitleBar();
1016
The Android Open Source Project0c908882009-03-03 19:32:16 -08001017 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001018 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001019 if (t != null) {
1020 dismissSubWindow(t);
1021 removeTabFromContentView(t);
1022 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001023 // Destroy all the tabs
1024 mTabControl.destroy();
1025 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001026
Grace Klobab4da0ad2009-05-14 14:45:40 -07001027 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +00001028
1029 // Stop watching the default geolocation permissions
1030 mSystemAllowGeolocationOrigins.stop();
1031 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001032 }
1033
1034 @Override
1035 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001036 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001037 super.onConfigurationChanged(newConfig);
1038
1039 if (mPageInfoDialog != null) {
1040 mPageInfoDialog.dismiss();
1041 showPageInfo(
1042 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001043 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001044 }
1045 if (mSSLCertificateDialog != null) {
1046 mSSLCertificateDialog.dismiss();
1047 showSSLCertificate(
1048 mSSLCertificateView);
1049 }
1050 if (mSSLCertificateOnErrorDialog != null) {
1051 mSSLCertificateOnErrorDialog.dismiss();
1052 showSSLCertificateOnError(
1053 mSSLCertificateOnErrorView,
1054 mSSLCertificateOnErrorHandler,
1055 mSSLCertificateOnErrorError);
1056 }
1057 if (mHttpAuthenticationDialog != null) {
1058 String title = ((TextView) mHttpAuthenticationDialog
1059 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1060 .toString();
1061 String name = ((TextView) mHttpAuthenticationDialog
1062 .findViewById(R.id.username_edit)).getText().toString();
1063 String password = ((TextView) mHttpAuthenticationDialog
1064 .findViewById(R.id.password_edit)).getText().toString();
1065 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1066 .getId();
1067 mHttpAuthenticationDialog.dismiss();
1068 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1069 name, password, focusId);
1070 }
Michael Kolbfe251992010-07-08 15:41:55 -07001071 rebuildTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001072 }
1073
Grace Kloba22ac16e2009-10-07 18:00:23 -07001074 @Override
1075 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001076 super.onLowMemory();
1077 mTabControl.freeMemory();
1078 }
1079
Cary Clarkff4d92c2010-03-25 11:17:03 -04001080 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001081 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001082 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001083 boolean inLoad = tab.inLoad();
1084 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001085 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001086 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001087 if (w != null) {
1088 w.resumeTimers();
1089 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001090 }
1091 }
1092
Mike Reed7bfa63b2009-05-28 11:08:32 -04001093 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001094 Tab tab = mTabControl.getCurrentTab();
1095 boolean inLoad = tab.inLoad();
1096 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001097 CookieSyncManager.getInstance().stopSync();
1098 WebView w = mTabControl.getCurrentWebView();
1099 if (w != null) {
1100 w.pauseTimers();
1101 }
1102 return true;
1103 } else {
1104 return false;
1105 }
1106 }
1107
The Android Open Source Project0c908882009-03-03 19:32:16 -08001108 // Open the icon database and retain all the icons for visited sites.
1109 private void retainIconsOnStartup() {
1110 final WebIconDatabase db = WebIconDatabase.getInstance();
1111 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001112 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001113 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001114 c = Browser.getAllBookmarks(mResolver);
1115 if (c.moveToFirst()) {
1116 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1117 do {
1118 String url = c.getString(urlIndex);
1119 db.retainIconForPageUrl(url);
1120 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001121 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001122 } catch (IllegalStateException e) {
1123 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001124 } finally {
1125 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001126 }
1127 }
1128
1129 // Helper method for getting the top window.
1130 WebView getTopWindow() {
1131 return mTabControl.getCurrentTopWebView();
1132 }
1133
Grace Kloba22ac16e2009-10-07 18:00:23 -07001134 TabControl getTabControl() {
1135 return mTabControl;
1136 }
1137
The Android Open Source Project0c908882009-03-03 19:32:16 -08001138 @Override
1139 public boolean onCreateOptionsMenu(Menu menu) {
1140 super.onCreateOptionsMenu(menu);
1141
1142 MenuInflater inflater = getMenuInflater();
1143 inflater.inflate(R.menu.browser, menu);
1144 mMenu = menu;
1145 updateInLoadMenuItems();
1146 return true;
1147 }
1148
1149 /**
1150 * As the menu can be open when loading state changes
1151 * we must manually update the state of the stop/reload menu
1152 * item
1153 */
1154 private void updateInLoadMenuItems() {
1155 if (mMenu == null) {
1156 return;
1157 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001158 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001159 MenuItem src = mInLoad ?
1160 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001161 mMenu.findItem(R.id.reload_menu_id);
1162 if (src != null) {
1163 dest.setIcon(src.getIcon());
1164 dest.setTitle(src.getTitle());
1165 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001166 }
1167
1168 @Override
1169 public boolean onContextItemSelected(MenuItem item) {
1170 // chording is not an issue with context menus, but we use the same
1171 // options selector, so set mCanChord to true so we can access them.
1172 mCanChord = true;
1173 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001174 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001175 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001176 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001177 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001178 Tab currentTab = mTabControl.getCurrentTab();
1179 if (null == currentTab) {
1180 result = false;
1181 break;
1182 }
1183 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001184 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001185 result = false;
1186 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001187 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001188 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001189 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001190 // -- Browser context menu
1191 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001192 case R.id.bookmark_context_menu_id:
1193 case R.id.save_link_context_menu_id:
1194 case R.id.share_link_context_menu_id:
1195 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001196 final WebView webView = getTopWindow();
1197 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001198 result = false;
1199 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001200 }
1201 final HashMap hrefMap = new HashMap();
1202 hrefMap.put("webview", webView);
1203 final Message msg = mHandler.obtainMessage(
1204 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001205 webView.requestFocusNodeHref(msg);
1206 break;
1207
1208 default:
1209 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001210 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001211 }
1212 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001213 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001214 }
1215
1216 private Bundle createGoogleSearchSourceBundle(String source) {
1217 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001218 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001219 return bundle;
1220 }
1221
Leon Scroggins8ad29922010-02-16 12:33:55 -05001222 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001223 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001224 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001225 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001226 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001227 }
1228
Leon Scroggins8ad29922010-02-16 12:33:55 -05001229 /**
1230 * Overriding this to insert a local information bundle
1231 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001232 @Override
1233 public void startSearch(String initialQuery, boolean selectInitialQuery,
1234 Bundle appSearchData, boolean globalSearch) {
1235 if (appSearchData == null) {
1236 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1237 }
1238 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1239 }
1240
Leon Scroggins1f005d32009-08-10 17:36:42 -04001241 /**
1242 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1243 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001244 * @param index Index of the tab to change to, as defined by
1245 * mTabControl.getTabIndex(Tab t).
1246 * @return boolean True if we successfully switched to a different tab. If
1247 * the indexth tab is null, or if that tab is the same as
1248 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001249 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001250 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001251 Tab tab = mTabControl.getTab(index);
1252 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001253 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001254 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001255 }
1256 if (currentTab != null) {
1257 // currentTab may be null if it was just removed. In that case,
1258 // we do not need to remove it
1259 removeTabFromContentView(currentTab);
1260 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001261 mTabControl.setCurrentTab(tab);
1262 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001263 resetTitleIconAndProgress();
1264 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001265 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001266 }
1267
Grace Kloba22ac16e2009-10-07 18:00:23 -07001268 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001269 return openTabAndShow(mSettings.getHomePage(), false, null);
1270 }
1271
Leon Scroggins1f005d32009-08-10 17:36:42 -04001272 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001273 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001274 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001275 // This is the last tab. Open a new one, with the home
1276 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001277 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001278 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001279 return;
1280 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001281 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001282 int indexToShow = -1;
1283 if (parent != null) {
1284 indexToShow = mTabControl.getTabIndex(parent);
1285 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001286 final int currentIndex = mTabControl.getCurrentIndex();
1287 // Try to move to the tab to the right
1288 indexToShow = currentIndex + 1;
1289 if (indexToShow > mTabControl.getTabCount() - 1) {
1290 // Try to move to the tab to the left
1291 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001292 }
1293 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001294 if (switchToTab(indexToShow)) {
1295 // Close window
1296 closeTab(current);
1297 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001298 }
1299
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001300 private ActiveTabsPage mActiveTabsPage;
1301
1302 /**
1303 * Remove the active tabs page.
1304 * @param needToAttach If true, the active tabs page did not attach a tab
1305 * to the content view, so we need to do that here.
1306 */
1307 /* package */ void removeActiveTabPage(boolean needToAttach) {
1308 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001309 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001310 mActiveTabsPage = null;
1311 mMenuState = R.id.MAIN_MENU;
1312 if (needToAttach) {
1313 attachTabToContentView(mTabControl.getCurrentTab());
1314 }
1315 getTopWindow().requestFocus();
1316 }
1317
Cary Clark01cfcdd2010-06-04 16:36:45 -04001318 private WebView showDialog(WebDialog dialog) {
1319 // Need to do something special for Tablet
1320 Tab tab = mTabControl.getCurrentTab();
1321 if (tab.getSubWebView() == null) {
1322 // If the find or select is being performed on the main webview,
1323 // remove the embedded title bar.
1324 WebView mainView = tab.getWebView();
1325 if (mainView != null) {
1326 mainView.setEmbeddedTitleBar(null);
1327 }
1328 }
1329 hideFakeTitleBar();
1330 mMenuState = EMPTY_MENU;
1331 return tab.showDialog(dialog);
1332 }
1333
The Android Open Source Project0c908882009-03-03 19:32:16 -08001334 @Override
1335 public boolean onOptionsItemSelected(MenuItem item) {
1336 if (!mCanChord) {
1337 // The user has already fired a shortcut with this hold down of the
1338 // menu key.
1339 return false;
1340 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001341 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001342 return false;
1343 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001344 if (mMenuIsDown) {
1345 // The shortcut action consumes the MENU. Even if it is still down,
1346 // it won't trigger the next shortcut action. In the case of the
1347 // shortcut action triggering a new activity, like Bookmarks, we
1348 // won't get onKeyUp for MENU. So it is important to reset it here.
1349 mMenuIsDown = false;
1350 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001351 switch (item.getItemId()) {
1352 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001353 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001354 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001355 break;
1356
Leon Scroggins64b80f32009-08-07 12:03:34 -04001357 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001358 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001359 break;
1360
1361 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001362 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001363 break;
1364
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001365 case R.id.active_tabs_menu_id:
1366 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1367 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001368 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001369 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001370 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1371 mActiveTabsPage.requestFocus();
1372 mMenuState = EMPTY_MENU;
1373 break;
1374
Leon Scroggins1f005d32009-08-10 17:36:42 -04001375 case R.id.add_bookmark_menu_id:
Leon Scroggins571b3762010-05-26 10:25:01 -04001376 bookmarkCurrentPage();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001377 break;
1378
1379 case R.id.stop_reload_menu_id:
1380 if (mInLoad) {
1381 stopLoading();
1382 } else {
1383 getTopWindow().reload();
1384 }
1385 break;
1386
1387 case R.id.back_menu_id:
1388 getTopWindow().goBack();
1389 break;
1390
1391 case R.id.forward_menu_id:
1392 getTopWindow().goForward();
1393 break;
1394
1395 case R.id.close_menu_id:
1396 // Close the subwindow if it exists.
1397 if (mTabControl.getCurrentSubWindow() != null) {
1398 dismissSubWindow(mTabControl.getCurrentTab());
1399 break;
1400 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001401 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001402 break;
1403
1404 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001405 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001406 if (current != null) {
1407 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001408 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001409 }
1410 break;
1411
1412 case R.id.preferences_menu_id:
1413 Intent intent = new Intent(this,
1414 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001415 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1416 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001417 startActivityForResult(intent, PREFERENCES_PAGE);
1418 break;
1419
1420 case R.id.find_menu_id:
Cary Clark01cfcdd2010-06-04 16:36:45 -04001421 showFindDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001422 break;
1423
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001424 case R.id.save_webarchive_menu_id:
1425 if (LOGD_ENABLED) {
1426 Log.d(LOGTAG, "Save as Web Archive");
1427 }
1428 String directory = getExternalFilesDir(null).getAbsolutePath() + File.separator;
1429 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1430 @Override
1431 public void onReceiveValue(String value) {
1432 if (value != null) {
1433 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved, Toast.LENGTH_SHORT).show();
1434 } else {
1435 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed, Toast.LENGTH_SHORT).show();
1436 }
1437 }
1438 });
1439 break;
1440
The Android Open Source Project0c908882009-03-03 19:32:16 -08001441 case R.id.page_info_menu_id:
1442 showPageInfo(mTabControl.getCurrentTab(), false);
1443 break;
1444
1445 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001446 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001447 break;
1448
Leon Scroggins96afcb12009-12-10 12:35:56 -05001449 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001450 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001451 Tab currentTab = mTabControl.getCurrentTab();
1452 if (null == currentTab) {
1453 mCanChord = false;
1454 return false;
1455 }
1456 currentTab.populatePickerData();
1457 sharePage(this, currentTab.getTitle(),
1458 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001459 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1460 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001461 break;
1462
1463 case R.id.dump_nav_menu_id:
1464 getTopWindow().debugDump();
1465 break;
1466
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001467 case R.id.dump_counters_menu_id:
1468 getTopWindow().dumpV8Counters();
1469 break;
1470
The Android Open Source Project0c908882009-03-03 19:32:16 -08001471 case R.id.zoom_in_menu_id:
1472 getTopWindow().zoomIn();
1473 break;
1474
1475 case R.id.zoom_out_menu_id:
1476 getTopWindow().zoomOut();
1477 break;
1478
1479 case R.id.view_downloads_menu_id:
1480 viewDownloads(null);
1481 break;
1482
The Android Open Source Project0c908882009-03-03 19:32:16 -08001483 case R.id.window_one_menu_id:
1484 case R.id.window_two_menu_id:
1485 case R.id.window_three_menu_id:
1486 case R.id.window_four_menu_id:
1487 case R.id.window_five_menu_id:
1488 case R.id.window_six_menu_id:
1489 case R.id.window_seven_menu_id:
1490 case R.id.window_eight_menu_id:
1491 {
1492 int menuid = item.getItemId();
1493 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1494 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001495 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001496 if (desiredTab != null &&
1497 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001498 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001499 }
1500 break;
1501 }
1502 }
1503 }
1504 break;
1505
1506 default:
1507 if (!super.onOptionsItemSelected(item)) {
1508 return false;
1509 }
1510 // Otherwise fall through.
1511 }
1512 mCanChord = false;
1513 return true;
1514 }
1515
Leon Scroggins571b3762010-05-26 10:25:01 -04001516 /* package */ void bookmarkCurrentPage() {
1517 Intent i = new Intent(BrowserActivity.this,
1518 AddBookmarkPage.class);
1519 WebView w = getTopWindow();
1520 i.putExtra("url", w.getUrl());
1521 i.putExtra("title", w.getTitle());
1522 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001523 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1524 getDesiredThumbnailHeight(this)));
Ben Murdocheecb4e62010-07-06 16:30:38 +01001525 i.putExtra("url_editable", false);
Leon Scroggins571b3762010-05-26 10:25:01 -04001526 startActivity(i);
1527 }
1528
Cary Clark01cfcdd2010-06-04 16:36:45 -04001529 private boolean dialogIsUp() {
1530 return null != mFindDialog && mFindDialog.isVisible() ||
1531 null != mSelectDialog && mSelectDialog.isVisible();
1532 }
1533
1534 private boolean closeDialog(WebDialog dialog) {
1535 if (null == dialog || !dialog.isVisible()) return false;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001536 Tab currentTab = mTabControl.getCurrentTab();
Cary Clark01cfcdd2010-06-04 16:36:45 -04001537 currentTab.closeDialog(dialog);
1538 dialog.dismiss();
1539 return true;
1540 }
1541
1542 /*
1543 * Remove the find dialog or select dialog.
1544 */
1545 public void closeDialogs() {
1546 if (!(closeDialog(mFindDialog) || closeDialog(mSelectDialog))) return;
Leon Scrogginsd746a942010-05-19 13:21:44 -04001547 if (!mXLargeScreenSize) {
1548 // If the Find was being performed in the main WebView, replace the
1549 // embedded title bar.
Cary Clark01cfcdd2010-06-04 16:36:45 -04001550 Tab currentTab = mTabControl.getCurrentTab();
Leon Scrogginsd746a942010-05-19 13:21:44 -04001551 if (currentTab.getSubWebView() == null) {
1552 WebView mainView = currentTab.getWebView();
1553 if (mainView != null) {
1554 mainView.setEmbeddedTitleBar(mTitleBar);
1555 }
Leon Scroggins79e36d92010-04-29 16:01:46 +01001556 }
1557 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001558 mMenuState = R.id.MAIN_MENU;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001559 if (mInLoad) {
1560 // The title bar was hidden, because otherwise it would cover up the
Cary Clark01cfcdd2010-06-04 16:36:45 -04001561 // find or select dialog. Now that the dialog has been removed,
1562 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001563 showFakeTitleBar();
1564 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001565 }
1566
Cary Clark01cfcdd2010-06-04 16:36:45 -04001567 public void showFindDialog() {
1568 if (null == mFindDialog) {
1569 mFindDialog = new FindDialog(this);
1570 }
1571 showDialog(mFindDialog).setFindIsUp(true);
1572 }
1573
1574 public void setFindDialogText(String text) {
1575 mFindDialog.setText(text);
1576 }
1577
1578 public void showSelectDialog() {
1579 if (null == mSelectDialog) {
1580 mSelectDialog = new SelectDialog(this);
1581 }
1582 showDialog(mSelectDialog).setUpSelect();
1583 mSelectDialog.hideSoftInput();
1584 }
1585
Grace Kloba22ac16e2009-10-07 18:00:23 -07001586 @Override
1587 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001588 // This happens when the user begins to hold down the menu key, so
1589 // allow them to chord to get a shortcut.
1590 mCanChord = true;
1591 // Note: setVisible will decide whether an item is visible; while
1592 // setEnabled() will decide whether an item is enabled, which also means
1593 // whether the matching shortcut key will function.
1594 super.onPrepareOptionsMenu(menu);
1595 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001596 case EMPTY_MENU:
1597 if (mCurrentMenuState != mMenuState) {
1598 menu.setGroupVisible(R.id.MAIN_MENU, false);
1599 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1600 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001601 }
1602 break;
1603 default:
1604 if (mCurrentMenuState != mMenuState) {
1605 menu.setGroupVisible(R.id.MAIN_MENU, true);
1606 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1607 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001608 }
1609 final WebView w = getTopWindow();
1610 boolean canGoBack = false;
1611 boolean canGoForward = false;
1612 boolean isHome = false;
1613 if (w != null) {
1614 canGoBack = w.canGoBack();
1615 canGoForward = w.canGoForward();
1616 isHome = mSettings.getHomePage().equals(w.getUrl());
1617 }
1618 final MenuItem back = menu.findItem(R.id.back_menu_id);
1619 back.setEnabled(canGoBack);
1620
1621 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1622 home.setEnabled(!isHome);
1623
Michael Kolbe0a36662010-06-29 10:37:12 -07001624 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1625 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001626
Michael Kolbe0a36662010-06-29 10:37:12 -07001627 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1628 newtab.setEnabled(mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001629
The Android Open Source Project0c908882009-03-03 19:32:16 -08001630 // decide whether to show the share link option
1631 PackageManager pm = getPackageManager();
1632 Intent send = new Intent(Intent.ACTION_SEND);
1633 send.setType("text/plain");
1634 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1635 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1636
The Android Open Source Project0c908882009-03-03 19:32:16 -08001637 boolean isNavDump = mSettings.isNavDump();
1638 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1639 nav.setVisible(isNavDump);
1640 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001641
1642 boolean showDebugSettings = mSettings.showDebugSettings();
1643 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1644 counter.setVisible(showDebugSettings);
1645 counter.setEnabled(showDebugSettings);
1646
The Android Open Source Project0c908882009-03-03 19:32:16 -08001647 break;
1648 }
1649 mCurrentMenuState = mMenuState;
1650 return true;
1651 }
1652
1653 @Override
1654 public void onCreateContextMenu(ContextMenu menu, View v,
1655 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001656 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001657 return;
1658 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001659 WebView webview = (WebView) v;
1660 WebView.HitTestResult result = webview.getHitTestResult();
1661 if (result == null) {
1662 return;
1663 }
1664
1665 int type = result.getType();
1666 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1667 Log.w(LOGTAG,
1668 "We should not show context menu when nothing is touched");
1669 return;
1670 }
1671 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1672 // let TextView handles context menu
1673 return;
1674 }
1675
1676 // Note, http://b/issue?id=1106666 is requesting that
1677 // an inflated menu can be used again. This is not available
1678 // yet, so inflate each time (yuk!)
1679 MenuInflater inflater = getMenuInflater();
1680 inflater.inflate(R.menu.browsercontext, menu);
1681
1682 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001683 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001684 menu.setGroupVisible(R.id.PHONE_MENU,
1685 type == WebView.HitTestResult.PHONE_TYPE);
1686 menu.setGroupVisible(R.id.EMAIL_MENU,
1687 type == WebView.HitTestResult.EMAIL_TYPE);
1688 menu.setGroupVisible(R.id.GEO_MENU,
1689 type == WebView.HitTestResult.GEO_TYPE);
1690 menu.setGroupVisible(R.id.IMAGE_MENU,
1691 type == WebView.HitTestResult.IMAGE_TYPE
1692 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1693 menu.setGroupVisible(R.id.ANCHOR_MENU,
1694 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1695 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1696
1697 // Setup custom handling depending on the type
1698 switch (type) {
1699 case WebView.HitTestResult.PHONE_TYPE:
1700 menu.setHeaderTitle(Uri.decode(extra));
1701 menu.findItem(R.id.dial_context_menu_id).setIntent(
1702 new Intent(Intent.ACTION_VIEW, Uri
1703 .parse(WebView.SCHEME_TEL + extra)));
1704 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1705 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001706 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001707 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1708 addIntent);
1709 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1710 new Copy(extra));
1711 break;
1712
1713 case WebView.HitTestResult.EMAIL_TYPE:
1714 menu.setHeaderTitle(extra);
1715 menu.findItem(R.id.email_context_menu_id).setIntent(
1716 new Intent(Intent.ACTION_VIEW, Uri
1717 .parse(WebView.SCHEME_MAILTO + extra)));
1718 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1719 new Copy(extra));
1720 break;
1721
1722 case WebView.HitTestResult.GEO_TYPE:
1723 menu.setHeaderTitle(extra);
1724 menu.findItem(R.id.map_context_menu_id).setIntent(
1725 new Intent(Intent.ACTION_VIEW, Uri
1726 .parse(WebView.SCHEME_GEO
1727 + URLEncoder.encode(extra))));
1728 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1729 new Copy(extra));
1730 break;
1731
1732 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1733 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1734 TextView titleView = (TextView) LayoutInflater.from(this)
1735 .inflate(android.R.layout.browser_link_context_header,
1736 null);
1737 titleView.setText(extra);
1738 menu.setHeaderView(titleView);
1739 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001740 boolean showNewTab = mTabControl.canCreateNewTab();
1741 MenuItem newTabItem
1742 = menu.findItem(R.id.open_newtab_context_menu_id);
1743 newTabItem.setVisible(showNewTab);
1744 if (showNewTab) {
1745 newTabItem.setOnMenuItemClickListener(
1746 new MenuItem.OnMenuItemClickListener() {
1747 public boolean onMenuItemClick(MenuItem item) {
1748 final Tab parent = mTabControl.getCurrentTab();
1749 final Tab newTab = openTab(extra);
1750 if (newTab != parent) {
1751 parent.addChildTab(newTab);
1752 }
1753 return true;
1754 }
1755 });
1756 }
Ben Murdochde353622009-10-12 10:29:00 +01001757 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1758 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001759 PackageManager pm = getPackageManager();
1760 Intent send = new Intent(Intent.ACTION_SEND);
1761 send.setType("text/plain");
1762 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1763 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1764 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1765 break;
1766 }
1767 // otherwise fall through to handle image part
1768 case WebView.HitTestResult.IMAGE_TYPE:
1769 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1770 menu.setHeaderTitle(extra);
1771 }
1772 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1773 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1774 menu.findItem(R.id.download_context_menu_id).
1775 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001776 menu.findItem(R.id.set_wallpaper_context_menu_id).
1777 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001778 break;
1779
1780 default:
1781 Log.w(LOGTAG, "We should not get here.");
1782 break;
1783 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001784 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001785 }
1786
The Android Open Source Project0c908882009-03-03 19:32:16 -08001787 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001788 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001789 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001790 // Attach the container that contains the main WebView and any other UI
1791 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001792 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001793
1794 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001795 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001796 if (errorConsole.numberOfErrors() == 0) {
1797 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1798 } else {
1799 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1800 }
1801
1802 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001803 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001804 ViewGroup.LayoutParams.WRAP_CONTENT));
1805 }
1806
Leon Scrogginsd746a942010-05-19 13:21:44 -04001807 if (!mXLargeScreenSize){
1808 WebView view = t.getWebView();
1809 view.setEmbeddedTitleBar(mTitleBar);
1810 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001811 if (t.isInVoiceSearchMode()) {
1812 showVoiceTitleBar(t.getVoiceDisplayTitle());
1813 } else {
1814 revertVoiceTitleBar();
1815 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001816 // Request focus on the top window.
1817 t.getTopWindow().requestFocus();
1818 }
1819
1820 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001821 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001822 t.attachSubWindow(mContentView);
1823 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001824 }
1825
1826 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001827 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001828 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001829 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001830
Grace Kloba22ac16e2009-10-07 18:00:23 -07001831 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1832 if (errorConsole != null) {
1833 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001834 }
1835
Leon Scrogginsd746a942010-05-19 13:21:44 -04001836 if (!mXLargeScreenSize) {
1837 WebView view = t.getWebView();
1838 if (view != null) {
1839 view.setEmbeddedTitleBar(null);
1840 }
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001841 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001842 }
1843
1844 // Remove the sub window if it exists. Also called by TabControl when the
1845 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001846 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001847 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001848 // dismiss the subwindow. This will destroy the WebView.
1849 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001850 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001851 }
1852
Leon Scroggins1f005d32009-08-10 17:36:42 -04001853 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001854 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001855 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001856 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001857 }
1858
1859 // This method does a ton of stuff. It will attempt to create a new tab
1860 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001861 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001862 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1863 String appId) {
1864 final Tab currentTab = mTabControl.getCurrentTab();
1865 if (mTabControl.canCreateNewTab()) {
1866 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1867 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001868 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001869 // If the last tab was removed from the active tabs page, currentTab
1870 // will be null.
1871 if (currentTab != null) {
1872 removeTabFromContentView(currentTab);
1873 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001874 // We must set the new tab as the current tab to reflect the old
1875 // animation behavior.
1876 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001877 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001878 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001879 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001880 }
1881 return tab;
1882 } else {
1883 // Get rid of the subwindow if it exists
1884 dismissSubWindow(currentTab);
1885 if (!urlData.isEmpty()) {
1886 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001887 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001888 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001889 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001890 }
1891 }
1892
Grace Kloba22ac16e2009-10-07 18:00:23 -07001893 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001894 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001895 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001896 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001897 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001898 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001899 }
Grace Klobac9181842009-04-14 08:53:22 -07001900 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001901 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001902 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001903 }
1904 }
1905
1906 private class Copy implements OnMenuItemClickListener {
1907 private CharSequence mText;
1908
1909 public boolean onMenuItemClick(MenuItem item) {
1910 copy(mText);
1911 return true;
1912 }
1913
1914 public Copy(CharSequence toCopy) {
1915 mText = toCopy;
1916 }
1917 }
1918
1919 private class Download implements OnMenuItemClickListener {
1920 private String mText;
1921
1922 public boolean onMenuItemClick(MenuItem item) {
1923 onDownloadStartNoStream(mText, null, null, null, -1);
1924 return true;
1925 }
1926
1927 public Download(String toDownload) {
1928 mText = toDownload;
1929 }
1930 }
1931
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001932 private class SetAsWallpaper extends Thread implements
1933 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1934 private URL mUrl;
1935 private ProgressDialog mWallpaperProgress;
1936 private boolean mCanceled = false;
1937
1938 public SetAsWallpaper(String url) {
1939 try {
1940 mUrl = new URL(url);
1941 } catch (MalformedURLException e) {
1942 mUrl = null;
1943 }
1944 }
1945
1946 public void onCancel(DialogInterface dialog) {
1947 mCanceled = true;
1948 }
1949
1950 public boolean onMenuItemClick(MenuItem item) {
1951 if (mUrl != null) {
1952 // The user may have tried to set a image with a large file size as their
1953 // background so it may take a few moments to perform the operation. Display
1954 // a progress spinner while it is working.
1955 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1956 mWallpaperProgress.setIndeterminate(true);
1957 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1958 mWallpaperProgress.setCancelable(true);
1959 mWallpaperProgress.setOnCancelListener(this);
1960 mWallpaperProgress.show();
1961 start();
1962 }
1963 return true;
1964 }
1965
Michael Kolbe0a36662010-06-29 10:37:12 -07001966 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001967 public void run() {
1968 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1969 try {
1970 // TODO: This will cause the resource to be downloaded again, when we
1971 // should in most cases be able to grab it from the cache. To fix this
1972 // we should query WebCore to see if we can access a cached version and
1973 // instead open an input stream on that. This pattern could also be used
1974 // in the download manager where the same problem exists.
1975 InputStream inputstream = mUrl.openStream();
1976 if (inputstream != null) {
1977 setWallpaper(inputstream);
1978 }
1979 } catch (IOException e) {
1980 Log.e(LOGTAG, "Unable to set new wallpaper");
1981 // Act as though the user canceled the operation so we try to
1982 // restore the old wallpaper.
1983 mCanceled = true;
1984 }
1985
1986 if (mCanceled) {
1987 // Restore the old wallpaper if the user cancelled whilst we were setting
1988 // the new wallpaper.
1989 int width = oldWallpaper.getIntrinsicWidth();
1990 int height = oldWallpaper.getIntrinsicHeight();
1991 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1992 Canvas canvas = new Canvas(bm);
1993 oldWallpaper.setBounds(0, 0, width, height);
1994 oldWallpaper.draw(canvas);
1995 try {
1996 setWallpaper(bm);
1997 } catch (IOException e) {
1998 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1999 }
2000 mCanceled = false;
2001 }
2002
2003 if (mWallpaperProgress.isShowing()) {
2004 mWallpaperProgress.dismiss();
2005 }
2006 }
2007 }
2008
The Android Open Source Project0c908882009-03-03 19:32:16 -08002009 private void copy(CharSequence text) {
2010 try {
2011 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2012 if (clip != null) {
2013 clip.setClipboardText(text);
2014 }
2015 } catch (android.os.RemoteException e) {
2016 Log.e(LOGTAG, "Copy failed", e);
2017 }
2018 }
2019
2020 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002021 * Resets the browser title-view to whatever it must be
2022 * (for example, if we had a loading error)
2023 * When we have a new page, we call resetTitle, when we
2024 * have to reset the titlebar to whatever it used to be
2025 * (for example, if the user chose to stop loading), we
2026 * call resetTitleAndRevertLockIcon.
2027 */
2028 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002029 mTabControl.getCurrentTab().revertLockIcon();
2030 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002031 resetTitleIconAndProgress();
2032 }
2033
2034 /**
2035 * Reset the title, favicon, and progress.
2036 */
2037 private void resetTitleIconAndProgress() {
2038 WebView current = mTabControl.getCurrentWebView();
2039 if (current == null) {
2040 return;
2041 }
2042 resetTitleAndIcon(current);
2043 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002044 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002045 }
2046
2047 // Reset the title and the icon based on the given item.
2048 private void resetTitleAndIcon(WebView view) {
2049 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2050 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002051 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002052 setFavicon(item.getFavicon());
2053 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002054 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002055 setFavicon(null);
2056 }
2057 }
2058
2059 /**
2060 * Sets a title composed of the URL and the title string.
2061 * @param url The URL of the site being loaded.
2062 * @param title The title of the site being loaded.
2063 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002064 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002065 mUrl = url;
2066 mTitle = title;
2067
Leon Scroggins58d56c62010-01-28 15:12:40 -05002068 // If we are in voice search mode, the title has already been set.
2069 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2070 mTitleBar.setDisplayTitle(url);
Leon Scrogginsd746a942010-05-19 13:21:44 -04002071 if (!mXLargeScreenSize) {
2072 mFakeTitleBar.setDisplayTitle(url);
2073 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002074 }
2075
2076 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002077 * @param url The URL to build a title version of the URL from.
2078 * @return The title version of the URL or null if fails.
2079 * The title version of the URL can be either the URL hostname,
2080 * or the hostname with an "https://" prefix (for secure URLs),
2081 * or an empty string if, for example, the URL in question is a
2082 * file:// URL with no hostname.
2083 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002084 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002085 String titleUrl = null;
2086
2087 if (url != null) {
2088 try {
2089 // parse the url string
2090 URL urlObj = new URL(url);
2091 if (urlObj != null) {
2092 titleUrl = "";
2093
2094 String protocol = urlObj.getProtocol();
2095 String host = urlObj.getHost();
2096
2097 if (host != null && 0 < host.length()) {
2098 titleUrl = host;
2099 if (protocol != null) {
2100 // if a secure site, add an "https://" prefix!
2101 if (protocol.equalsIgnoreCase("https")) {
2102 titleUrl = protocol + "://" + host;
2103 }
2104 }
2105 }
2106 }
2107 } catch (MalformedURLException e) {}
2108 }
2109
2110 return titleUrl;
2111 }
2112
2113 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002114 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002115 mTitleBar.setFavicon(icon);
Leon Scrogginsd746a942010-05-19 13:21:44 -04002116 if (!mXLargeScreenSize) {
2117 mFakeTitleBar.setFavicon(icon);
2118 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002119 }
2120
2121 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002122 * Close the tab, remove its associated title bar, and adjust mTabControl's
2123 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002124 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002125 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002126 int currentIndex = mTabControl.getCurrentIndex();
2127 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002128 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002129 if (currentIndex >= removeIndex && currentIndex != 0) {
2130 currentIndex--;
2131 }
2132 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002133 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002134 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002135 }
2136
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002137 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002138 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002139 if (current == null) {
2140 /*
2141 * Instead of finishing the activity, simply push this to the back
2142 * of the stack and let ActivityManager to choose the foreground
2143 * activity. As BrowserActivity is singleTask, it will be always the
2144 * root of the task. So we can use either true or false for
2145 * moveTaskToBack().
2146 */
2147 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002148 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002149 }
2150 WebView w = current.getWebView();
2151 if (w.canGoBack()) {
2152 w.goBack();
2153 } else {
2154 // Check to see if we are closing a window that was created by
2155 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002156 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002157 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002158 switchToTab(mTabControl.getTabIndex(parent));
2159 // Now we close the other tab
2160 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002161 } else {
2162 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002163 // force the tab's inLoad() to be false as we are going to
2164 // either finish the activity or remove the tab. This will
2165 // ensure pauseWebViewTimers() taking action.
2166 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002167 if (mTabControl.getTabCount() == 1) {
2168 finish();
2169 return;
2170 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002171 // call pauseWebViewTimers() now, we won't be able to call
2172 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002173 // Temporarily change mActivityInPause to be true as
2174 // pauseWebViewTimers() will do nothing if mActivityInPause
2175 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002176 boolean savedState = mActivityInPause;
2177 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002178 Log.e(LOGTAG, "BrowserActivity is already paused "
2179 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002180 }
2181 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002182 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002183 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002184 removeTabFromContentView(current);
2185 mTabControl.removeTab(current);
2186 }
2187 /*
2188 * Instead of finishing the activity, simply push this to the back
2189 * of the stack and let ActivityManager to choose the foreground
2190 * activity. As BrowserActivity is singleTask, it will be always the
2191 * root of the task. So we can use either true or false for
2192 * moveTaskToBack().
2193 */
2194 moveTaskToBack(true);
2195 }
2196 }
2197 }
2198
Grace Kloba22ac16e2009-10-07 18:00:23 -07002199 boolean isMenuDown() {
2200 return mMenuIsDown;
2201 }
2202
Grace Kloba5942df02009-09-18 11:48:29 -07002203 @Override
2204 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002205 // Even if MENU is already held down, we need to call to super to open
2206 // the IME on long press.
2207 if (KeyEvent.KEYCODE_MENU == keyCode) {
2208 mMenuIsDown = true;
2209 return super.onKeyDown(keyCode, event);
2210 }
Grace Kloba5942df02009-09-18 11:48:29 -07002211 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2212 // still down, we don't want to trigger the search. Pretend to consume
2213 // the key and do nothing.
2214 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002215
Grace Kloba5942df02009-09-18 11:48:29 -07002216 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002217 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002218 // WebView/WebTextView handle the keys in the KeyDown. As
2219 // the Activity's shortcut keys are only handled when WebView
2220 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2221 if (event.isShiftPressed()) {
2222 getTopWindow().pageUp(false);
2223 } else {
2224 getTopWindow().pageDown(false);
2225 }
Grace Kloba5942df02009-09-18 11:48:29 -07002226 return true;
2227 case KeyEvent.KEYCODE_BACK:
2228 if (event.getRepeatCount() == 0) {
2229 event.startTracking();
2230 return true;
2231 } else if (mCustomView == null && mActiveTabsPage == null
2232 && event.isLongPress()) {
2233 bookmarksOrHistoryPicker(true);
2234 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002235 }
Grace Kloba5942df02009-09-18 11:48:29 -07002236 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002237 }
Grace Kloba5942df02009-09-18 11:48:29 -07002238 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002239 }
2240
Grace Kloba5942df02009-09-18 11:48:29 -07002241 @Override
2242 public boolean onKeyUp(int keyCode, KeyEvent event) {
2243 switch(keyCode) {
2244 case KeyEvent.KEYCODE_MENU:
2245 mMenuIsDown = false;
2246 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002247 case KeyEvent.KEYCODE_BACK:
2248 if (event.isTracking() && !event.isCanceled()) {
2249 if (mCustomView != null) {
2250 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002251 mTabControl.getCurrentWebView().getWebChromeClient()
2252 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002253 } else if (mActiveTabsPage != null) {
2254 // if tab page is showing, hide it
2255 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002256 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002257 WebView subwindow = mTabControl.getCurrentSubWindow();
2258 if (subwindow != null) {
2259 if (subwindow.canGoBack()) {
2260 subwindow.goBack();
2261 } else {
2262 dismissSubWindow(mTabControl.getCurrentTab());
2263 }
2264 } else {
2265 goBackOnePageOrQuit();
2266 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002267 }
Grace Kloba5942df02009-09-18 11:48:29 -07002268 return true;
2269 }
2270 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002271 }
Grace Kloba5942df02009-09-18 11:48:29 -07002272 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002273 }
2274
Leon Scroggins68579392009-09-15 15:31:54 -04002275 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002276 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002277 resetTitleAndRevertLockIcon();
2278 WebView w = getTopWindow();
2279 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002280 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2281 // same logic here. But for subwindow case, should we call into the main
2282 // WebView's onPageFinished as we never call its onPageStarted and if
2283 // the page finishes itself, we don't call onPageFinished.
2284 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2285 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002286
2287 cancelStopToast();
2288 mStopToast = Toast
2289 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2290 mStopToast.show();
2291 }
2292
Grace Kloba22ac16e2009-10-07 18:00:23 -07002293 boolean didUserStopLoading() {
2294 return mDidStopLoad;
2295 }
2296
The Android Open Source Project0c908882009-03-03 19:32:16 -08002297 private void cancelStopToast() {
2298 if (mStopToast != null) {
2299 mStopToast.cancel();
2300 mStopToast = null;
2301 }
2302 }
2303
Grace Kloba22ac16e2009-10-07 18:00:23 -07002304 // called by a UI or non-UI thread to post the message
2305 public void postMessage(int what, int arg1, int arg2, Object obj,
2306 long delayMillis) {
2307 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2308 obj), delayMillis);
2309 }
2310
2311 // called by a UI or non-UI thread to remove the message
2312 void removeMessages(int what, Object object) {
2313 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002314 }
2315
2316 // public message ids
2317 public final static int LOAD_URL = 1001;
2318 public final static int STOP_LOAD = 1002;
2319
2320 // Message Ids
2321 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002322 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002323
Grace Kloba22ac16e2009-10-07 18:00:23 -07002324 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002325
Ben Murdocheecb4e62010-07-06 16:30:38 +01002326 private static final int TOUCH_ICON_DOWNLOADED = 109;
2327
The Android Open Source Project0c908882009-03-03 19:32:16 -08002328 // Private handler for handling javascript and saving passwords
2329 private Handler mHandler = new Handler() {
2330
Michael Kolbe0a36662010-06-29 10:37:12 -07002331 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002332 public void handleMessage(Message msg) {
2333 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002334 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002335 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002336 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002337 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002338 if (url == null || url.length() == 0) {
2339 break;
2340 }
2341 HashMap focusNodeMap = (HashMap) msg.obj;
2342 WebView view = (WebView) focusNodeMap.get("webview");
2343 // Only apply the action if the top window did not change.
2344 if (getTopWindow() != view) {
2345 break;
2346 }
2347 switch (msg.arg1) {
2348 case R.id.open_context_menu_id:
2349 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002350 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002351 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002352 case R.id.bookmark_context_menu_id:
2353 Intent intent = new Intent(BrowserActivity.this,
2354 AddBookmarkPage.class);
2355 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002356 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002357 startActivity(intent);
2358 break;
2359 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002360 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002361 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002362 break;
2363 case R.id.copy_link_context_menu_id:
2364 copy(url);
2365 break;
2366 case R.id.save_link_context_menu_id:
2367 case R.id.download_context_menu_id:
2368 onDownloadStartNoStream(url, null, null, null, -1);
2369 break;
2370 }
2371 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002372 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002373
2374 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002375 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002376 break;
2377
2378 case STOP_LOAD:
2379 stopLoading();
2380 break;
2381
The Android Open Source Project0c908882009-03-03 19:32:16 -08002382 case RELEASE_WAKELOCK:
2383 if (mWakeLock.isHeld()) {
2384 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002385 // if we reach here, Browser should be still in the
2386 // background loading after WAKELOCK_TIMEOUT (5-min).
2387 // To avoid burning the battery, stop loading.
2388 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002389 }
2390 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002391
2392 case UPDATE_BOOKMARK_THUMBNAIL:
2393 WebView view = (WebView) msg.obj;
2394 if (view != null) {
2395 updateScreenshot(view);
2396 }
2397 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002398
2399 case TOUCH_ICON_DOWNLOADED:
2400 Bundle b = msg.getData();
2401 showSaveToHomescreenDialog(b.getString("url"),
2402 b.getString("title"),
2403 (Bitmap) b.getParcelable("touchIcon"),
2404 (Bitmap) b.getParcelable("favicon"));
2405 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002406 }
2407 }
2408 };
2409
Leon Scroggins96afcb12009-12-10 12:35:56 -05002410 /**
2411 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2412 * an {@link Intent} to launch the Activity chooser.
2413 * @param c Context used to launch a new Activity.
2414 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002415 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002416 * @param url URL of the page. Stored in the Intent with
2417 * {@link Intent#EXTRA_TEXT}
2418 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2419 * with {@link Browser#EXTRA_SHARE_FAVICON}
2420 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2421 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2422 */
2423 public static final void sharePage(Context c, String title, String url,
2424 Bitmap favicon, Bitmap screenshot) {
2425 Intent send = new Intent(Intent.ACTION_SEND);
2426 send.setType("text/plain");
2427 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002428 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002429 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2430 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2431 try {
2432 c.startActivity(Intent.createChooser(send, c.getString(
2433 R.string.choosertitle_sharevia)));
2434 } catch(android.content.ActivityNotFoundException ex) {
2435 // if no app handles it, do nothing
2436 }
2437 }
2438
Leon Scroggins89c6d362009-07-15 16:54:37 -04002439 private void updateScreenshot(WebView view) {
2440 // If this is a bookmarked site, add a screenshot to the database.
2441 // FIXME: When should we update? Every time?
2442 // FIXME: Would like to make sure there is actually something to
2443 // draw, but the API for that (WebViewCore.pictureReady()) is not
2444 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002445
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002446 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2447 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002448 if (bm == null) {
2449 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002450 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002451
2452 final ContentResolver cr = getContentResolver();
2453 final String url = view.getUrl();
2454 final String originalUrl = view.getOriginalUrl();
2455
2456 new AsyncTask<Void, Void, Void>() {
2457 @Override
2458 protected Void doInBackground(Void... unused) {
2459 Cursor c = null;
2460 try {
2461 c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2462 cr, originalUrl, url, true);
2463 if (c != null) {
2464 if (c.moveToFirst()) {
2465 ContentValues values = new ContentValues();
2466 final ByteArrayOutputStream os
2467 = new ByteArrayOutputStream();
2468 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2469 values.put(Browser.BookmarkColumns.THUMBNAIL,
2470 os.toByteArray());
2471 do {
2472 cr.update(ContentUris.withAppendedId(
2473 Browser.BOOKMARKS_URI, c.getInt(0)),
2474 values, null, null);
2475 } while (c.moveToNext());
2476 }
2477 }
2478 } catch (IllegalStateException e) {
2479 // Ignore
2480 } finally {
2481 if (c != null) c.close();
2482 }
2483 return null;
2484 }
2485 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002486 }
2487
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002488 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002489 * Values for the size of the thumbnail created when taking a screenshot.
2490 * Lazily initialized. Instead of using these directly, use
2491 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002492 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002493 private static int THUMBNAIL_WIDTH = 0;
2494 private static int THUMBNAIL_HEIGHT = 0;
2495
2496 /**
2497 * Return the desired width for thumbnail screenshots, which are stored in
2498 * the database, and used on the bookmarks screen.
2499 * @param context Context for finding out the density of the screen.
2500 * @return int desired width for thumbnail screenshot.
2501 */
2502 /* package */ static int getDesiredThumbnailWidth(Context context) {
2503 if (THUMBNAIL_WIDTH == 0) {
2504 float density = context.getResources().getDisplayMetrics().density;
2505 THUMBNAIL_WIDTH = (int) (90 * density);
2506 THUMBNAIL_HEIGHT = (int) (80 * density);
2507 }
2508 return THUMBNAIL_WIDTH;
2509 }
2510
2511 /**
2512 * Return the desired height for thumbnail screenshots, which are stored in
2513 * the database, and used on the bookmarks screen.
2514 * @param context Context for finding out the density of the screen.
2515 * @return int desired height for thumbnail screenshot.
2516 */
2517 /* package */ static int getDesiredThumbnailHeight(Context context) {
2518 // To ensure that they are both initialized.
2519 getDesiredThumbnailWidth(context);
2520 return THUMBNAIL_HEIGHT;
2521 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002522
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002523 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002524 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002525 if (thumbnail == null) {
2526 return null;
2527 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002528 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002529 Canvas canvas = new Canvas(bm);
2530 // May need to tweak these values to determine what is the
2531 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002532 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002533 int thumbnailHeight = thumbnail.getHeight();
2534 float scaleFactorX = 1.0f;
2535 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002536 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002537 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002538 } else {
2539 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002540 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002541
2542 if (view.getWidth() > view.getHeight() &&
2543 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2544 // If the device is in landscape and the page is shorter
2545 // than the height of the view, stretch the thumbnail to fill the
2546 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002547 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002548 } else {
2549 // In the portrait case, this looks nice.
2550 scaleFactorY = scaleFactorX;
2551 }
2552
2553 canvas.scale(scaleFactorX, scaleFactorY);
2554
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002555 thumbnail.draw(canvas);
2556 return bm;
2557 }
2558
The Android Open Source Project0c908882009-03-03 19:32:16 -08002559 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002560 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002561 //-------------------------------------------------------------------------
2562
2563 // Use in overrideUrlLoading
2564 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2565 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2566 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2567 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2568
Leon Scroggins92472e82010-02-17 16:32:28 -05002569 // Keep this initial progress in sync with initialProgressValue (* 100)
2570 // in ProgressTracker.cpp
2571 private final static int INITIAL_PROGRESS = 10;
2572
Grace Kloba22ac16e2009-10-07 18:00:23 -07002573 void onPageStarted(WebView view, String url, Bitmap favicon) {
2574 // when BrowserActivity just starts, onPageStarted may be called before
2575 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2576 // to start the timer. As we won't switch tabs while an activity is in
2577 // pause state, we can ensure calling resume and pause in pair.
2578 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002579
Grace Kloba22ac16e2009-10-07 18:00:23 -07002580 resetLockIcon(url);
2581 setUrlTitle(url, null);
2582 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002583 // Show some progress so that the user knows the page is beginning to
2584 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002585 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002586 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002587 if (!mIsNetworkUp) createAndShowNetworkDialog();
Cary Clark01cfcdd2010-06-04 16:36:45 -04002588 closeDialogs();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002589 if (mSettings.isTracing()) {
2590 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002591 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002592 WebAddress uri = new WebAddress(url);
2593 host = uri.mHost;
2594 } catch (android.net.ParseException ex) {
2595 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002596 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002597 host = host.replace('.', '_');
2598 host += ".trace";
2599 mInTrace = true;
2600 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2601 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002602
Grace Kloba22ac16e2009-10-07 18:00:23 -07002603 // Performance probe
2604 if (false) {
2605 mStart = SystemClock.uptimeMillis();
2606 mProcessStart = Process.getElapsedCpuTime();
2607 long[] sysCpu = new long[7];
2608 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2609 sysCpu, null)) {
2610 mUserStart = sysCpu[0] + sysCpu[1];
2611 mSystemStart = sysCpu[2];
2612 mIdleStart = sysCpu[3];
2613 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2614 }
2615 mUiStart = SystemClock.currentThreadTimeMillis();
2616 }
2617 }
2618
2619 void onPageFinished(WebView view, String url) {
2620 // Reset the title and icon in case we stopped a provisional load.
2621 resetTitleAndIcon(view);
2622 // Update the lock icon image only once we are done loading
2623 updateLockIconToLatest();
2624 // pause the WebView timer and release the wake lock if it is finished
2625 // while BrowserActivity is in pause state.
2626 if (mActivityInPause && pauseWebViewTimers()) {
2627 if (mWakeLock.isHeld()) {
2628 mHandler.removeMessages(RELEASE_WAKELOCK);
2629 mWakeLock.release();
2630 }
2631 }
2632
2633 // Performance probe
2634 if (false) {
2635 long[] sysCpu = new long[7];
2636 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2637 sysCpu, null)) {
2638 String uiInfo = "UI thread used "
2639 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2640 + " ms";
2641 if (LOGD_ENABLED) {
2642 Log.d(LOGTAG, uiInfo);
2643 }
2644 //The string that gets written to the log
2645 String performanceString = "It took total "
2646 + (SystemClock.uptimeMillis() - mStart)
2647 + " ms clock time to load the page."
2648 + "\nbrowser process used "
2649 + (Process.getElapsedCpuTime() - mProcessStart)
2650 + " ms, user processes used "
2651 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2652 + " ms, kernel used "
2653 + (sysCpu[2] - mSystemStart) * 10
2654 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2655 + " ms and irq took "
2656 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2657 * 10 + " ms, " + uiInfo;
2658 if (LOGD_ENABLED) {
2659 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2660 }
2661 if (url != null) {
2662 // strip the url to maintain consistency
2663 String newUrl = new String(url);
2664 if (newUrl.startsWith("http://www.")) {
2665 newUrl = newUrl.substring(11);
2666 } else if (newUrl.startsWith("http://")) {
2667 newUrl = newUrl.substring(7);
2668 } else if (newUrl.startsWith("https://www.")) {
2669 newUrl = newUrl.substring(12);
2670 } else if (newUrl.startsWith("https://")) {
2671 newUrl = newUrl.substring(8);
2672 }
2673 if (LOGD_ENABLED) {
2674 Log.d(LOGTAG, newUrl + " loaded");
2675 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002676 }
2677 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002678 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002679
Grace Kloba22ac16e2009-10-07 18:00:23 -07002680 if (mInTrace) {
2681 mInTrace = false;
2682 Debug.stopMethodTracing();
2683 }
2684 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002685
Grace Klobae7fe26b2010-06-28 16:23:33 -07002686 private void closeEmptyChildTab() {
2687 Tab current = mTabControl.getCurrentTab();
2688 if (current != null
2689 && current.getWebView().copyBackForwardList().getSize() == 0) {
2690 Tab parent = current.getParentTab();
2691 if (parent != null) {
2692 switchToTab(mTabControl.getTabIndex(parent));
2693 closeTab(current);
2694 }
2695 }
2696 }
2697
Grace Kloba22ac16e2009-10-07 18:00:23 -07002698 boolean shouldOverrideUrlLoading(WebView view, String url) {
2699 if (url.startsWith(SCHEME_WTAI)) {
2700 // wtai://wp/mc;number
2701 // number=string(phone-number)
2702 if (url.startsWith(SCHEME_WTAI_MC)) {
2703 Intent intent = new Intent(Intent.ACTION_VIEW,
2704 Uri.parse(WebView.SCHEME_TEL +
2705 url.substring(SCHEME_WTAI_MC.length())));
2706 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002707 // before leaving BrowserActivity, close the empty child tab.
2708 // If a new tab is created through JavaScript open to load this
2709 // url, we would like to close it as we will load this url in a
2710 // different Activity.
2711 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002712 return true;
2713 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002714 // wtai://wp/sd;dtmf
2715 // dtmf=string(dialstring)
2716 if (url.startsWith(SCHEME_WTAI_SD)) {
2717 // TODO: only send when there is active voice connection
2718 return false;
2719 }
2720 // wtai://wp/ap;number;name
2721 // number=string(phone-number)
2722 // name=string
2723 if (url.startsWith(SCHEME_WTAI_AP)) {
2724 // TODO
2725 return false;
2726 }
2727 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002728
Grace Kloba22ac16e2009-10-07 18:00:23 -07002729 // The "about:" schemes are internal to the browser; don't want these to
2730 // be dispatched to other apps.
2731 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002732 return false;
2733 }
2734
Grace Kloba22ac16e2009-10-07 18:00:23 -07002735 Intent intent;
2736 // perform generic parsing of the URI to turn it into an Intent.
2737 try {
2738 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2739 } catch (URISyntaxException ex) {
2740 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2741 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002742 }
2743
Grace Kloba22ac16e2009-10-07 18:00:23 -07002744 // check whether the intent can be resolved. If not, we will see
2745 // whether we can download it from the Market.
2746 if (getPackageManager().resolveActivity(intent, 0) == null) {
2747 String packagename = intent.getPackage();
2748 if (packagename != null) {
2749 intent = new Intent(Intent.ACTION_VIEW, Uri
2750 .parse("market://search?q=pname:" + packagename));
2751 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2752 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002753 // before leaving BrowserActivity, close the empty child tab.
2754 // If a new tab is created through JavaScript open to load this
2755 // url, we would like to close it as we will load this url in a
2756 // different Activity.
2757 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002758 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002759 } else {
2760 return false;
2761 }
2762 }
2763
Grace Kloba22ac16e2009-10-07 18:00:23 -07002764 // sanitize the Intent, ensuring web pages can not bypass browser
2765 // security (only access to BROWSABLE activities).
2766 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2767 intent.setComponent(null);
2768 try {
2769 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002770 // before leaving BrowserActivity, close the empty child tab.
2771 // If a new tab is created through JavaScript open to load this
2772 // url, we would like to close it as we will load this url in a
2773 // different Activity.
2774 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002775 return true;
2776 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002777 } catch (ActivityNotFoundException ex) {
2778 // ignore the error. If no application can handle the URL,
2779 // eg about:blank, assume the browser can handle it.
2780 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002781
Grace Kloba22ac16e2009-10-07 18:00:23 -07002782 if (mMenuIsDown) {
2783 openTab(url);
2784 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002785 return true;
2786 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002787 return false;
2788 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002789
Grace Kloba22ac16e2009-10-07 18:00:23 -07002790 // -------------------------------------------------------------------------
2791 // Helper function for WebChromeClient
2792 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002793
Grace Kloba22ac16e2009-10-07 18:00:23 -07002794 void onProgressChanged(WebView view, int newProgress) {
Leon Scrogginsd746a942010-05-19 13:21:44 -04002795 if (mXLargeScreenSize) {
2796 mTitleBar.setProgress(newProgress);
2797 } else {
2798 // On the phone, the fake title bar will always cover up the
2799 // regular title bar (or the regular one is offscreen), so only the
2800 // fake title bar needs to change its progress
2801 mFakeTitleBar.setProgress(newProgress);
2802 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002803
Grace Kloba22ac16e2009-10-07 18:00:23 -07002804 if (newProgress == 100) {
2805 // onProgressChanged() may continue to be called after the main
2806 // frame has finished loading, as any remaining sub frames continue
2807 // to load. We'll only get called once though with newProgress as
2808 // 100 when everything is loaded. (onPageFinished is called once
2809 // when the main frame completes loading regardless of the state of
2810 // any sub frames so calls to onProgressChanges may continue after
2811 // onPageFinished has executed)
2812 if (mInLoad) {
2813 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002814 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002815 // If the options menu is open, leave the title bar
2816 if (!mOptionsMenuOpen || !mIconView) {
2817 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002818 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002819 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002820 } else {
2821 if (!mInLoad) {
2822 // onPageFinished may have already been called but a subframe is
2823 // still loading and updating the progress. Reset mInLoad and
2824 // update the menu items.
2825 mInLoad = true;
2826 updateInLoadMenuItems();
2827 }
2828 // When the page first begins to load, the Activity may still be
2829 // paused, in which case showFakeTitleBar will do nothing. Call
2830 // again as the page continues to load so that it will be shown.
2831 // (Calling it will the fake title bar is already showing will also
2832 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002833 if (!mOptionsMenuOpen || mIconView) {
2834 // This page has begun to load, so show the title bar
2835 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002836 }
2837 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002838 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002839
Grace Kloba22ac16e2009-10-07 18:00:23 -07002840 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002841 // if a view already exists then immediately terminate the new one
2842 if (mCustomView != null) {
2843 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002844 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002845 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002846
2847 // Add the custom view to its container.
2848 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2849 mCustomView = view;
2850 mCustomViewCallback = callback;
2851 // Save the menu state and set it to empty while the custom
2852 // view is showing.
2853 mOldMenuState = mMenuState;
2854 mMenuState = EMPTY_MENU;
2855 // Hide the content view.
2856 mContentView.setVisibility(View.GONE);
2857 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002858 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002859 mCustomViewContainer.setVisibility(View.VISIBLE);
2860 mCustomViewContainer.bringToFront();
2861 }
2862
2863 void onHideCustomView() {
2864 if (mCustomView == null)
2865 return;
2866
2867 // Hide the custom view.
2868 mCustomView.setVisibility(View.GONE);
2869 // Remove the custom view from its container.
2870 mCustomViewContainer.removeView(mCustomView);
2871 mCustomView = null;
2872 // Reset the old menu state.
2873 mMenuState = mOldMenuState;
2874 mOldMenuState = EMPTY_MENU;
2875 mCustomViewContainer.setVisibility(View.GONE);
2876 mCustomViewCallback.onCustomViewHidden();
2877 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002878 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002879 mContentView.setVisibility(View.VISIBLE);
2880 }
2881
2882 Bitmap getDefaultVideoPoster() {
2883 if (mDefaultVideoPoster == null) {
2884 mDefaultVideoPoster = BitmapFactory.decodeResource(
2885 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002886 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002887 return mDefaultVideoPoster;
2888 }
Patrick Scott3918d442009-08-04 13:22:29 -04002889
Grace Kloba22ac16e2009-10-07 18:00:23 -07002890 View getVideoLoadingProgressView() {
2891 if (mVideoProgressView == null) {
2892 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2893 mVideoProgressView = inflater.inflate(
2894 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002895 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002896 return mVideoProgressView;
2897 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002898
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002899 /*
2900 * The Object used to inform the WebView of the file to upload.
2901 */
2902 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002903 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002904
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002905 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2906
2907 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002908 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01002909 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01002910 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002911 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01002912 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002913 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01002914 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002915
Ben Murdoch039bd472010-07-21 21:26:57 +01002916 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002917 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002918
Ben Murdoch6af492a2010-06-15 12:38:17 +01002919 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002920 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01002921 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
2922 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002923
Ben Murdoch6af492a2010-06-15 12:38:17 +01002924 if (mUploadMessage != null) {
2925 // Already a file picker operation in progress.
2926 return;
2927 }
2928
Grace Kloba22ac16e2009-10-07 18:00:23 -07002929 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002930
2931 // Parse the accept type.
2932 String params[] = acceptType.split(";");
2933 String mimeType = params[0];
2934
2935 for (String p : params) {
2936 String[] keyValue = p.split("=");
2937 if (keyValue.length == 2) {
2938 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002939 if (mediaSourceKey.equals(keyValue[0])) {
2940 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002941 }
2942 }
2943 }
2944
2945 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002946 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2947 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002948
2949 // Create an intent to add to the standard file picker that will
2950 // capture an image from the camera. We'll combine this intent with
2951 // the standard OPENABLE picker unless the web developer specifically
2952 // requested the camera or gallery be opened by passing a parameter
2953 // in the accept type.
2954 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
2955 File externalDataDir = Environment.getExternalStoragePublicDirectory(
2956 Environment.DIRECTORY_DCIM);
2957 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
2958 File.separator + "browser-photos");
2959 cameraDataDir.mkdirs();
2960 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
2961 System.currentTimeMillis() + ".jpg";
2962 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
2963
Ben Murdoch6af492a2010-06-15 12:38:17 +01002964 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
2965
Ben Murdoch039bd472010-07-21 21:26:57 +01002966 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
2967
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002968 if (mimeType.equals(imageMimeType)) {
2969 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01002970 addCamcorderIntent = false;
2971 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002972 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
2973 // directly.
2974 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
2975 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01002976 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
2977 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002978 addCameraIntent = false;
2979 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01002980 } else if (mimeType.equals(videoMimeType)) {
2981 i.setType(videoMimeType);
2982 addCameraIntent = false;
2983 // The camcorder saves it's own file and returns it to us in the intent, so
2984 // we don't need to generate one here.
2985 mCameraFilePath = null;
2986
2987 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01002988 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
2989 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002990 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
2991 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01002992 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
2993 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002994 addCamcorderIntent = false;
2995 }
Ben Murdoch039bd472010-07-21 21:26:57 +01002996 } else if (mimeType.equals(audioMimeType)) {
2997 i.setType(audioMimeType);
2998 addCameraIntent = false;
2999 addCamcorderIntent = false;
3000 if (mediaSource.equals(mediaSourceValueMicrophone)) {
3001 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
3002 // recorder.
3003 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
3004 return;
3005 }
3006 // On a default system, there is no single option to open an audio "gallery". Both the
3007 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3008 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3009 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003010 } else {
3011 i.setType("*/*");
3012 }
3013
Ben Murdoch6af492a2010-06-15 12:38:17 +01003014 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003015 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3016 chooser.putExtra(Intent.EXTRA_INTENT, i);
3017
Ben Murdoch6af492a2010-06-15 12:38:17 +01003018 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3019
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003020 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003021 extraInitialIntents.add(cameraIntent);
3022 }
3023
3024 if (addCamcorderIntent) {
3025 extraInitialIntents.add(camcorderIntent);
3026 }
3027
3028 if (extraInitialIntents.size() > 0) {
3029 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3030 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003031 }
3032
3033 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3034 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003035 }
3036
3037 // -------------------------------------------------------------------------
3038 // Implement functions for DownloadListener
3039 // -------------------------------------------------------------------------
3040
The Android Open Source Project0c908882009-03-03 19:32:16 -08003041 /**
3042 * Notify the host application a download should be done, or that
3043 * the data should be streamed if a streaming viewer is available.
3044 * @param url The full url to the content that should be downloaded
3045 * @param contentDisposition Content-disposition http header, if
3046 * present.
3047 * @param mimetype The mimetype of the content reported by the server
3048 * @param contentLength The file size reported by the server
3049 */
3050 public void onDownloadStart(String url, String userAgent,
3051 String contentDisposition, String mimetype, long contentLength) {
3052 // if we're dealing wih A/V content that's not explicitly marked
3053 // for download, check if it's streamable.
3054 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003055 || !contentDisposition.regionMatches(
3056 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003057 // query the package manager to see if there's a registered handler
3058 // that matches.
3059 Intent intent = new Intent(Intent.ACTION_VIEW);
3060 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003061 ResolveInfo info = getPackageManager().resolveActivity(intent,
3062 PackageManager.MATCH_DEFAULT_ONLY);
3063 if (info != null) {
3064 ComponentName myName = getComponentName();
3065 // If we resolved to ourselves, we don't want to attempt to
3066 // load the url only to try and download it again.
3067 if (!myName.getPackageName().equals(
3068 info.activityInfo.packageName)
3069 || !myName.getClassName().equals(
3070 info.activityInfo.name)) {
3071 // someone (other than us) knows how to handle this mime
3072 // type with this scheme, don't download.
3073 try {
3074 startActivity(intent);
3075 return;
3076 } catch (ActivityNotFoundException ex) {
3077 if (LOGD_ENABLED) {
3078 Log.d(LOGTAG, "activity not found for " + mimetype
3079 + " over " + Uri.parse(url).getScheme(),
3080 ex);
3081 }
3082 // Best behavior is to fall back to a download in this
3083 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003084 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003085 }
3086 }
3087 }
3088 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3089 }
3090
Kristian Monsenfa52d172010-03-25 18:29:21 +00003091 // This is to work around the fact that java.net.URI throws Exceptions
3092 // instead of just encoding URL's properly
3093 // Helper method for onDownloadStartNoStream
3094 private static String encodePath(String path) {
3095 char[] chars = path.toCharArray();
3096
3097 boolean needed = false;
3098 for (char c : chars) {
3099 if (c == '[' || c == ']') {
3100 needed = true;
3101 break;
3102 }
3103 }
3104 if (needed == false) {
3105 return path;
3106 }
3107
3108 StringBuilder sb = new StringBuilder("");
3109 for (char c : chars) {
3110 if (c == '[' || c == ']') {
3111 sb.append('%');
3112 sb.append(Integer.toHexString(c));
3113 } else {
3114 sb.append(c);
3115 }
3116 }
3117
3118 return sb.toString();
3119 }
3120
The Android Open Source Project0c908882009-03-03 19:32:16 -08003121 /**
3122 * Notify the host application a download should be done, even if there
3123 * is a streaming viewer available for thise type.
3124 * @param url The full url to the content that should be downloaded
3125 * @param contentDisposition Content-disposition http header, if
3126 * present.
3127 * @param mimetype The mimetype of the content reported by the server
3128 * @param contentLength The file size reported by the server
3129 */
3130 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3131 String contentDisposition, String mimetype, long contentLength) {
3132
3133 String filename = URLUtil.guessFileName(url,
3134 contentDisposition, mimetype);
3135
3136 // Check to see if we have an SDCard
3137 String status = Environment.getExternalStorageState();
3138 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3139 int title;
3140 String msg;
3141
3142 // Check to see if the SDCard is busy, same as the music app
3143 if (status.equals(Environment.MEDIA_SHARED)) {
3144 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3145 title = R.string.download_sdcard_busy_dlg_title;
3146 } else {
3147 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3148 title = R.string.download_no_sdcard_dlg_title;
3149 }
3150
3151 new AlertDialog.Builder(this)
3152 .setTitle(title)
3153 .setIcon(android.R.drawable.ic_dialog_alert)
3154 .setMessage(msg)
3155 .setPositiveButton(R.string.ok, null)
3156 .show();
3157 return;
3158 }
3159
Kristian Monsenfa52d172010-03-25 18:29:21 +00003160 // java.net.URI is a lot stricter than KURL so we have to encode some
3161 // extra characters. Fix for b 2538060 and b 1634719
3162 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003163 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003164 webAddress = new WebAddress(url);
3165 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003166 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003167 // This only happens for very bad urls, we want to chatch the
3168 // exception here
3169 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003170 return;
3171 }
3172
3173 // XXX: Have to use the old url since the cookies were stored using the
3174 // old percent-encoded url.
3175 String cookies = CookieManager.getInstance().getCookie(url);
3176
3177 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003178 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003179 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3180 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3181 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003182 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003183 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003184 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003185 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3186 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3187 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3188 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003189 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003190 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003191 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003192 }
3193 if (mimetype == null) {
3194 // We must have long pressed on a link or image to download it. We
3195 // are not sure of the mimetype in this case, so do a head request
3196 new FetchUrlMimeType(this).execute(values);
3197 } else {
3198 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003199 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003200 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003201 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3202 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003203 }
3204
Grace Kloba22ac16e2009-10-07 18:00:23 -07003205 // -------------------------------------------------------------------------
3206
The Android Open Source Project0c908882009-03-03 19:32:16 -08003207 /**
3208 * Resets the lock icon. This method is called when we start a new load and
3209 * know the url to be loaded.
3210 */
3211 private void resetLockIcon(String url) {
3212 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003213 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003214 updateLockIconImage(LOCK_ICON_UNSECURE);
3215 }
3216
The Android Open Source Project0c908882009-03-03 19:32:16 -08003217 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003218 * Update the lock icon to correspond to our latest state.
3219 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003220 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003221 Tab t = mTabControl.getCurrentTab();
3222 if (t != null) {
3223 updateLockIconImage(t.getLockIconType());
3224 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003225 }
3226
3227 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003228 * Updates the lock-icon image in the title-bar.
3229 */
3230 private void updateLockIconImage(int lockIconType) {
3231 Drawable d = null;
3232 if (lockIconType == LOCK_ICON_SECURE) {
3233 d = mSecLockIcon;
3234 } else if (lockIconType == LOCK_ICON_MIXED) {
3235 d = mMixLockIcon;
3236 }
Leon Scroggins68579392009-09-15 15:31:54 -04003237 mTitleBar.setLock(d);
Leon Scrogginsd746a942010-05-19 13:21:44 -04003238 if (!mXLargeScreenSize) {
3239 mFakeTitleBar.setLock(d);
3240 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003241 }
3242
3243 /**
3244 * Displays a page-info dialog.
3245 * @param tab The tab to show info about
3246 * @param fromShowSSLCertificateOnError The flag that indicates whether
3247 * this dialog was opened from the SSL-certificate-on-error dialog or
3248 * not. This is important, since we need to know whether to return to
3249 * the parent dialog or simply dismiss.
3250 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003251 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003252 final boolean fromShowSSLCertificateOnError) {
3253 final LayoutInflater factory = LayoutInflater
3254 .from(this);
3255
3256 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3257
3258 final WebView view = tab.getWebView();
3259
3260 String url = null;
3261 String title = null;
3262
3263 if (view == null) {
3264 url = tab.getUrl();
3265 title = tab.getTitle();
3266 } else if (view == mTabControl.getCurrentWebView()) {
3267 // Use the cached title and url if this is the current WebView
3268 url = mUrl;
3269 title = mTitle;
3270 } else {
3271 url = view.getUrl();
3272 title = view.getTitle();
3273 }
3274
3275 if (url == null) {
3276 url = "";
3277 }
3278 if (title == null) {
3279 title = "";
3280 }
3281
3282 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3283 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3284
3285 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003286 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003287
3288 AlertDialog.Builder alertDialogBuilder =
3289 new AlertDialog.Builder(this)
3290 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3291 .setView(pageInfoView)
3292 .setPositiveButton(
3293 R.string.ok,
3294 new DialogInterface.OnClickListener() {
3295 public void onClick(DialogInterface dialog,
3296 int whichButton) {
3297 mPageInfoDialog = null;
3298 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003299
3300 // if we came here from the SSL error dialog
3301 if (fromShowSSLCertificateOnError) {
3302 // go back to the SSL error dialog
3303 showSSLCertificateOnError(
3304 mSSLCertificateOnErrorView,
3305 mSSLCertificateOnErrorHandler,
3306 mSSLCertificateOnErrorError);
3307 }
3308 }
3309 })
3310 .setOnCancelListener(
3311 new DialogInterface.OnCancelListener() {
3312 public void onCancel(DialogInterface dialog) {
3313 mPageInfoDialog = null;
3314 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003315
3316 // if we came here from the SSL error dialog
3317 if (fromShowSSLCertificateOnError) {
3318 // go back to the SSL error dialog
3319 showSSLCertificateOnError(
3320 mSSLCertificateOnErrorView,
3321 mSSLCertificateOnErrorHandler,
3322 mSSLCertificateOnErrorError);
3323 }
3324 }
3325 });
3326
3327 // if we have a main top-level page SSL certificate set or a certificate
3328 // error
3329 if (fromShowSSLCertificateOnError ||
3330 (view != null && view.getCertificate() != null)) {
3331 // add a 'View Certificate' button
3332 alertDialogBuilder.setNeutralButton(
3333 R.string.view_certificate,
3334 new DialogInterface.OnClickListener() {
3335 public void onClick(DialogInterface dialog,
3336 int whichButton) {
3337 mPageInfoDialog = null;
3338 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003339
3340 // if we came here from the SSL error dialog
3341 if (fromShowSSLCertificateOnError) {
3342 // go back to the SSL error dialog
3343 showSSLCertificateOnError(
3344 mSSLCertificateOnErrorView,
3345 mSSLCertificateOnErrorHandler,
3346 mSSLCertificateOnErrorError);
3347 } else {
3348 // otherwise, display the top-most certificate from
3349 // the chain
3350 if (view.getCertificate() != null) {
3351 showSSLCertificate(tab);
3352 }
3353 }
3354 }
3355 });
3356 }
3357
3358 mPageInfoDialog = alertDialogBuilder.show();
3359 }
3360
3361 /**
3362 * Displays the main top-level page SSL certificate dialog
3363 * (accessible from the Page-Info dialog).
3364 * @param tab The tab to show certificate for.
3365 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003366 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003367 final View certificateView =
3368 inflateCertificateView(tab.getWebView().getCertificate());
3369 if (certificateView == null) {
3370 return;
3371 }
3372
3373 LayoutInflater factory = LayoutInflater.from(this);
3374
3375 final LinearLayout placeholder =
3376 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3377
3378 LinearLayout ll = (LinearLayout) factory.inflate(
3379 R.layout.ssl_success, placeholder);
3380 ((TextView)ll.findViewById(R.id.success))
3381 .setText(R.string.ssl_certificate_is_valid);
3382
3383 mSSLCertificateView = tab;
3384 mSSLCertificateDialog =
3385 new AlertDialog.Builder(this)
3386 .setTitle(R.string.ssl_certificate).setIcon(
3387 R.drawable.ic_dialog_browser_certificate_secure)
3388 .setView(certificateView)
3389 .setPositiveButton(R.string.ok,
3390 new DialogInterface.OnClickListener() {
3391 public void onClick(DialogInterface dialog,
3392 int whichButton) {
3393 mSSLCertificateDialog = null;
3394 mSSLCertificateView = null;
3395
3396 showPageInfo(tab, false);
3397 }
3398 })
3399 .setOnCancelListener(
3400 new DialogInterface.OnCancelListener() {
3401 public void onCancel(DialogInterface dialog) {
3402 mSSLCertificateDialog = null;
3403 mSSLCertificateView = null;
3404
3405 showPageInfo(tab, false);
3406 }
3407 })
3408 .show();
3409 }
3410
3411 /**
3412 * Displays the SSL error certificate dialog.
3413 * @param view The target web-view.
3414 * @param handler The SSL error handler responsible for cancelling the
3415 * connection that resulted in an SSL error or proceeding per user request.
3416 * @param error The SSL error object.
3417 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003418 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003419 final WebView view, final SslErrorHandler handler, final SslError error) {
3420
3421 final View certificateView =
3422 inflateCertificateView(error.getCertificate());
3423 if (certificateView == null) {
3424 return;
3425 }
3426
3427 LayoutInflater factory = LayoutInflater.from(this);
3428
3429 final LinearLayout placeholder =
3430 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3431
3432 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3433 LinearLayout ll = (LinearLayout)factory
3434 .inflate(R.layout.ssl_warning, placeholder);
3435 ((TextView)ll.findViewById(R.id.warning))
3436 .setText(R.string.ssl_untrusted);
3437 }
3438
3439 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3440 LinearLayout ll = (LinearLayout)factory
3441 .inflate(R.layout.ssl_warning, placeholder);
3442 ((TextView)ll.findViewById(R.id.warning))
3443 .setText(R.string.ssl_mismatch);
3444 }
3445
3446 if (error.hasError(SslError.SSL_EXPIRED)) {
3447 LinearLayout ll = (LinearLayout)factory
3448 .inflate(R.layout.ssl_warning, placeholder);
3449 ((TextView)ll.findViewById(R.id.warning))
3450 .setText(R.string.ssl_expired);
3451 }
3452
3453 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3454 LinearLayout ll = (LinearLayout)factory
3455 .inflate(R.layout.ssl_warning, placeholder);
3456 ((TextView)ll.findViewById(R.id.warning))
3457 .setText(R.string.ssl_not_yet_valid);
3458 }
3459
3460 mSSLCertificateOnErrorHandler = handler;
3461 mSSLCertificateOnErrorView = view;
3462 mSSLCertificateOnErrorError = error;
3463 mSSLCertificateOnErrorDialog =
3464 new AlertDialog.Builder(this)
3465 .setTitle(R.string.ssl_certificate).setIcon(
3466 R.drawable.ic_dialog_browser_certificate_partially_secure)
3467 .setView(certificateView)
3468 .setPositiveButton(R.string.ok,
3469 new DialogInterface.OnClickListener() {
3470 public void onClick(DialogInterface dialog,
3471 int whichButton) {
3472 mSSLCertificateOnErrorDialog = null;
3473 mSSLCertificateOnErrorView = null;
3474 mSSLCertificateOnErrorHandler = null;
3475 mSSLCertificateOnErrorError = null;
3476
Grace Kloba22ac16e2009-10-07 18:00:23 -07003477 view.getWebViewClient().onReceivedSslError(
3478 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003479 }
3480 })
3481 .setNeutralButton(R.string.page_info_view,
3482 new DialogInterface.OnClickListener() {
3483 public void onClick(DialogInterface dialog,
3484 int whichButton) {
3485 mSSLCertificateOnErrorDialog = null;
3486
3487 // do not clear the dialog state: we will
3488 // need to show the dialog again once the
3489 // user is done exploring the page-info details
3490
3491 showPageInfo(mTabControl.getTabFromView(view),
3492 true);
3493 }
3494 })
3495 .setOnCancelListener(
3496 new DialogInterface.OnCancelListener() {
3497 public void onCancel(DialogInterface dialog) {
3498 mSSLCertificateOnErrorDialog = null;
3499 mSSLCertificateOnErrorView = null;
3500 mSSLCertificateOnErrorHandler = null;
3501 mSSLCertificateOnErrorError = null;
3502
Grace Kloba22ac16e2009-10-07 18:00:23 -07003503 view.getWebViewClient().onReceivedSslError(
3504 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003505 }
3506 })
3507 .show();
3508 }
3509
3510 /**
3511 * Inflates the SSL certificate view (helper method).
3512 * @param certificate The SSL certificate.
3513 * @return The resultant certificate view with issued-to, issued-by,
3514 * issued-on, expires-on, and possibly other fields set.
3515 * If the input certificate is null, returns null.
3516 */
3517 private View inflateCertificateView(SslCertificate certificate) {
3518 if (certificate == null) {
3519 return null;
3520 }
3521
3522 LayoutInflater factory = LayoutInflater.from(this);
3523
3524 View certificateView = factory.inflate(
3525 R.layout.ssl_certificate, null);
3526
3527 // issued to:
3528 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3529 if (issuedTo != null) {
3530 ((TextView) certificateView.findViewById(R.id.to_common))
3531 .setText(issuedTo.getCName());
3532 ((TextView) certificateView.findViewById(R.id.to_org))
3533 .setText(issuedTo.getOName());
3534 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3535 .setText(issuedTo.getUName());
3536 }
3537
3538 // issued by:
3539 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3540 if (issuedBy != null) {
3541 ((TextView) certificateView.findViewById(R.id.by_common))
3542 .setText(issuedBy.getCName());
3543 ((TextView) certificateView.findViewById(R.id.by_org))
3544 .setText(issuedBy.getOName());
3545 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3546 .setText(issuedBy.getUName());
3547 }
3548
3549 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003550 String issuedOn = formatCertificateDate(
3551 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003552 ((TextView) certificateView.findViewById(R.id.issued_on))
3553 .setText(issuedOn);
3554
3555 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003556 String expiresOn = formatCertificateDate(
3557 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003558 ((TextView) certificateView.findViewById(R.id.expires_on))
3559 .setText(expiresOn);
3560
3561 return certificateView;
3562 }
3563
3564 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003565 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003566 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003567 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003568 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003569 private String formatCertificateDate(Date certificateDate) {
3570 if (certificateDate == null) {
3571 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003572 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003573 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3574 if (formattedDate == null) {
3575 return "";
3576 }
3577 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003578 }
3579
3580 /**
3581 * Displays an http-authentication dialog.
3582 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003583 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003584 final String host, final String realm, final String title,
3585 final String name, final String password, int focusId) {
3586 LayoutInflater factory = LayoutInflater.from(this);
3587 final View v = factory
3588 .inflate(R.layout.http_authentication, null);
3589 if (name != null) {
3590 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3591 }
3592 if (password != null) {
3593 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3594 }
3595
3596 String titleText = title;
3597 if (titleText == null) {
3598 titleText = getText(R.string.sign_in_to).toString().replace(
3599 "%s1", host).replace("%s2", realm);
3600 }
3601
3602 mHttpAuthHandler = handler;
3603 AlertDialog dialog = new AlertDialog.Builder(this)
3604 .setTitle(titleText)
3605 .setIcon(android.R.drawable.ic_dialog_alert)
3606 .setView(v)
3607 .setPositiveButton(R.string.action,
3608 new DialogInterface.OnClickListener() {
3609 public void onClick(DialogInterface dialog,
3610 int whichButton) {
3611 String nm = ((EditText) v
3612 .findViewById(R.id.username_edit))
3613 .getText().toString();
3614 String pw = ((EditText) v
3615 .findViewById(R.id.password_edit))
3616 .getText().toString();
3617 BrowserActivity.this.setHttpAuthUsernamePassword
3618 (host, realm, nm, pw);
3619 handler.proceed(nm, pw);
3620 mHttpAuthenticationDialog = null;
3621 mHttpAuthHandler = null;
3622 }})
3623 .setNegativeButton(R.string.cancel,
3624 new DialogInterface.OnClickListener() {
3625 public void onClick(DialogInterface dialog,
3626 int whichButton) {
3627 handler.cancel();
3628 BrowserActivity.this.resetTitleAndRevertLockIcon();
3629 mHttpAuthenticationDialog = null;
3630 mHttpAuthHandler = null;
3631 }})
3632 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3633 public void onCancel(DialogInterface dialog) {
3634 handler.cancel();
3635 BrowserActivity.this.resetTitleAndRevertLockIcon();
3636 mHttpAuthenticationDialog = null;
3637 mHttpAuthHandler = null;
3638 }})
3639 .create();
3640 // Make the IME appear when the dialog is displayed if applicable.
3641 dialog.getWindow().setSoftInputMode(
3642 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3643 dialog.show();
3644 if (focusId != 0) {
3645 dialog.findViewById(focusId).requestFocus();
3646 } else {
3647 v.findViewById(R.id.username_edit).requestFocus();
3648 }
3649 mHttpAuthenticationDialog = dialog;
3650 }
3651
3652 public int getProgress() {
3653 WebView w = mTabControl.getCurrentWebView();
3654 if (w != null) {
3655 return w.getProgress();
3656 } else {
3657 return 100;
3658 }
3659 }
3660
3661 /**
3662 * Set HTTP authentication password.
3663 *
3664 * @param host The host for the password
3665 * @param realm The realm for the password
3666 * @param username The username for the password. If it is null, it means
3667 * password can't be saved.
3668 * @param password The password
3669 */
3670 public void setHttpAuthUsernamePassword(String host, String realm,
3671 String username,
3672 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003673 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003674 if (w != null) {
3675 w.setHttpAuthUsernamePassword(host, realm, username, password);
3676 }
3677 }
3678
3679 /**
3680 * connectivity manager says net has come or gone... inform the user
3681 * @param up true if net has come up, false if net has gone down
3682 */
3683 public void onNetworkToggle(boolean up) {
3684 if (up == mIsNetworkUp) {
3685 return;
3686 } else if (up) {
3687 mIsNetworkUp = true;
3688 if (mAlertDialog != null) {
3689 mAlertDialog.cancel();
3690 mAlertDialog = null;
3691 }
3692 } else {
3693 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003694 if (mInLoad) {
3695 createAndShowNetworkDialog();
3696 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003697 }
3698 WebView w = mTabControl.getCurrentWebView();
3699 if (w != null) {
3700 w.setNetworkAvailable(up);
3701 }
3702 }
3703
Grace Kloba22ac16e2009-10-07 18:00:23 -07003704 boolean isNetworkUp() {
3705 return mIsNetworkUp;
3706 }
3707
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003708 // This method shows the network dialog alerting the user that the net is
3709 // down. It will only show the dialog if mAlertDialog is null.
3710 private void createAndShowNetworkDialog() {
3711 if (mAlertDialog == null) {
3712 mAlertDialog = new AlertDialog.Builder(this)
3713 .setTitle(R.string.loadSuspendedTitle)
3714 .setMessage(R.string.loadSuspended)
3715 .setPositiveButton(R.string.ok, null)
3716 .show();
3717 }
3718 }
3719
The Android Open Source Project0c908882009-03-03 19:32:16 -08003720 @Override
3721 protected void onActivityResult(int requestCode, int resultCode,
3722 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003723 if (getTopWindow() == null) return;
3724
The Android Open Source Project0c908882009-03-03 19:32:16 -08003725 switch (requestCode) {
3726 case COMBO_PAGE:
3727 if (resultCode == RESULT_OK && intent != null) {
3728 String data = intent.getAction();
3729 Bundle extras = intent.getExtras();
3730 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003731 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003732 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003733 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003734 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003735 dismissSubWindow(currentTab);
3736 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003737 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003738 }
3739 }
3740 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003741 // Deliberately fall through to PREFERENCES_PAGE, since the
3742 // same extra may be attached to the COMBO_PAGE
3743 case PREFERENCES_PAGE:
3744 if (resultCode == RESULT_OK && intent != null) {
3745 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3746 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3747 mTabControl.removeParentChildRelationShips();
3748 }
3749 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003750 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003751 // Choose a file from the file picker.
3752 case FILE_SELECTED:
3753 if (null == mUploadMessage) break;
3754 Uri result = intent == null || resultCode != RESULT_OK ? null
3755 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003756
3757 // As we ask the camera to save the result of the user taking
3758 // a picture, the camera application does not return anything other
3759 // than RESULT_OK. So we need to check whether the file we expected
3760 // was written to disk in the in the case that we
3761 // did not get an intent returned but did get a RESULT_OK. If it was,
3762 // we assume that this result has came back from the camera.
3763 if (result == null && intent == null && resultCode == RESULT_OK) {
3764 File cameraFile = new File(mCameraFilePath);
3765 if (cameraFile.exists()) {
3766 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003767 // Broadcast to the media scanner that we have a new photo
3768 // so it will be added into the gallery for the user.
3769 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003770 }
3771 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003772 mUploadMessage.onReceiveValue(result);
3773 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003774 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003775 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003776 default:
3777 break;
3778 }
Leon Scroggins30444232009-09-04 18:36:20 -04003779 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003780 }
3781
3782 /*
3783 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003784 * menu to see the download window. It shows the download window on top of
3785 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003786 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003787 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003788 Intent intent = new Intent(this,
3789 BrowserDownloadPage.class);
3790 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003791 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003792
3793 }
3794
Ben Murdocheecb4e62010-07-06 16:30:38 +01003795 /* package*/ void promptAddOrInstallBookmark() {
3796 final Tab current = mTabControl.getCurrentTab();
3797 Resources resources = getResources();
3798 CharSequence[] choices = {
3799 resources.getString(R.string.save_to_bookmarks),
3800 resources.getString(R.string.create_shortcut_bookmark)
3801 };
3802
3803 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3804 builder.setTitle(R.string.add_new_bookmark);
3805 builder.setItems(choices, new DialogInterface.OnClickListener() {
3806 public void onClick(DialogInterface dialog, int item) {
3807 if (item == 0) {
3808 bookmarkCurrentPage();
3809 } else if (item == 1) {
3810 current.populatePickerData();
3811 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3812 if (touchIconUrl != null) {
3813 // Download the touch icon for this site then save it to the
3814 // homescreen.
3815 Bundle b = new Bundle();
3816 b.putString("url", current.getUrl());
3817 b.putString("title", current.getTitle());
3818 b.putParcelable("favicon", current.getFavicon());
3819 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3820 msg.setData(b);
Ben Murdochccb5de02010-07-19 18:38:17 +01003821 new DownloadTouchIcon(BrowserActivity.this, msg,
Ben Murdocheecb4e62010-07-06 16:30:38 +01003822 mTabControl.getCurrentWebView().getSettings()
3823 .getUserAgentString()).execute(touchIconUrl);
3824 } else {
3825 // add to homescreen, can do it immediately as there is no touch
3826 // icon.
3827 showSaveToHomescreenDialog(current.getUrl(), current.getTitle(),
3828 null, current.getFavicon());
3829 }
3830 }
3831 }
3832 });
3833 builder.create().show();
3834 }
3835
Leon Scroggins160a7e72009-08-14 18:28:01 -04003836 /**
3837 * Open the Go page.
3838 * @param startWithHistory If true, open starting on the history tab.
3839 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003840 */
Leon Scroggins30444232009-09-04 18:36:20 -04003841 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003842 WebView current = mTabControl.getCurrentWebView();
3843 if (current == null) {
3844 return;
3845 }
3846 Intent intent = new Intent(this,
3847 CombinedBookmarkHistoryActivity.class);
3848 String title = current.getTitle();
3849 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003850 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3851 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003852
The Android Open Source Project0c908882009-03-03 19:32:16 -08003853 // Just in case the user opens bookmarks before a page finishes loading
3854 // so the current history item, and therefore the page, is null.
3855 if (null == url) {
3856 url = mLastEnteredUrl;
3857 // This can happen.
3858 if (null == url) {
3859 url = mSettings.getHomePage();
3860 }
3861 }
3862 // In case the web page has not yet received its associated title.
3863 if (title == null) {
3864 title = url;
3865 }
3866 intent.putExtra("title", title);
3867 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003868 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003869 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003870 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003871 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003872 if (startWithHistory) {
3873 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3874 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3875 }
3876 startActivityForResult(intent, COMBO_PAGE);
3877 }
3878
Ben Murdocheecb4e62010-07-06 16:30:38 +01003879 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
3880 Bitmap favicon) {
3881 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
3882
3883 // Just in case the user tries to save before a page finishes loading
3884 // so the current history item, and therefore the page, is null.
3885 if (null == url) {
3886 url = mLastEnteredUrl;
3887 // This can happen.
3888 if (null == url) {
3889 url = mSettings.getHomePage();
3890 }
3891 }
3892
3893 // In case the web page has not yet received its associated title.
3894 if (title == null) {
3895 title = url;
3896 }
3897
3898 intent.putExtra("title", title);
3899 intent.putExtra("url", url);
3900 intent.putExtra("favicon", favicon);
3901 intent.putExtra("touchIcon", touchIcon);
3902 startActivity(intent);
3903 }
3904
3905
The Android Open Source Project0c908882009-03-03 19:32:16 -08003906 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003907 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003908 // In case the user enters nothing.
3909 if (url != null && url.length() != 0 && view != null) {
3910 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003911 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003912 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003913 }
3914 }
3915 }
3916
Leon Scroggins92472e82010-02-17 16:32:28 -05003917 /**
3918 * Load the URL into the given WebView and update the title bar
3919 * to reflect the new load. Call this instead of WebView.loadUrl
3920 * directly.
3921 * @param view The WebView used to load url.
3922 * @param url The URL to load.
3923 */
3924 private void loadUrl(WebView view, String url) {
3925 updateTitleBarForNewLoad(view, url);
3926 view.loadUrl(url);
3927 }
3928
3929 /**
3930 * Load UrlData into a Tab and update the title bar to reflect the new
3931 * load. Call this instead of UrlData.loadIn directly.
3932 * @param t The Tab used to load.
3933 * @param data The UrlData being loaded.
3934 */
3935 private void loadUrlDataIn(Tab t, UrlData data) {
3936 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3937 data.loadIn(t);
3938 }
3939
3940 /**
3941 * If the WebView is the top window, update the title bar to reflect
3942 * loading the new URL. i.e. set its text, clear the favicon (which
3943 * will be set once the page begins loading), and set the progress to
3944 * INITIAL_PROGRESS to show that the page has begun to load. Called
3945 * by loadUrl and loadUrlDataIn.
3946 * @param view The WebView that is starting a load.
3947 * @param url The URL that is being loaded.
3948 */
3949 private void updateTitleBarForNewLoad(WebView view, String url) {
3950 if (view == getTopWindow()) {
3951 setUrlTitle(url, null);
3952 setFavicon(null);
3953 onProgressChanged(view, INITIAL_PROGRESS);
3954 }
3955 }
3956
The Android Open Source Project0c908882009-03-03 19:32:16 -08003957 private String smartUrlFilter(Uri inUri) {
3958 if (inUri != null) {
3959 return smartUrlFilter(inUri.toString());
3960 }
3961 return null;
3962 }
3963
Feng Qianb34f87a2009-03-24 21:27:26 -07003964 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003965 "(?i)" + // switch on case insensitive matching
3966 "(" + // begin group for schema
3967 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003968 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003969 ")" +
3970 "(.*)" );
3971
3972 /**
3973 * Attempts to determine whether user input is a URL or search
3974 * terms. Anything with a space is passed to search.
3975 *
3976 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3977 * "Http://" converts to "http://"
3978 *
3979 * @return Original or modified URL
3980 *
3981 */
3982 String smartUrlFilter(String url) {
3983
3984 String inUrl = url.trim();
3985 boolean hasSpace = inUrl.indexOf(' ') != -1;
3986
3987 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3988 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003989 // force scheme to lowercase
3990 String scheme = matcher.group(1);
3991 String lcScheme = scheme.toLowerCase();
3992 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003993 inUrl = lcScheme + matcher.group(2);
3994 }
3995 if (hasSpace) {
3996 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003997 }
3998 return inUrl;
3999 }
4000 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004001 // FIXME: Is this the correct place to add to searches?
4002 // what if someone else calls this function?
4003 int shortcut = parseUrlShortcut(inUrl);
4004 if (shortcut != SHORTCUT_INVALID) {
4005 Browser.addSearchUrl(mResolver, inUrl);
4006 String query = inUrl.substring(2);
4007 switch (shortcut) {
4008 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004009 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004010 case SHORTCUT_WIKIPEDIA_SEARCH:
4011 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4012 case SHORTCUT_DICTIONARY_SEARCH:
4013 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4014 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004015 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004016 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004017 }
4018 }
4019 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004020 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004021 return URLUtil.guessUrl(inUrl);
4022 }
4023 }
4024
4025 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004026 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004027 }
4028
Ben Murdochbff2d602009-07-01 20:19:05 +01004029 /* package */ void setShouldShowErrorConsole(boolean flag) {
4030 if (flag == mShouldShowErrorConsole) {
4031 // Nothing to do.
4032 return;
4033 }
4034
4035 mShouldShowErrorConsole = flag;
4036
Grace Kloba22ac16e2009-10-07 18:00:23 -07004037 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
4038 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004039
4040 if (flag) {
4041 // Setting the show state of the console will cause it's the layout to be inflated.
4042 if (errorConsole.numberOfErrors() > 0) {
4043 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4044 } else {
4045 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4046 }
4047
4048 // Now we can add it to the main view.
4049 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004050 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004051 ViewGroup.LayoutParams.WRAP_CONTENT));
4052 } else {
4053 mErrorConsoleContainer.removeView(errorConsole);
4054 }
4055
4056 }
4057
Grace Kloba22ac16e2009-10-07 18:00:23 -07004058 boolean shouldShowErrorConsole() {
4059 return mShouldShowErrorConsole;
4060 }
4061
Andrei Popescu163ab742009-10-20 17:58:23 +01004062 private void setStatusBarVisibility(boolean visible) {
4063 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4064 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4065 }
4066
Andrei Popescu56199cc2010-01-12 22:39:16 +00004067
4068 private void sendNetworkType(String type, String subtype) {
4069 WebView w = mTabControl.getCurrentWebView();
4070 if (w != null) {
4071 w.setNetworkType(type, subtype);
4072 }
4073 }
4074
Andrei Popescu30995e72010-02-09 16:59:58 +00004075 private void packageChanged(String packageName, boolean wasAdded) {
4076 WebView w = mTabControl.getCurrentWebView();
4077 if (w == null) {
4078 return;
4079 }
4080
4081 if (wasAdded) {
4082 w.addPackageName(packageName);
4083 } else {
4084 w.removePackageName(packageName);
4085 }
4086 }
4087
4088 private void addPackageNames(Set<String> packageNames) {
4089 WebView w = mTabControl.getCurrentWebView();
4090 if (w == null) {
4091 return;
4092 }
4093
4094 w.addPackageNames(packageNames);
4095 }
4096
4097 private void getInstalledPackages() {
4098 AsyncTask<Void, Void, Set<String> > task =
4099 new AsyncTask<Void, Void, Set<String> >() {
Michael Kolbe0a36662010-06-29 10:37:12 -07004100 @Override
Andrei Popescu30995e72010-02-09 16:59:58 +00004101 protected Set<String> doInBackground(Void... unused) {
4102 Set<String> installedPackages = new HashSet<String>();
4103 PackageManager pm = BrowserActivity.this.getPackageManager();
4104 if (pm != null) {
4105 List<PackageInfo> packages = pm.getInstalledPackages(0);
4106 for (PackageInfo p : packages) {
4107 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
4108 installedPackages.add(p.packageName);
4109 }
4110 }
4111 }
4112
4113 return installedPackages;
4114 }
4115
4116 // Executes on the UI thread
Michael Kolbe0a36662010-06-29 10:37:12 -07004117 @Override
Andrei Popescu30995e72010-02-09 16:59:58 +00004118 protected void onPostExecute(Set<String> installedPackages) {
4119 addPackageNames(installedPackages);
4120 }
4121 };
4122 task.execute();
4123 }
4124
Grace Klobaeb6eef42009-09-15 17:56:32 -07004125 final static int LOCK_ICON_UNSECURE = 0;
4126 final static int LOCK_ICON_SECURE = 1;
4127 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004128
The Android Open Source Project0c908882009-03-03 19:32:16 -08004129 private BrowserSettings mSettings;
4130 private TabControl mTabControl;
4131 private ContentResolver mResolver;
4132 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004133 private View mCustomView;
4134 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004135 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004136
4137 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4138 // view, we should rewrite this.
4139 private int mCurrentMenuState = 0;
4140 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004141 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004142 private static final int EMPTY_MENU = -1;
4143 private Menu mMenu;
4144
4145 private FindDialog mFindDialog;
Cary Clark01cfcdd2010-06-04 16:36:45 -04004146 private SelectDialog mSelectDialog;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004147 // Used to prevent chording to result in firing two shortcuts immediately
4148 // one after another. Fixes bug 1211714.
4149 boolean mCanChord;
4150
4151 private boolean mInLoad;
4152 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004153 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004154
Cary Clark1f10cbf2010-03-22 11:45:23 -04004155 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004156
4157 private boolean mMenuIsDown;
4158
The Android Open Source Project0c908882009-03-03 19:32:16 -08004159 private static boolean mInTrace;
4160
4161 // Performance probe
4162 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4163 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4164 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4165 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4166 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4167 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4168 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4169 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4170 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4171 };
4172
4173 private long mStart;
4174 private long mProcessStart;
4175 private long mUserStart;
4176 private long mSystemStart;
4177 private long mIdleStart;
4178 private long mIrqStart;
4179
4180 private long mUiStart;
4181
4182 private Drawable mMixLockIcon;
4183 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004184
4185 /* hold a ref so we can auto-cancel if necessary */
4186 private AlertDialog mAlertDialog;
4187
The Android Open Source Project0c908882009-03-03 19:32:16 -08004188 // The up-to-date URL and title (these can be different from those stored
4189 // in WebView, since it takes some time for the information in WebView to
4190 // get updated)
4191 private String mUrl;
4192 private String mTitle;
4193
4194 // As PageInfo has different style for landscape / portrait, we have
4195 // to re-open it when configuration changed
4196 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004197 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004198 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4199 // dialog, we should not just dismiss it, but should get back to the
4200 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004201 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004202
4203 // as SSLCertificateOnError has different style for landscape / portrait,
4204 // we have to re-open it when configuration changed
4205 private AlertDialog mSSLCertificateOnErrorDialog;
4206 private WebView mSSLCertificateOnErrorView;
4207 private SslErrorHandler mSSLCertificateOnErrorHandler;
4208 private SslError mSSLCertificateOnErrorError;
4209
4210 // as SSLCertificate has different style for landscape / portrait, we
4211 // have to re-open it when configuration changed
4212 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004213 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004214
4215 // as HttpAuthentication has different style for landscape / portrait, we
4216 // have to re-open it when configuration changed
4217 private AlertDialog mHttpAuthenticationDialog;
4218 private HttpAuthHandler mHttpAuthHandler;
4219
4220 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4221 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004222 ViewGroup.LayoutParams.MATCH_PARENT,
4223 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004224 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4225 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004226 ViewGroup.LayoutParams.MATCH_PARENT,
4227 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004228 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004229 // Google search
4230 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004231 // Wikipedia search
4232 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4233 // Dictionary search
4234 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4235 // Google Mobile Local search
4236 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4237
4238 final static String QUERY_PLACE_HOLDER = "%s";
4239
4240 // "source" parameter for Google search through search key
4241 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4242 // "source" parameter for Google search through goto menu
4243 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4244 // "source" parameter for Google search through simplily type
4245 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4246 // "source" parameter for Google search suggested by the browser
4247 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4248 // "source" parameter for Google search from unknown source
4249 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4250
4251 private final static String LOGTAG = "browser";
4252
The Android Open Source Project0c908882009-03-03 19:32:16 -08004253 private String mLastEnteredUrl;
4254
4255 private PowerManager.WakeLock mWakeLock;
4256 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4257
4258 private Toast mStopToast;
4259
Leon Scroggins571b3762010-05-26 10:25:01 -04004260 private TitleBarBase mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004261
Ben Murdochbff2d602009-07-01 20:19:05 +01004262 private LinearLayout mErrorConsoleContainer = null;
4263 private boolean mShouldShowErrorConsole = false;
4264
The Android Open Source Project0c908882009-03-03 19:32:16 -08004265 // As the ids are dynamically created, we can't guarantee that they will
4266 // be in sequence, so this static array maps ids to a window number.
4267 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4268 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4269 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4270 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4271
4272 // monitor platform changes
4273 private IntentFilter mNetworkStateChangedFilter;
4274 private BroadcastReceiver mNetworkStateIntentReceiver;
4275
Grace Klobab4da0ad2009-05-14 14:45:40 -07004276 private BroadcastReceiver mPackageInstallationReceiver;
4277
Bjorn Bringerta7611812010-03-24 11:12:02 +00004278 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4279
The Android Open Source Project0c908882009-03-03 19:32:16 -08004280 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004281 final static int COMBO_PAGE = 1;
4282 final static int DOWNLOAD_PAGE = 2;
4283 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004284 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004285
Andrei Popescu540035d2009-09-18 18:59:20 +01004286 // the default <video> poster
4287 private Bitmap mDefaultVideoPoster;
4288 // the video progress view
4289 private View mVideoProgressView;
4290
Andrei Popescu30995e72010-02-09 16:59:58 +00004291 // The Google packages we monitor for the navigator.isApplicationInstalled()
4292 // API. Add as needed.
4293 private static Set<String> sGoogleApps;
4294 static {
4295 sGoogleApps = new HashSet<String>();
4296 sGoogleApps.add("com.google.android.youtube");
4297 }
4298
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004299 /**
4300 * A UrlData class to abstract how the content will be set to WebView.
4301 * This base class uses loadUrl to show the content.
4302 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004303 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004304 final String mUrl;
4305 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004306 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004307
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004308 UrlData(String url) {
4309 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004310 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004311 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004312 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004313
Leon Scroggins58d56c62010-01-28 15:12:40 -05004314 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004315 this.mUrl = url;
4316 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004317 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4318 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004319 this.mVoiceIntent = intent;
4320 } else {
4321 this.mVoiceIntent = null;
4322 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004323 }
4324
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004325 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004326 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004327 }
4328
Leon Scroggins92472e82010-02-17 16:32:28 -05004329 /**
4330 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4331 * the title bar as well.
4332 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004333 public void loadIn(Tab t) {
4334 if (mVoiceIntent != null) {
4335 t.activateVoiceSearchMode(mVoiceIntent);
4336 } else {
4337 t.getWebView().loadUrl(mUrl, mHeaders);
4338 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004339 }
4340 };
4341
Leon Scroggins1f005d32009-08-10 17:36:42 -04004342 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004343}