blob: ad82fd067b719da76b55461079039d12c9b7a4a6 [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;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800124import java.util.regex.Matcher;
125import java.util.regex.Pattern;
Ben Murdoch6af492a2010-06-15 12:38:17 +0100126import java.util.Vector;
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
Leon Scrogginsd746a942010-05-19 13:21:44 -0400217 if (mXLargeScreenSize) {
Leon Scroggins571b3762010-05-26 10:25:01 -0400218 mTitleBar = new TitleBarXLarge(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400219 LinearLayout layout = (LinearLayout) mBrowserFrameLayout.
220 findViewById(R.id.vertical_layout);
221 layout.addView(mTitleBar, 0, new LinearLayout.LayoutParams(
222 ViewGroup.LayoutParams.MATCH_PARENT,
223 ViewGroup.LayoutParams.WRAP_CONTENT));
224 } else {
Leon Scroggins571b3762010-05-26 10:25:01 -0400225 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400226 // mTitleBar will be always be shown in the fully loaded mode on
227 // phone
228 mTitleBar.setProgress(100);
229 // Fake title bar is not needed in xlarge layout
230 mFakeTitleBar = new TitleBar(this);
231 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800232
233 // Create the tab control and our initial tab
234 mTabControl = new TabControl(this);
235
236 // Open the icon database and retain all the bookmark urls for favicons
237 retainIconsOnStartup();
238
239 // Keep a settings instance handy.
240 mSettings = BrowserSettings.getInstance();
241 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800242
243 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
244 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
245
Patrick Scott6adacc92010-03-05 08:24:51 -0500246 // Find out if the network is currently up.
247 ConnectivityManager cm = (ConnectivityManager) getSystemService(
248 Context.CONNECTIVITY_SERVICE);
249 NetworkInfo info = cm.getActiveNetworkInfo();
250 if (info != null) {
251 mIsNetworkUp = info.isAvailable();
252 }
253
Grace Klobaa34f6862009-07-31 16:28:17 -0700254 /* enables registration for changes in network status from
255 http stack */
256 mNetworkStateChangedFilter = new IntentFilter();
257 mNetworkStateChangedFilter.addAction(
258 ConnectivityManager.CONNECTIVITY_ACTION);
259 mNetworkStateIntentReceiver = new BroadcastReceiver() {
260 @Override
261 public void onReceive(Context context, Intent intent) {
262 if (intent.getAction().equals(
263 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000264
265 NetworkInfo info = intent.getParcelableExtra(
266 ConnectivityManager.EXTRA_NETWORK_INFO);
267 String typeName = info.getTypeName();
268 String subtypeName = info.getSubtypeName();
269 sendNetworkType(typeName.toLowerCase(),
270 (subtypeName != null ? subtypeName.toLowerCase() : ""));
271
272 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700273 }
274 }
275 };
276
Grace Kloba615c6c92009-08-03 10:22:44 -0700277 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
278 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
279 filter.addDataScheme("package");
280 mPackageInstallationReceiver = new BroadcastReceiver() {
281 @Override
282 public void onReceive(Context context, Intent intent) {
283 final String action = intent.getAction();
284 final String packageName = intent.getData()
285 .getSchemeSpecificPart();
286 final boolean replacing = intent.getBooleanExtra(
287 Intent.EXTRA_REPLACING, false);
288 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
289 // if it is replacing, refreshPlugins() when adding
290 return;
291 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000292
293 if (sGoogleApps.contains(packageName)) {
294 BrowserActivity.this.packageChanged(packageName,
295 Intent.ACTION_PACKAGE_ADDED.equals(action));
296 }
297
Grace Kloba615c6c92009-08-03 10:22:44 -0700298 PackageManager pm = BrowserActivity.this.getPackageManager();
299 PackageInfo pkgInfo = null;
300 try {
301 pkgInfo = pm.getPackageInfo(packageName,
302 PackageManager.GET_PERMISSIONS);
303 } catch (PackageManager.NameNotFoundException e) {
304 return;
305 }
306 if (pkgInfo != null) {
307 String permissions[] = pkgInfo.requestedPermissions;
308 if (permissions == null) {
309 return;
310 }
311 boolean permissionOk = false;
312 for (String permit : permissions) {
313 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
314 permissionOk = true;
315 break;
316 }
317 }
318 if (permissionOk) {
319 PluginManager.getInstance(BrowserActivity.this)
Grace Klobae56a0f22010-05-26 17:31:02 -0700320 .refreshPlugins(true);
Grace Kloba615c6c92009-08-03 10:22:44 -0700321 }
322 }
323 }
324 };
325 registerReceiver(mPackageInstallationReceiver, filter);
326
The Android Open Source Project0c908882009-03-03 19:32:16 -0800327 if (!mTabControl.restoreState(icicle)) {
328 // clear up the thumbnail directory if we can't restore the state as
329 // none of the files in the directory are referenced any more.
330 new ClearThumbnails().execute(
331 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700332 // there is no quit on Android. But if we can't restore the state,
333 // we can treat it as a new Browser, remove the old session cookies.
334 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800335 final Intent intent = getIntent();
336 final Bundle extra = intent.getExtras();
337 // Create an initial tab.
338 // If the intent is ACTION_VIEW and data is not null, the Browser is
339 // invoked to view the content by another application. In this case,
340 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700341 UrlData urlData = getUrlDataFromIntent(intent);
342
Leon Scroggins58d56c62010-01-28 15:12:40 -0500343 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700344 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500345 (Intent.ACTION_VIEW.equals(action) &&
346 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500347 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
348 .equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700349 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800350 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800351 attachTabToContentView(t);
352 WebView webView = t.getWebView();
353 if (extra != null) {
354 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
355 if (scale > 0 && scale <= 1000) {
356 webView.setInitialScale(scale);
357 }
358 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800359
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700360 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700361 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800362 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500363 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800364 }
365 } else {
366 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400367 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800368 attachTabToContentView(mTabControl.getCurrentTab());
369 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700370
Cary Clarkb4b83182010-07-01 12:36:56 -0400371 // Delete old thumbnails to save space
372 File dir = mTabControl.getThumbnailDir();
373 if (dir.exists()) {
374 for (String child : dir.list()) {
375 File f = new File(dir, child);
376 f.delete();
377 }
378 }
379
Feng Qianb3c02da2009-06-29 15:58:08 -0700380 // Read JavaScript flags if it exists.
381 String jsFlags = mSettings.getJsFlags();
382 if (jsFlags.trim().length() != 0) {
383 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
384 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000385 // Work out which packages are installed on the system.
386 getInstalledPackages();
Bjorn Bringerta7611812010-03-24 11:12:02 +0000387
388 // Start watching the default geolocation permissions
389 mSystemAllowGeolocationOrigins
390 = new SystemAllowGeolocationOrigins(getApplicationContext());
391 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800392 }
393
Leon Scroggins58d56c62010-01-28 15:12:40 -0500394 /**
395 * Feed the previously stored results strings to the BrowserProvider so that
396 * the SearchDialog will show them instead of the standard searches.
397 * @param result String to show on the editable line of the SearchDialog.
398 */
399 /* package */ void showVoiceSearchResults(String result) {
400 ContentProviderClient client = mResolver.acquireContentProviderClient(
401 Browser.BOOKMARKS_URI);
402 ContentProvider prov = client.getLocalContentProvider();
403 BrowserProvider bp = (BrowserProvider) prov;
404 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
405 client.release();
406
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500407 Bundle bundle = createGoogleSearchSourceBundle(
408 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
409 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
410 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500411 }
412
The Android Open Source Project0c908882009-03-03 19:32:16 -0800413 @Override
414 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700415 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800416 // When a tab is closed on exit, the current tab index is set to -1.
417 // Reset before proceed as Browser requires the current tab to be set.
418 if (current == null) {
419 // Try to reset the tab in case the index was incorrect.
420 current = mTabControl.getTab(0);
421 if (current == null) {
422 // No tabs at all so just ignore this intent.
423 return;
424 }
425 mTabControl.setCurrentTab(current);
426 attachTabToContentView(current);
427 resetTitleAndIcon(current.getWebView());
428 }
429 final String action = intent.getAction();
430 final int flags = intent.getFlags();
431 if (Intent.ACTION_MAIN.equals(action) ||
432 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
433 // just resume the browser
434 return;
435 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400436 // In case the SearchDialog is open.
437 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
438 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500439 boolean activateVoiceSearch = RecognizerResultsIntent
440 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800441 if (Intent.ACTION_VIEW.equals(action)
442 || Intent.ACTION_SEARCH.equals(action)
443 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500444 || Intent.ACTION_WEB_SEARCH.equals(action)
445 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500446 if (current.isInVoiceSearchMode()) {
447 String title = current.getVoiceDisplayTitle();
448 if (title != null && title.equals(intent.getStringExtra(
449 SearchManager.QUERY))) {
450 // The user submitted the same search as the last voice
451 // search, so do nothing.
452 return;
453 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500454 if (Intent.ACTION_SEARCH.equals(action)
455 && current.voiceSearchSourceIsGoogle()) {
456 Intent logIntent = new Intent(
457 LoggingEvents.ACTION_LOG_EVENT);
458 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
459 LoggingEvents.VoiceSearch.QUERY_UPDATED);
460 logIntent.putExtra(
461 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
462 intent.getDataString());
463 sendBroadcast(logIntent);
464 // Note, onPageStarted will revert the voice title bar
465 // When http://b/issue?id=2379215 is fixed, we should update
466 // the title bar here.
467 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500468 }
Satish Sampath565505b2009-05-29 15:37:27 +0100469 // If this was a search request (e.g. search query directly typed into the address bar),
470 // pass it on to the default web search provider.
471 if (handleWebSearchIntent(intent)) {
472 return;
473 }
474
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700475 UrlData urlData = getUrlDataFromIntent(intent);
476 if (urlData.isEmpty()) {
477 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800478 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700479
Grace Klobacc634032009-07-28 15:58:19 -0700480 final String appId = intent
481 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400482 if ((Intent.ACTION_VIEW.equals(action)
483 // If a voice search has no appId, it means that it came
484 // from the browser. In that case, reuse the current tab.
485 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700486 && !getPackageName().equals(appId)
487 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700488 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700489 if (appTab != null) {
490 Log.i(LOGTAG, "Reusing tab for " + appId);
491 // Dismiss the subwindow if applicable.
492 dismissSubWindow(appTab);
493 // Since we might kill the WebView, remove it from the
494 // content view first.
495 removeTabFromContentView(appTab);
496 // Recreate the main WebView after destroying the old one.
497 // If the WebView has the same original url and is on that
498 // page, it can be reused.
499 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400500 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100501
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700502 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400503 switchToTab(mTabControl.getTabIndex(appTab));
504 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500505 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400506 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700507 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400508 // If the tab was the current tab, we have to attach
509 // it to the view system again.
510 attachTabToContentView(appTab);
511 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500512 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700513 }
514 }
515 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400516 } else {
517 // No matching application tab, try to find a regular tab
518 // with a matching url.
519 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400520 if (appTab != null) {
521 if (current != appTab) {
522 switchToTab(mTabControl.getTabIndex(appTab));
523 }
524 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400525 } else {
526 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
527 // will be opened in a new tab unless we have reached
528 // MAX_TABS. Then the url will be opened in the current
529 // tab. If a new tab is created, it will have "true" for
530 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400531 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400532 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700533 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800534 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800535 if (!urlData.isEmpty()
536 && urlData.mUrl.startsWith("about:debug")) {
537 if ("about:debug.dom".equals(urlData.mUrl)) {
538 current.getWebView().dumpDomTree(false);
539 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
540 current.getWebView().dumpDomTree(true);
541 } else if ("about:debug.render".equals(urlData.mUrl)) {
542 current.getWebView().dumpRenderTree(false);
543 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
544 current.getWebView().dumpRenderTree(true);
545 } else if ("about:debug.display".equals(urlData.mUrl)) {
546 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800547 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
548 int index = urlData.mUrl.codePointAt(16) - '0';
549 if (index <= 0 || index > 9) {
550 current.getWebView().setDragTracker(null);
551 } else {
552 current.getWebView().setDragTracker(new MeshTracker(index));
553 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800554 } else {
555 mSettings.toggleDebugSettings();
556 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800557 return;
558 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400559 // Get rid of the subwindow if it exists
560 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400561 // If the current Tab is being used as an application tab,
562 // remove the association, since the new Intent means that it is
563 // no longer associated with that application.
564 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500565 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800566 }
567 }
568 }
569
Satish Sampath565505b2009-05-29 15:37:27 +0100570 private int parseUrlShortcut(String url) {
571 if (url == null) return SHORTCUT_INVALID;
572
573 // FIXME: quick search, need to be customized by setting
574 if (url.length() > 2 && url.charAt(1) == ' ') {
575 switch (url.charAt(0)) {
576 case 'g': return SHORTCUT_GOOGLE_SEARCH;
577 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
578 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
579 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
580 }
581 }
582 return SHORTCUT_INVALID;
583 }
584
585 /**
586 * Launches the default web search activity with the query parameters if the given intent's data
587 * are identified as plain search terms and not URLs/shortcuts.
588 * @return true if the intent was handled and web search activity was launched, false if not.
589 */
590 private boolean handleWebSearchIntent(Intent intent) {
591 if (intent == null) return false;
592
593 String url = null;
594 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500595 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
596 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500597 return false;
598 }
Satish Sampath565505b2009-05-29 15:37:27 +0100599 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700600 Uri data = intent.getData();
601 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100602 } else if (Intent.ACTION_SEARCH.equals(action)
603 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
604 || Intent.ACTION_WEB_SEARCH.equals(action)) {
605 url = intent.getStringExtra(SearchManager.QUERY);
606 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100607 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
608 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100609 }
610
611 /**
612 * Launches the default web search activity with the query parameters if the given url string
613 * was identified as plain search terms and not URL/shortcut.
614 * @return true if the request was handled and web search activity was launched, false if not.
615 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100616 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100617 if (inUrl == null) return false;
618
619 // In general, we shouldn't modify URL from Intent.
620 // But currently, we get the user-typed URL from search box as well.
621 String url = fixUrl(inUrl).trim();
622
623 // URLs and site specific search shortcuts are handled by the regular flow of control, so
624 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800625 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100626 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100627 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
628 return false;
629 }
630
Leon Scroggins8d06e362010-03-24 14:45:57 -0400631 final ContentResolver cr = mResolver;
632 final String newUrl = url;
633 new AsyncTask<Void, Void, Void>() {
Michael Kolbe0a36662010-06-29 10:37:12 -0700634 @Override
Leon Scroggins8d06e362010-03-24 14:45:57 -0400635 protected Void doInBackground(Void... unused) {
636 Browser.updateVisitedHistory(cr, newUrl, false);
637 Browser.addSearchUrl(cr, newUrl);
638 return null;
639 }
640 }.execute();
Satish Sampath565505b2009-05-29 15:37:27 +0100641
642 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
643 intent.addCategory(Intent.CATEGORY_DEFAULT);
644 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100645 if (appData != null) {
646 intent.putExtra(SearchManager.APP_DATA, appData);
647 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100648 if (extraData != null) {
649 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
650 }
Grace Klobacc634032009-07-28 15:58:19 -0700651 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100652 startActivity(intent);
653
654 return true;
655 }
656
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700657 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500658 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800659 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800660 if (intent != null) {
661 final String action = intent.getAction();
662 if (Intent.ACTION_VIEW.equals(action)) {
663 url = smartUrlFilter(intent.getData());
664 if (url != null && url.startsWith("content:")) {
665 /* Append mimetype so webview knows how to display */
666 String mimeType = intent.resolveType(getContentResolver());
667 if (mimeType != null) {
668 url += "?" + mimeType;
669 }
670 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800671 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800672 final Bundle pairs = intent
673 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800674 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800675 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800676 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800677 while (iter.hasNext()) {
678 String key = iter.next();
679 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800680 }
681 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700682 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800683 } else if (Intent.ACTION_SEARCH.equals(action)
684 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
685 || Intent.ACTION_WEB_SEARCH.equals(action)) {
686 url = intent.getStringExtra(SearchManager.QUERY);
687 if (url != null) {
688 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800689 // In general, we shouldn't modify URL from Intent.
690 // But currently, we get the user-typed URL from search box as well.
691 url = fixUrl(url);
692 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400693 final ContentResolver cr = mResolver;
694 final String newUrl = url;
695 new AsyncTask<Void, Void, Void>() {
Michael Kolbe0a36662010-06-29 10:37:12 -0700696 @Override
Leon Scroggins8d06e362010-03-24 14:45:57 -0400697 protected Void doInBackground(Void... unused) {
698 Browser.updateVisitedHistory(cr, newUrl, false);
699 return null;
700 }
701 }.execute();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800702 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
703 if (url.contains(searchSource)) {
704 String source = null;
705 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
706 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000707 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800708 }
709 if (TextUtils.isEmpty(source)) {
710 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
711 }
712 url = url.replace(searchSource, "&source=android-"+source+"&");
713 }
714 }
715 }
716 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500717 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800718 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500719 /* package */ void showVoiceTitleBar(String title) {
720 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500721 mTitleBar.setDisplayTitle(title);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400722
723 if (!mXLargeScreenSize) {
724 mFakeTitleBar.setInVoiceMode(true);
725 mFakeTitleBar.setDisplayTitle(title);
726 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500727 }
728 /* package */ void revertVoiceTitleBar() {
729 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500730 mTitleBar.setDisplayTitle(mUrl);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400731
732 if (!mXLargeScreenSize) {
733 mFakeTitleBar.setInVoiceMode(false);
734 mFakeTitleBar.setDisplayTitle(mUrl);
735 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500736 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800737 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400738 // FIXME: Converting the url to lower case
739 // duplicates functionality in smartUrlFilter().
740 // However, changing all current callers of fixUrl to
741 // call smartUrlFilter in addition may have unwanted
742 // consequences, and is deferred for now.
743 int colon = inUrl.indexOf(':');
744 boolean allLower = true;
745 for (int index = 0; index < colon; index++) {
746 char ch = inUrl.charAt(index);
747 if (!Character.isLetter(ch)) {
748 break;
749 }
750 allLower &= Character.isLowerCase(ch);
751 if (index == colon - 1 && !allLower) {
752 inUrl = inUrl.substring(0, colon).toLowerCase()
753 + inUrl.substring(colon);
754 }
755 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800756 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
757 return inUrl;
758 if (inUrl.startsWith("http:") ||
759 inUrl.startsWith("https:")) {
760 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
761 inUrl = inUrl.replaceFirst("/", "//");
762 } else inUrl = inUrl.replaceFirst(":", "://");
763 }
764 return inUrl;
765 }
766
Grace Kloba22ac16e2009-10-07 18:00:23 -0700767 @Override
768 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800769 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700770 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800771 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
772 }
773
774 if (!mActivityInPause) {
775 Log.e(LOGTAG, "BrowserActivity is already resumed.");
776 return;
777 }
778
Mike Reed7bfa63b2009-05-28 11:08:32 -0400779 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800780 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400781 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800782
783 if (mWakeLock.isHeld()) {
784 mHandler.removeMessages(RELEASE_WAKELOCK);
785 mWakeLock.release();
786 }
787
The Android Open Source Project0c908882009-03-03 19:32:16 -0800788 registerReceiver(mNetworkStateIntentReceiver,
789 mNetworkStateChangedFilter);
790 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800791 }
792
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400793 /**
794 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400795 * would change its appearance, use a different TitleBar to show overlayed
796 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400797 */
798 private TitleBar mFakeTitleBar;
799
800 /**
801 * Keeps track of whether the options menu is open. This is important in
802 * determining whether to show or hide the title bar overlay.
803 */
804 private boolean mOptionsMenuOpen;
805
806 /**
807 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
808 * of whether the configuration has changed. The first onMenuOpened call
809 * after a configuration change is simply a reopening of the same menu
810 * (i.e. mIconView did not change).
811 */
812 private boolean mConfigChanged;
813
814 /**
815 * Whether or not the options menu is in its smaller, icon menu form. When
816 * true, we want the title bar overlay to be up. When false, we do not.
817 * Only meaningful if mOptionsMenuOpen is true.
818 */
819 private boolean mIconView;
820
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400821 @Override
822 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400823 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
824 if (mOptionsMenuOpen) {
825 if (mConfigChanged) {
826 // We do not need to make any changes to the state of the
827 // title bar, since the only thing that happened was a
828 // change in orientation
829 mConfigChanged = false;
830 } else {
831 if (mIconView) {
832 // Switching the menu to expanded view, so hide the
833 // title bar.
834 hideFakeTitleBar();
835 mIconView = false;
836 } else {
837 // Switching the menu back to icon view, so show the
838 // title bar once again.
839 showFakeTitleBar();
840 mIconView = true;
841 }
842 }
843 } else {
844 // The options menu is closed, so open it, and show the title
845 showFakeTitleBar();
846 mOptionsMenuOpen = true;
847 mConfigChanged = false;
848 mIconView = true;
849 }
850 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400851 return true;
852 }
853
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400854 private void showFakeTitleBar() {
Leon Scrogginsd746a942010-05-19 13:21:44 -0400855 if (mXLargeScreenSize) return;
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400856 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Grace Kloba847c25b2010-03-30 16:00:26 -0700857 && !mActivityInPause) {
858 WebView mainView = mTabControl.getCurrentWebView();
859 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700860 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400861 return;
862 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100863 // Do not need to check for null, since the current tab will have
864 // at least a main WebView, or we would have returned above.
Cary Clark01cfcdd2010-06-04 16:36:45 -0400865 if (dialogIsUp()) {
Leon Scroggins79e36d92010-04-29 16:01:46 +0100866 // Do not show the fake title bar, which would cover up the
Cary Clark01cfcdd2010-06-04 16:36:45 -0400867 // find or select dialog.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100868 return;
869 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400870
871 WindowManager manager
872 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
873
874 // Add the title bar to the window manager so it can receive touches
875 // while the menu is up
876 WindowManager.LayoutParams params
877 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800878 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400879 ViewGroup.LayoutParams.WRAP_CONTENT,
Grace Kloba847c25b2010-03-30 16:00:26 -0700880 WindowManager.LayoutParams.TYPE_APPLICATION,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400881 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400882 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400883 params.gravity = Gravity.TOP;
Grace Kloba847c25b2010-03-30 16:00:26 -0700884 boolean atTop = mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400885 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Grace Kloba13f9ace2010-03-18 21:44:14 -0700886 manager.addView(mFakeTitleBar, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400887 }
888 }
889
890 @Override
891 public void onOptionsMenuClosed(Menu menu) {
892 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400893 if (!mInLoad) {
894 hideFakeTitleBar();
895 } else if (!mIconView) {
896 // The page is currently loading, and we are in expanded mode, so
897 // we were not showing the menu. Show it once again. It will be
898 // removed when the page finishes.
899 showFakeTitleBar();
900 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400901 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700902
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400903 private void hideFakeTitleBar() {
Leon Scrogginsd746a942010-05-19 13:21:44 -0400904 if (mXLargeScreenSize || mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400905 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
Grace Kloba13f9ace2010-03-18 21:44:14 -0700906 mFakeTitleBar.getLayoutParams();
Leon Scroggins20329572009-09-23 17:42:41 -0400907 WebView mainView = mTabControl.getCurrentWebView();
908 // Although we decided whether or not to animate based on the current
909 // scroll position, the scroll position may have changed since the
910 // fake title bar was displayed. Make sure it has the appropriate
911 // animation/lack thereof before removing.
912 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400913 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400914 WindowManager manager
915 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Grace Kloba13f9ace2010-03-18 21:44:14 -0700916 manager.updateViewLayout(mFakeTitleBar, params);
917 manager.removeView(mFakeTitleBar);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400918 }
919
The Android Open Source Project0c908882009-03-03 19:32:16 -0800920 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400921 * Special method for the fake title bar to call when displaying its context
922 * menu, since it is in its own Window, and its parent does not show a
923 * context menu.
924 */
925 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400926 if (null == mTitleBar.getParent()) {
927 return;
928 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400929 openContextMenu(mTitleBar);
930 }
931
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400932 @Override
933 public void onContextMenuClosed(Menu menu) {
934 super.onContextMenuClosed(menu);
935 if (mInLoad) {
936 showFakeTitleBar();
937 }
938 }
939
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400940 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800941 * onSaveInstanceState(Bundle map)
942 * onSaveInstanceState is called right before onStop(). The map contains
943 * the saved state.
944 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700945 @Override
946 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700947 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800948 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
949 }
950 // the default implementation requires each view to have an id. As the
951 // browser handles the state itself and it doesn't use id for the views,
952 // don't call the default implementation. Otherwise it will trigger the
953 // warning like this, "couldn't save which view has focus because the
954 // focused view XXX has no id".
955
956 // Save all the tabs
957 mTabControl.saveState(outState);
958 }
959
Grace Kloba22ac16e2009-10-07 18:00:23 -0700960 @Override
961 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800962 super.onPause();
963
964 if (mActivityInPause) {
965 Log.e(LOGTAG, "BrowserActivity is already paused.");
966 return;
967 }
968
Mike Reed7bfa63b2009-05-28 11:08:32 -0400969 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800970 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400971 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800972 mWakeLock.acquire();
973 mHandler.sendMessageDelayed(mHandler
974 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
975 }
976
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400977 // FIXME: This removes the active tabs page and resets the menu to
978 // MAIN_MENU. A better solution might be to do this work in onNewIntent
979 // but then we would need to save it in onSaveInstanceState and restore
980 // it in onCreate/onRestoreInstanceState
981 if (mActiveTabsPage != null) {
982 removeActiveTabPage(true);
983 }
984
The Android Open Source Project0c908882009-03-03 19:32:16 -0800985 cancelStopToast();
986
987 // unregister network state listener
988 unregisterReceiver(mNetworkStateIntentReceiver);
989 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800990 }
991
Grace Kloba22ac16e2009-10-07 18:00:23 -0700992 @Override
993 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700994 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800995 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
996 }
997 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700998
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400999 if (mUploadMessage != null) {
1000 mUploadMessage.onReceiveValue(null);
1001 mUploadMessage = null;
1002 }
1003
Grace Kloba0923d692009-09-23 21:37:25 -07001004 if (mTabControl == null) return;
1005
Grace Kloba1fc98a32009-10-21 13:23:08 -07001006 // Remove the fake title bar if it is there
1007 hideFakeTitleBar();
1008
The Android Open Source Project0c908882009-03-03 19:32:16 -08001009 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001010 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001011 if (t != null) {
1012 dismissSubWindow(t);
1013 removeTabFromContentView(t);
1014 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001015 // Destroy all the tabs
1016 mTabControl.destroy();
1017 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001018
Grace Klobab4da0ad2009-05-14 14:45:40 -07001019 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +00001020
1021 // Stop watching the default geolocation permissions
1022 mSystemAllowGeolocationOrigins.stop();
1023 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001024 }
1025
1026 @Override
1027 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001028 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001029 super.onConfigurationChanged(newConfig);
1030
1031 if (mPageInfoDialog != null) {
1032 mPageInfoDialog.dismiss();
1033 showPageInfo(
1034 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001035 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001036 }
1037 if (mSSLCertificateDialog != null) {
1038 mSSLCertificateDialog.dismiss();
1039 showSSLCertificate(
1040 mSSLCertificateView);
1041 }
1042 if (mSSLCertificateOnErrorDialog != null) {
1043 mSSLCertificateOnErrorDialog.dismiss();
1044 showSSLCertificateOnError(
1045 mSSLCertificateOnErrorView,
1046 mSSLCertificateOnErrorHandler,
1047 mSSLCertificateOnErrorError);
1048 }
1049 if (mHttpAuthenticationDialog != null) {
1050 String title = ((TextView) mHttpAuthenticationDialog
1051 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1052 .toString();
1053 String name = ((TextView) mHttpAuthenticationDialog
1054 .findViewById(R.id.username_edit)).getText().toString();
1055 String password = ((TextView) mHttpAuthenticationDialog
1056 .findViewById(R.id.password_edit)).getText().toString();
1057 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1058 .getId();
1059 mHttpAuthenticationDialog.dismiss();
1060 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1061 name, password, focusId);
1062 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001063 }
1064
Grace Kloba22ac16e2009-10-07 18:00:23 -07001065 @Override
1066 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001067 super.onLowMemory();
1068 mTabControl.freeMemory();
1069 }
1070
Cary Clarkff4d92c2010-03-25 11:17:03 -04001071 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001072 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001073 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001074 boolean inLoad = tab.inLoad();
1075 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001076 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001077 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001078 if (w != null) {
1079 w.resumeTimers();
1080 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001081 }
1082 }
1083
Mike Reed7bfa63b2009-05-28 11:08:32 -04001084 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001085 Tab tab = mTabControl.getCurrentTab();
1086 boolean inLoad = tab.inLoad();
1087 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001088 CookieSyncManager.getInstance().stopSync();
1089 WebView w = mTabControl.getCurrentWebView();
1090 if (w != null) {
1091 w.pauseTimers();
1092 }
1093 return true;
1094 } else {
1095 return false;
1096 }
1097 }
1098
The Android Open Source Project0c908882009-03-03 19:32:16 -08001099 // Open the icon database and retain all the icons for visited sites.
1100 private void retainIconsOnStartup() {
1101 final WebIconDatabase db = WebIconDatabase.getInstance();
1102 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001103 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001104 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001105 c = Browser.getAllBookmarks(mResolver);
1106 if (c.moveToFirst()) {
1107 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1108 do {
1109 String url = c.getString(urlIndex);
1110 db.retainIconForPageUrl(url);
1111 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001112 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001113 } catch (IllegalStateException e) {
1114 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001115 } finally {
1116 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001117 }
1118 }
1119
1120 // Helper method for getting the top window.
1121 WebView getTopWindow() {
1122 return mTabControl.getCurrentTopWebView();
1123 }
1124
Grace Kloba22ac16e2009-10-07 18:00:23 -07001125 TabControl getTabControl() {
1126 return mTabControl;
1127 }
1128
The Android Open Source Project0c908882009-03-03 19:32:16 -08001129 @Override
1130 public boolean onCreateOptionsMenu(Menu menu) {
1131 super.onCreateOptionsMenu(menu);
1132
1133 MenuInflater inflater = getMenuInflater();
1134 inflater.inflate(R.menu.browser, menu);
1135 mMenu = menu;
1136 updateInLoadMenuItems();
1137 return true;
1138 }
1139
1140 /**
1141 * As the menu can be open when loading state changes
1142 * we must manually update the state of the stop/reload menu
1143 * item
1144 */
1145 private void updateInLoadMenuItems() {
1146 if (mMenu == null) {
1147 return;
1148 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001149 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001150 MenuItem src = mInLoad ?
1151 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001152 mMenu.findItem(R.id.reload_menu_id);
1153 if (src != null) {
1154 dest.setIcon(src.getIcon());
1155 dest.setTitle(src.getTitle());
1156 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001157 }
1158
1159 @Override
1160 public boolean onContextItemSelected(MenuItem item) {
1161 // chording is not an issue with context menus, but we use the same
1162 // options selector, so set mCanChord to true so we can access them.
1163 mCanChord = true;
1164 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001165 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001166 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001167 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001168 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001169 Tab currentTab = mTabControl.getCurrentTab();
1170 if (null == currentTab) {
1171 result = false;
1172 break;
1173 }
1174 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001175 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001176 result = false;
1177 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001178 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001179 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001180 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001181 // -- Browser context menu
1182 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001183 case R.id.bookmark_context_menu_id:
1184 case R.id.save_link_context_menu_id:
1185 case R.id.share_link_context_menu_id:
1186 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001187 final WebView webView = getTopWindow();
1188 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001189 result = false;
1190 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001191 }
1192 final HashMap hrefMap = new HashMap();
1193 hrefMap.put("webview", webView);
1194 final Message msg = mHandler.obtainMessage(
1195 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001196 webView.requestFocusNodeHref(msg);
1197 break;
1198
1199 default:
1200 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001201 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001202 }
1203 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001204 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001205 }
1206
1207 private Bundle createGoogleSearchSourceBundle(String source) {
1208 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001209 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001210 return bundle;
1211 }
1212
Leon Scroggins8ad29922010-02-16 12:33:55 -05001213 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001214 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001215 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001216 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001217 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001218 }
1219
Leon Scroggins8ad29922010-02-16 12:33:55 -05001220 /**
1221 * Overriding this to insert a local information bundle
1222 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001223 @Override
1224 public void startSearch(String initialQuery, boolean selectInitialQuery,
1225 Bundle appSearchData, boolean globalSearch) {
1226 if (appSearchData == null) {
1227 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1228 }
1229 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1230 }
1231
Leon Scroggins1f005d32009-08-10 17:36:42 -04001232 /**
1233 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1234 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001235 * @param index Index of the tab to change to, as defined by
1236 * mTabControl.getTabIndex(Tab t).
1237 * @return boolean True if we successfully switched to a different tab. If
1238 * the indexth tab is null, or if that tab is the same as
1239 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001240 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001241 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001242 Tab tab = mTabControl.getTab(index);
1243 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001244 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001245 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001246 }
1247 if (currentTab != null) {
1248 // currentTab may be null if it was just removed. In that case,
1249 // we do not need to remove it
1250 removeTabFromContentView(currentTab);
1251 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001252 mTabControl.setCurrentTab(tab);
1253 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001254 resetTitleIconAndProgress();
1255 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001256 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001257 }
1258
Grace Kloba22ac16e2009-10-07 18:00:23 -07001259 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001260 return openTabAndShow(mSettings.getHomePage(), false, null);
1261 }
1262
Leon Scroggins1f005d32009-08-10 17:36:42 -04001263 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001264 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001265 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001266 // This is the last tab. Open a new one, with the home
1267 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001268 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001269 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001270 return;
1271 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001272 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001273 int indexToShow = -1;
1274 if (parent != null) {
1275 indexToShow = mTabControl.getTabIndex(parent);
1276 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001277 final int currentIndex = mTabControl.getCurrentIndex();
1278 // Try to move to the tab to the right
1279 indexToShow = currentIndex + 1;
1280 if (indexToShow > mTabControl.getTabCount() - 1) {
1281 // Try to move to the tab to the left
1282 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001283 }
1284 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001285 if (switchToTab(indexToShow)) {
1286 // Close window
1287 closeTab(current);
1288 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001289 }
1290
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001291 private ActiveTabsPage mActiveTabsPage;
1292
1293 /**
1294 * Remove the active tabs page.
1295 * @param needToAttach If true, the active tabs page did not attach a tab
1296 * to the content view, so we need to do that here.
1297 */
1298 /* package */ void removeActiveTabPage(boolean needToAttach) {
1299 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001300 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001301 mActiveTabsPage = null;
1302 mMenuState = R.id.MAIN_MENU;
1303 if (needToAttach) {
1304 attachTabToContentView(mTabControl.getCurrentTab());
1305 }
1306 getTopWindow().requestFocus();
1307 }
1308
Cary Clark01cfcdd2010-06-04 16:36:45 -04001309 private WebView showDialog(WebDialog dialog) {
1310 // Need to do something special for Tablet
1311 Tab tab = mTabControl.getCurrentTab();
1312 if (tab.getSubWebView() == null) {
1313 // If the find or select is being performed on the main webview,
1314 // remove the embedded title bar.
1315 WebView mainView = tab.getWebView();
1316 if (mainView != null) {
1317 mainView.setEmbeddedTitleBar(null);
1318 }
1319 }
1320 hideFakeTitleBar();
1321 mMenuState = EMPTY_MENU;
1322 return tab.showDialog(dialog);
1323 }
1324
The Android Open Source Project0c908882009-03-03 19:32:16 -08001325 @Override
1326 public boolean onOptionsItemSelected(MenuItem item) {
1327 if (!mCanChord) {
1328 // The user has already fired a shortcut with this hold down of the
1329 // menu key.
1330 return false;
1331 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001332 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001333 return false;
1334 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001335 if (mMenuIsDown) {
1336 // The shortcut action consumes the MENU. Even if it is still down,
1337 // it won't trigger the next shortcut action. In the case of the
1338 // shortcut action triggering a new activity, like Bookmarks, we
1339 // won't get onKeyUp for MENU. So it is important to reset it here.
1340 mMenuIsDown = false;
1341 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001342 switch (item.getItemId()) {
1343 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001344 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001345 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001346 break;
1347
Leon Scroggins64b80f32009-08-07 12:03:34 -04001348 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001349 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001350 break;
1351
1352 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001353 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001354 break;
1355
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001356 case R.id.active_tabs_menu_id:
1357 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1358 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001359 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001360 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001361 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1362 mActiveTabsPage.requestFocus();
1363 mMenuState = EMPTY_MENU;
1364 break;
1365
Leon Scroggins1f005d32009-08-10 17:36:42 -04001366 case R.id.add_bookmark_menu_id:
Leon Scroggins571b3762010-05-26 10:25:01 -04001367 bookmarkCurrentPage();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001368 break;
1369
1370 case R.id.stop_reload_menu_id:
1371 if (mInLoad) {
1372 stopLoading();
1373 } else {
1374 getTopWindow().reload();
1375 }
1376 break;
1377
1378 case R.id.back_menu_id:
1379 getTopWindow().goBack();
1380 break;
1381
1382 case R.id.forward_menu_id:
1383 getTopWindow().goForward();
1384 break;
1385
1386 case R.id.close_menu_id:
1387 // Close the subwindow if it exists.
1388 if (mTabControl.getCurrentSubWindow() != null) {
1389 dismissSubWindow(mTabControl.getCurrentTab());
1390 break;
1391 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001392 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001393 break;
1394
1395 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001396 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001397 if (current != null) {
1398 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001399 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001400 }
1401 break;
1402
1403 case R.id.preferences_menu_id:
1404 Intent intent = new Intent(this,
1405 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001406 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1407 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001408 startActivityForResult(intent, PREFERENCES_PAGE);
1409 break;
1410
1411 case R.id.find_menu_id:
Cary Clark01cfcdd2010-06-04 16:36:45 -04001412 showFindDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001413 break;
1414
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001415 case R.id.save_webarchive_menu_id:
1416 if (LOGD_ENABLED) {
1417 Log.d(LOGTAG, "Save as Web Archive");
1418 }
1419 String directory = getExternalFilesDir(null).getAbsolutePath() + File.separator;
1420 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1421 @Override
1422 public void onReceiveValue(String value) {
1423 if (value != null) {
1424 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved, Toast.LENGTH_SHORT).show();
1425 } else {
1426 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed, Toast.LENGTH_SHORT).show();
1427 }
1428 }
1429 });
1430 break;
1431
The Android Open Source Project0c908882009-03-03 19:32:16 -08001432 case R.id.page_info_menu_id:
1433 showPageInfo(mTabControl.getCurrentTab(), false);
1434 break;
1435
1436 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001437 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001438 break;
1439
Leon Scroggins96afcb12009-12-10 12:35:56 -05001440 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001441 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001442 Tab currentTab = mTabControl.getCurrentTab();
1443 if (null == currentTab) {
1444 mCanChord = false;
1445 return false;
1446 }
1447 currentTab.populatePickerData();
1448 sharePage(this, currentTab.getTitle(),
1449 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001450 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1451 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001452 break;
1453
1454 case R.id.dump_nav_menu_id:
1455 getTopWindow().debugDump();
1456 break;
1457
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001458 case R.id.dump_counters_menu_id:
1459 getTopWindow().dumpV8Counters();
1460 break;
1461
The Android Open Source Project0c908882009-03-03 19:32:16 -08001462 case R.id.zoom_in_menu_id:
1463 getTopWindow().zoomIn();
1464 break;
1465
1466 case R.id.zoom_out_menu_id:
1467 getTopWindow().zoomOut();
1468 break;
1469
1470 case R.id.view_downloads_menu_id:
1471 viewDownloads(null);
1472 break;
1473
The Android Open Source Project0c908882009-03-03 19:32:16 -08001474 case R.id.window_one_menu_id:
1475 case R.id.window_two_menu_id:
1476 case R.id.window_three_menu_id:
1477 case R.id.window_four_menu_id:
1478 case R.id.window_five_menu_id:
1479 case R.id.window_six_menu_id:
1480 case R.id.window_seven_menu_id:
1481 case R.id.window_eight_menu_id:
1482 {
1483 int menuid = item.getItemId();
1484 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1485 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001486 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001487 if (desiredTab != null &&
1488 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001489 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001490 }
1491 break;
1492 }
1493 }
1494 }
1495 break;
1496
1497 default:
1498 if (!super.onOptionsItemSelected(item)) {
1499 return false;
1500 }
1501 // Otherwise fall through.
1502 }
1503 mCanChord = false;
1504 return true;
1505 }
1506
Leon Scroggins571b3762010-05-26 10:25:01 -04001507 /* package */ void bookmarkCurrentPage() {
1508 Intent i = new Intent(BrowserActivity.this,
1509 AddBookmarkPage.class);
1510 WebView w = getTopWindow();
1511 i.putExtra("url", w.getUrl());
1512 i.putExtra("title", w.getTitle());
1513 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001514 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1515 getDesiredThumbnailHeight(this)));
Ben Murdocheecb4e62010-07-06 16:30:38 +01001516 i.putExtra("url_editable", false);
Leon Scroggins571b3762010-05-26 10:25:01 -04001517 startActivity(i);
1518 }
1519
Cary Clark01cfcdd2010-06-04 16:36:45 -04001520 private boolean dialogIsUp() {
1521 return null != mFindDialog && mFindDialog.isVisible() ||
1522 null != mSelectDialog && mSelectDialog.isVisible();
1523 }
1524
1525 private boolean closeDialog(WebDialog dialog) {
1526 if (null == dialog || !dialog.isVisible()) return false;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001527 Tab currentTab = mTabControl.getCurrentTab();
Cary Clark01cfcdd2010-06-04 16:36:45 -04001528 currentTab.closeDialog(dialog);
1529 dialog.dismiss();
1530 return true;
1531 }
1532
1533 /*
1534 * Remove the find dialog or select dialog.
1535 */
1536 public void closeDialogs() {
1537 if (!(closeDialog(mFindDialog) || closeDialog(mSelectDialog))) return;
Leon Scrogginsd746a942010-05-19 13:21:44 -04001538 if (!mXLargeScreenSize) {
1539 // If the Find was being performed in the main WebView, replace the
1540 // embedded title bar.
Cary Clark01cfcdd2010-06-04 16:36:45 -04001541 Tab currentTab = mTabControl.getCurrentTab();
Leon Scrogginsd746a942010-05-19 13:21:44 -04001542 if (currentTab.getSubWebView() == null) {
1543 WebView mainView = currentTab.getWebView();
1544 if (mainView != null) {
1545 mainView.setEmbeddedTitleBar(mTitleBar);
1546 }
Leon Scroggins79e36d92010-04-29 16:01:46 +01001547 }
1548 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001549 mMenuState = R.id.MAIN_MENU;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001550 if (mInLoad) {
1551 // The title bar was hidden, because otherwise it would cover up the
Cary Clark01cfcdd2010-06-04 16:36:45 -04001552 // find or select dialog. Now that the dialog has been removed,
1553 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001554 showFakeTitleBar();
1555 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001556 }
1557
Cary Clark01cfcdd2010-06-04 16:36:45 -04001558 public void showFindDialog() {
1559 if (null == mFindDialog) {
1560 mFindDialog = new FindDialog(this);
1561 }
1562 showDialog(mFindDialog).setFindIsUp(true);
1563 }
1564
1565 public void setFindDialogText(String text) {
1566 mFindDialog.setText(text);
1567 }
1568
1569 public void showSelectDialog() {
1570 if (null == mSelectDialog) {
1571 mSelectDialog = new SelectDialog(this);
1572 }
1573 showDialog(mSelectDialog).setUpSelect();
1574 mSelectDialog.hideSoftInput();
1575 }
1576
Grace Kloba22ac16e2009-10-07 18:00:23 -07001577 @Override
1578 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001579 // This happens when the user begins to hold down the menu key, so
1580 // allow them to chord to get a shortcut.
1581 mCanChord = true;
1582 // Note: setVisible will decide whether an item is visible; while
1583 // setEnabled() will decide whether an item is enabled, which also means
1584 // whether the matching shortcut key will function.
1585 super.onPrepareOptionsMenu(menu);
1586 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001587 case EMPTY_MENU:
1588 if (mCurrentMenuState != mMenuState) {
1589 menu.setGroupVisible(R.id.MAIN_MENU, false);
1590 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1591 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001592 }
1593 break;
1594 default:
1595 if (mCurrentMenuState != mMenuState) {
1596 menu.setGroupVisible(R.id.MAIN_MENU, true);
1597 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1598 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001599 }
1600 final WebView w = getTopWindow();
1601 boolean canGoBack = false;
1602 boolean canGoForward = false;
1603 boolean isHome = false;
1604 if (w != null) {
1605 canGoBack = w.canGoBack();
1606 canGoForward = w.canGoForward();
1607 isHome = mSettings.getHomePage().equals(w.getUrl());
1608 }
1609 final MenuItem back = menu.findItem(R.id.back_menu_id);
1610 back.setEnabled(canGoBack);
1611
1612 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1613 home.setEnabled(!isHome);
1614
Michael Kolbe0a36662010-06-29 10:37:12 -07001615 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1616 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001617
Michael Kolbe0a36662010-06-29 10:37:12 -07001618 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1619 newtab.setEnabled(mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001620
The Android Open Source Project0c908882009-03-03 19:32:16 -08001621 // decide whether to show the share link option
1622 PackageManager pm = getPackageManager();
1623 Intent send = new Intent(Intent.ACTION_SEND);
1624 send.setType("text/plain");
1625 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1626 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1627
The Android Open Source Project0c908882009-03-03 19:32:16 -08001628 boolean isNavDump = mSettings.isNavDump();
1629 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1630 nav.setVisible(isNavDump);
1631 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001632
1633 boolean showDebugSettings = mSettings.showDebugSettings();
1634 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1635 counter.setVisible(showDebugSettings);
1636 counter.setEnabled(showDebugSettings);
1637
The Android Open Source Project0c908882009-03-03 19:32:16 -08001638 break;
1639 }
1640 mCurrentMenuState = mMenuState;
1641 return true;
1642 }
1643
1644 @Override
1645 public void onCreateContextMenu(ContextMenu menu, View v,
1646 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001647 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001648 return;
1649 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001650 WebView webview = (WebView) v;
1651 WebView.HitTestResult result = webview.getHitTestResult();
1652 if (result == null) {
1653 return;
1654 }
1655
1656 int type = result.getType();
1657 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1658 Log.w(LOGTAG,
1659 "We should not show context menu when nothing is touched");
1660 return;
1661 }
1662 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1663 // let TextView handles context menu
1664 return;
1665 }
1666
1667 // Note, http://b/issue?id=1106666 is requesting that
1668 // an inflated menu can be used again. This is not available
1669 // yet, so inflate each time (yuk!)
1670 MenuInflater inflater = getMenuInflater();
1671 inflater.inflate(R.menu.browsercontext, menu);
1672
1673 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001674 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001675 menu.setGroupVisible(R.id.PHONE_MENU,
1676 type == WebView.HitTestResult.PHONE_TYPE);
1677 menu.setGroupVisible(R.id.EMAIL_MENU,
1678 type == WebView.HitTestResult.EMAIL_TYPE);
1679 menu.setGroupVisible(R.id.GEO_MENU,
1680 type == WebView.HitTestResult.GEO_TYPE);
1681 menu.setGroupVisible(R.id.IMAGE_MENU,
1682 type == WebView.HitTestResult.IMAGE_TYPE
1683 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1684 menu.setGroupVisible(R.id.ANCHOR_MENU,
1685 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1686 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1687
1688 // Setup custom handling depending on the type
1689 switch (type) {
1690 case WebView.HitTestResult.PHONE_TYPE:
1691 menu.setHeaderTitle(Uri.decode(extra));
1692 menu.findItem(R.id.dial_context_menu_id).setIntent(
1693 new Intent(Intent.ACTION_VIEW, Uri
1694 .parse(WebView.SCHEME_TEL + extra)));
1695 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1696 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001697 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001698 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1699 addIntent);
1700 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1701 new Copy(extra));
1702 break;
1703
1704 case WebView.HitTestResult.EMAIL_TYPE:
1705 menu.setHeaderTitle(extra);
1706 menu.findItem(R.id.email_context_menu_id).setIntent(
1707 new Intent(Intent.ACTION_VIEW, Uri
1708 .parse(WebView.SCHEME_MAILTO + extra)));
1709 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1710 new Copy(extra));
1711 break;
1712
1713 case WebView.HitTestResult.GEO_TYPE:
1714 menu.setHeaderTitle(extra);
1715 menu.findItem(R.id.map_context_menu_id).setIntent(
1716 new Intent(Intent.ACTION_VIEW, Uri
1717 .parse(WebView.SCHEME_GEO
1718 + URLEncoder.encode(extra))));
1719 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1720 new Copy(extra));
1721 break;
1722
1723 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1724 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1725 TextView titleView = (TextView) LayoutInflater.from(this)
1726 .inflate(android.R.layout.browser_link_context_header,
1727 null);
1728 titleView.setText(extra);
1729 menu.setHeaderView(titleView);
1730 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001731 boolean showNewTab = mTabControl.canCreateNewTab();
1732 MenuItem newTabItem
1733 = menu.findItem(R.id.open_newtab_context_menu_id);
1734 newTabItem.setVisible(showNewTab);
1735 if (showNewTab) {
1736 newTabItem.setOnMenuItemClickListener(
1737 new MenuItem.OnMenuItemClickListener() {
1738 public boolean onMenuItemClick(MenuItem item) {
1739 final Tab parent = mTabControl.getCurrentTab();
1740 final Tab newTab = openTab(extra);
1741 if (newTab != parent) {
1742 parent.addChildTab(newTab);
1743 }
1744 return true;
1745 }
1746 });
1747 }
Ben Murdochde353622009-10-12 10:29:00 +01001748 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1749 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001750 PackageManager pm = getPackageManager();
1751 Intent send = new Intent(Intent.ACTION_SEND);
1752 send.setType("text/plain");
1753 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1754 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1755 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1756 break;
1757 }
1758 // otherwise fall through to handle image part
1759 case WebView.HitTestResult.IMAGE_TYPE:
1760 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1761 menu.setHeaderTitle(extra);
1762 }
1763 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1764 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1765 menu.findItem(R.id.download_context_menu_id).
1766 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001767 menu.findItem(R.id.set_wallpaper_context_menu_id).
1768 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001769 break;
1770
1771 default:
1772 Log.w(LOGTAG, "We should not get here.");
1773 break;
1774 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001775 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001776 }
1777
The Android Open Source Project0c908882009-03-03 19:32:16 -08001778 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001779 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001780 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001781 // Attach the container that contains the main WebView and any other UI
1782 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001783 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001784
1785 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001786 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001787 if (errorConsole.numberOfErrors() == 0) {
1788 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1789 } else {
1790 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1791 }
1792
1793 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001794 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001795 ViewGroup.LayoutParams.WRAP_CONTENT));
1796 }
1797
Leon Scrogginsd746a942010-05-19 13:21:44 -04001798 if (!mXLargeScreenSize){
1799 WebView view = t.getWebView();
1800 view.setEmbeddedTitleBar(mTitleBar);
1801 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001802 if (t.isInVoiceSearchMode()) {
1803 showVoiceTitleBar(t.getVoiceDisplayTitle());
1804 } else {
1805 revertVoiceTitleBar();
1806 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001807 // Request focus on the top window.
1808 t.getTopWindow().requestFocus();
1809 }
1810
1811 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001812 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001813 t.attachSubWindow(mContentView);
1814 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001815 }
1816
1817 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001818 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001819 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001820 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001821
Grace Kloba22ac16e2009-10-07 18:00:23 -07001822 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1823 if (errorConsole != null) {
1824 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001825 }
1826
Leon Scrogginsd746a942010-05-19 13:21:44 -04001827 if (!mXLargeScreenSize) {
1828 WebView view = t.getWebView();
1829 if (view != null) {
1830 view.setEmbeddedTitleBar(null);
1831 }
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001832 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001833 }
1834
1835 // Remove the sub window if it exists. Also called by TabControl when the
1836 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001837 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001838 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001839 // dismiss the subwindow. This will destroy the WebView.
1840 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001841 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001842 }
1843
Leon Scroggins1f005d32009-08-10 17:36:42 -04001844 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001845 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001846 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001847 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001848 }
1849
1850 // This method does a ton of stuff. It will attempt to create a new tab
1851 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001852 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001853 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1854 String appId) {
1855 final Tab currentTab = mTabControl.getCurrentTab();
1856 if (mTabControl.canCreateNewTab()) {
1857 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1858 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001859 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001860 // If the last tab was removed from the active tabs page, currentTab
1861 // will be null.
1862 if (currentTab != null) {
1863 removeTabFromContentView(currentTab);
1864 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001865 // We must set the new tab as the current tab to reflect the old
1866 // animation behavior.
1867 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001868 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001869 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001870 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001871 }
1872 return tab;
1873 } else {
1874 // Get rid of the subwindow if it exists
1875 dismissSubWindow(currentTab);
1876 if (!urlData.isEmpty()) {
1877 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001878 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001879 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001880 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001881 }
1882 }
1883
Grace Kloba22ac16e2009-10-07 18:00:23 -07001884 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001885 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001886 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001887 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001888 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001889 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001890 }
Grace Klobac9181842009-04-14 08:53:22 -07001891 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001892 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001893 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001894 }
1895 }
1896
1897 private class Copy implements OnMenuItemClickListener {
1898 private CharSequence mText;
1899
1900 public boolean onMenuItemClick(MenuItem item) {
1901 copy(mText);
1902 return true;
1903 }
1904
1905 public Copy(CharSequence toCopy) {
1906 mText = toCopy;
1907 }
1908 }
1909
1910 private class Download implements OnMenuItemClickListener {
1911 private String mText;
1912
1913 public boolean onMenuItemClick(MenuItem item) {
1914 onDownloadStartNoStream(mText, null, null, null, -1);
1915 return true;
1916 }
1917
1918 public Download(String toDownload) {
1919 mText = toDownload;
1920 }
1921 }
1922
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001923 private class SetAsWallpaper extends Thread implements
1924 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1925 private URL mUrl;
1926 private ProgressDialog mWallpaperProgress;
1927 private boolean mCanceled = false;
1928
1929 public SetAsWallpaper(String url) {
1930 try {
1931 mUrl = new URL(url);
1932 } catch (MalformedURLException e) {
1933 mUrl = null;
1934 }
1935 }
1936
1937 public void onCancel(DialogInterface dialog) {
1938 mCanceled = true;
1939 }
1940
1941 public boolean onMenuItemClick(MenuItem item) {
1942 if (mUrl != null) {
1943 // The user may have tried to set a image with a large file size as their
1944 // background so it may take a few moments to perform the operation. Display
1945 // a progress spinner while it is working.
1946 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1947 mWallpaperProgress.setIndeterminate(true);
1948 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1949 mWallpaperProgress.setCancelable(true);
1950 mWallpaperProgress.setOnCancelListener(this);
1951 mWallpaperProgress.show();
1952 start();
1953 }
1954 return true;
1955 }
1956
Michael Kolbe0a36662010-06-29 10:37:12 -07001957 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001958 public void run() {
1959 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1960 try {
1961 // TODO: This will cause the resource to be downloaded again, when we
1962 // should in most cases be able to grab it from the cache. To fix this
1963 // we should query WebCore to see if we can access a cached version and
1964 // instead open an input stream on that. This pattern could also be used
1965 // in the download manager where the same problem exists.
1966 InputStream inputstream = mUrl.openStream();
1967 if (inputstream != null) {
1968 setWallpaper(inputstream);
1969 }
1970 } catch (IOException e) {
1971 Log.e(LOGTAG, "Unable to set new wallpaper");
1972 // Act as though the user canceled the operation so we try to
1973 // restore the old wallpaper.
1974 mCanceled = true;
1975 }
1976
1977 if (mCanceled) {
1978 // Restore the old wallpaper if the user cancelled whilst we were setting
1979 // the new wallpaper.
1980 int width = oldWallpaper.getIntrinsicWidth();
1981 int height = oldWallpaper.getIntrinsicHeight();
1982 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1983 Canvas canvas = new Canvas(bm);
1984 oldWallpaper.setBounds(0, 0, width, height);
1985 oldWallpaper.draw(canvas);
1986 try {
1987 setWallpaper(bm);
1988 } catch (IOException e) {
1989 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1990 }
1991 mCanceled = false;
1992 }
1993
1994 if (mWallpaperProgress.isShowing()) {
1995 mWallpaperProgress.dismiss();
1996 }
1997 }
1998 }
1999
The Android Open Source Project0c908882009-03-03 19:32:16 -08002000 private void copy(CharSequence text) {
2001 try {
2002 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2003 if (clip != null) {
2004 clip.setClipboardText(text);
2005 }
2006 } catch (android.os.RemoteException e) {
2007 Log.e(LOGTAG, "Copy failed", e);
2008 }
2009 }
2010
2011 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002012 * Resets the browser title-view to whatever it must be
2013 * (for example, if we had a loading error)
2014 * When we have a new page, we call resetTitle, when we
2015 * have to reset the titlebar to whatever it used to be
2016 * (for example, if the user chose to stop loading), we
2017 * call resetTitleAndRevertLockIcon.
2018 */
2019 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002020 mTabControl.getCurrentTab().revertLockIcon();
2021 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002022 resetTitleIconAndProgress();
2023 }
2024
2025 /**
2026 * Reset the title, favicon, and progress.
2027 */
2028 private void resetTitleIconAndProgress() {
2029 WebView current = mTabControl.getCurrentWebView();
2030 if (current == null) {
2031 return;
2032 }
2033 resetTitleAndIcon(current);
2034 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002035 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002036 }
2037
2038 // Reset the title and the icon based on the given item.
2039 private void resetTitleAndIcon(WebView view) {
2040 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2041 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002042 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002043 setFavicon(item.getFavicon());
2044 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002045 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002046 setFavicon(null);
2047 }
2048 }
2049
2050 /**
2051 * Sets a title composed of the URL and the title string.
2052 * @param url The URL of the site being loaded.
2053 * @param title The title of the site being loaded.
2054 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002055 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002056 mUrl = url;
2057 mTitle = title;
2058
Leon Scroggins58d56c62010-01-28 15:12:40 -05002059 // If we are in voice search mode, the title has already been set.
2060 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2061 mTitleBar.setDisplayTitle(url);
Leon Scrogginsd746a942010-05-19 13:21:44 -04002062 if (!mXLargeScreenSize) {
2063 mFakeTitleBar.setDisplayTitle(url);
2064 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002065 }
2066
2067 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002068 * @param url The URL to build a title version of the URL from.
2069 * @return The title version of the URL or null if fails.
2070 * The title version of the URL can be either the URL hostname,
2071 * or the hostname with an "https://" prefix (for secure URLs),
2072 * or an empty string if, for example, the URL in question is a
2073 * file:// URL with no hostname.
2074 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002075 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002076 String titleUrl = null;
2077
2078 if (url != null) {
2079 try {
2080 // parse the url string
2081 URL urlObj = new URL(url);
2082 if (urlObj != null) {
2083 titleUrl = "";
2084
2085 String protocol = urlObj.getProtocol();
2086 String host = urlObj.getHost();
2087
2088 if (host != null && 0 < host.length()) {
2089 titleUrl = host;
2090 if (protocol != null) {
2091 // if a secure site, add an "https://" prefix!
2092 if (protocol.equalsIgnoreCase("https")) {
2093 titleUrl = protocol + "://" + host;
2094 }
2095 }
2096 }
2097 }
2098 } catch (MalformedURLException e) {}
2099 }
2100
2101 return titleUrl;
2102 }
2103
2104 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002105 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002106 mTitleBar.setFavicon(icon);
Leon Scrogginsd746a942010-05-19 13:21:44 -04002107 if (!mXLargeScreenSize) {
2108 mFakeTitleBar.setFavicon(icon);
2109 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002110 }
2111
2112 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002113 * Close the tab, remove its associated title bar, and adjust mTabControl's
2114 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002115 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002116 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002117 int currentIndex = mTabControl.getCurrentIndex();
2118 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002119 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002120 if (currentIndex >= removeIndex && currentIndex != 0) {
2121 currentIndex--;
2122 }
2123 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002124 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002125 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002126 }
2127
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002128 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002129 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002130 if (current == null) {
2131 /*
2132 * Instead of finishing the activity, simply push this to the back
2133 * of the stack and let ActivityManager to choose the foreground
2134 * activity. As BrowserActivity is singleTask, it will be always the
2135 * root of the task. So we can use either true or false for
2136 * moveTaskToBack().
2137 */
2138 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002139 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002140 }
2141 WebView w = current.getWebView();
2142 if (w.canGoBack()) {
2143 w.goBack();
2144 } else {
2145 // Check to see if we are closing a window that was created by
2146 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002147 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002148 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002149 switchToTab(mTabControl.getTabIndex(parent));
2150 // Now we close the other tab
2151 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002152 } else {
2153 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002154 // force the tab's inLoad() to be false as we are going to
2155 // either finish the activity or remove the tab. This will
2156 // ensure pauseWebViewTimers() taking action.
2157 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002158 if (mTabControl.getTabCount() == 1) {
2159 finish();
2160 return;
2161 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002162 // call pauseWebViewTimers() now, we won't be able to call
2163 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002164 // Temporarily change mActivityInPause to be true as
2165 // pauseWebViewTimers() will do nothing if mActivityInPause
2166 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002167 boolean savedState = mActivityInPause;
2168 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002169 Log.e(LOGTAG, "BrowserActivity is already paused "
2170 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002171 }
2172 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002173 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002174 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002175 removeTabFromContentView(current);
2176 mTabControl.removeTab(current);
2177 }
2178 /*
2179 * Instead of finishing the activity, simply push this to the back
2180 * of the stack and let ActivityManager to choose the foreground
2181 * activity. As BrowserActivity is singleTask, it will be always the
2182 * root of the task. So we can use either true or false for
2183 * moveTaskToBack().
2184 */
2185 moveTaskToBack(true);
2186 }
2187 }
2188 }
2189
Grace Kloba22ac16e2009-10-07 18:00:23 -07002190 boolean isMenuDown() {
2191 return mMenuIsDown;
2192 }
2193
Grace Kloba5942df02009-09-18 11:48:29 -07002194 @Override
2195 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002196 // Even if MENU is already held down, we need to call to super to open
2197 // the IME on long press.
2198 if (KeyEvent.KEYCODE_MENU == keyCode) {
2199 mMenuIsDown = true;
2200 return super.onKeyDown(keyCode, event);
2201 }
Grace Kloba5942df02009-09-18 11:48:29 -07002202 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2203 // still down, we don't want to trigger the search. Pretend to consume
2204 // the key and do nothing.
2205 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002206
Grace Kloba5942df02009-09-18 11:48:29 -07002207 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002208 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002209 // WebView/WebTextView handle the keys in the KeyDown. As
2210 // the Activity's shortcut keys are only handled when WebView
2211 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2212 if (event.isShiftPressed()) {
2213 getTopWindow().pageUp(false);
2214 } else {
2215 getTopWindow().pageDown(false);
2216 }
Grace Kloba5942df02009-09-18 11:48:29 -07002217 return true;
2218 case KeyEvent.KEYCODE_BACK:
2219 if (event.getRepeatCount() == 0) {
2220 event.startTracking();
2221 return true;
2222 } else if (mCustomView == null && mActiveTabsPage == null
2223 && event.isLongPress()) {
2224 bookmarksOrHistoryPicker(true);
2225 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002226 }
Grace Kloba5942df02009-09-18 11:48:29 -07002227 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002228 }
Grace Kloba5942df02009-09-18 11:48:29 -07002229 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002230 }
2231
Grace Kloba5942df02009-09-18 11:48:29 -07002232 @Override
2233 public boolean onKeyUp(int keyCode, KeyEvent event) {
2234 switch(keyCode) {
2235 case KeyEvent.KEYCODE_MENU:
2236 mMenuIsDown = false;
2237 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002238 case KeyEvent.KEYCODE_BACK:
2239 if (event.isTracking() && !event.isCanceled()) {
2240 if (mCustomView != null) {
2241 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002242 mTabControl.getCurrentWebView().getWebChromeClient()
2243 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002244 } else if (mActiveTabsPage != null) {
2245 // if tab page is showing, hide it
2246 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002247 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002248 WebView subwindow = mTabControl.getCurrentSubWindow();
2249 if (subwindow != null) {
2250 if (subwindow.canGoBack()) {
2251 subwindow.goBack();
2252 } else {
2253 dismissSubWindow(mTabControl.getCurrentTab());
2254 }
2255 } else {
2256 goBackOnePageOrQuit();
2257 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002258 }
Grace Kloba5942df02009-09-18 11:48:29 -07002259 return true;
2260 }
2261 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002262 }
Grace Kloba5942df02009-09-18 11:48:29 -07002263 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002264 }
2265
Leon Scroggins68579392009-09-15 15:31:54 -04002266 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002267 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002268 resetTitleAndRevertLockIcon();
2269 WebView w = getTopWindow();
2270 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002271 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2272 // same logic here. But for subwindow case, should we call into the main
2273 // WebView's onPageFinished as we never call its onPageStarted and if
2274 // the page finishes itself, we don't call onPageFinished.
2275 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2276 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002277
2278 cancelStopToast();
2279 mStopToast = Toast
2280 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2281 mStopToast.show();
2282 }
2283
Grace Kloba22ac16e2009-10-07 18:00:23 -07002284 boolean didUserStopLoading() {
2285 return mDidStopLoad;
2286 }
2287
The Android Open Source Project0c908882009-03-03 19:32:16 -08002288 private void cancelStopToast() {
2289 if (mStopToast != null) {
2290 mStopToast.cancel();
2291 mStopToast = null;
2292 }
2293 }
2294
Grace Kloba22ac16e2009-10-07 18:00:23 -07002295 // called by a UI or non-UI thread to post the message
2296 public void postMessage(int what, int arg1, int arg2, Object obj,
2297 long delayMillis) {
2298 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2299 obj), delayMillis);
2300 }
2301
2302 // called by a UI or non-UI thread to remove the message
2303 void removeMessages(int what, Object object) {
2304 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002305 }
2306
2307 // public message ids
2308 public final static int LOAD_URL = 1001;
2309 public final static int STOP_LOAD = 1002;
2310
2311 // Message Ids
2312 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002313 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002314
Grace Kloba22ac16e2009-10-07 18:00:23 -07002315 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002316
Ben Murdocheecb4e62010-07-06 16:30:38 +01002317 private static final int TOUCH_ICON_DOWNLOADED = 109;
2318
The Android Open Source Project0c908882009-03-03 19:32:16 -08002319 // Private handler for handling javascript and saving passwords
2320 private Handler mHandler = new Handler() {
2321
Michael Kolbe0a36662010-06-29 10:37:12 -07002322 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002323 public void handleMessage(Message msg) {
2324 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002325 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002326 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002327 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002328 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002329 if (url == null || url.length() == 0) {
2330 break;
2331 }
2332 HashMap focusNodeMap = (HashMap) msg.obj;
2333 WebView view = (WebView) focusNodeMap.get("webview");
2334 // Only apply the action if the top window did not change.
2335 if (getTopWindow() != view) {
2336 break;
2337 }
2338 switch (msg.arg1) {
2339 case R.id.open_context_menu_id:
2340 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002341 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002342 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002343 case R.id.bookmark_context_menu_id:
2344 Intent intent = new Intent(BrowserActivity.this,
2345 AddBookmarkPage.class);
2346 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002347 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002348 startActivity(intent);
2349 break;
2350 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002351 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002352 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002353 break;
2354 case R.id.copy_link_context_menu_id:
2355 copy(url);
2356 break;
2357 case R.id.save_link_context_menu_id:
2358 case R.id.download_context_menu_id:
2359 onDownloadStartNoStream(url, null, null, null, -1);
2360 break;
2361 }
2362 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002363 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002364
2365 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002366 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002367 break;
2368
2369 case STOP_LOAD:
2370 stopLoading();
2371 break;
2372
The Android Open Source Project0c908882009-03-03 19:32:16 -08002373 case RELEASE_WAKELOCK:
2374 if (mWakeLock.isHeld()) {
2375 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002376 // if we reach here, Browser should be still in the
2377 // background loading after WAKELOCK_TIMEOUT (5-min).
2378 // To avoid burning the battery, stop loading.
2379 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002380 }
2381 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002382
2383 case UPDATE_BOOKMARK_THUMBNAIL:
2384 WebView view = (WebView) msg.obj;
2385 if (view != null) {
2386 updateScreenshot(view);
2387 }
2388 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002389
2390 case TOUCH_ICON_DOWNLOADED:
2391 Bundle b = msg.getData();
2392 showSaveToHomescreenDialog(b.getString("url"),
2393 b.getString("title"),
2394 (Bitmap) b.getParcelable("touchIcon"),
2395 (Bitmap) b.getParcelable("favicon"));
2396 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002397 }
2398 }
2399 };
2400
Leon Scroggins96afcb12009-12-10 12:35:56 -05002401 /**
2402 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2403 * an {@link Intent} to launch the Activity chooser.
2404 * @param c Context used to launch a new Activity.
2405 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002406 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002407 * @param url URL of the page. Stored in the Intent with
2408 * {@link Intent#EXTRA_TEXT}
2409 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2410 * with {@link Browser#EXTRA_SHARE_FAVICON}
2411 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2412 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2413 */
2414 public static final void sharePage(Context c, String title, String url,
2415 Bitmap favicon, Bitmap screenshot) {
2416 Intent send = new Intent(Intent.ACTION_SEND);
2417 send.setType("text/plain");
2418 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002419 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002420 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2421 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2422 try {
2423 c.startActivity(Intent.createChooser(send, c.getString(
2424 R.string.choosertitle_sharevia)));
2425 } catch(android.content.ActivityNotFoundException ex) {
2426 // if no app handles it, do nothing
2427 }
2428 }
2429
Leon Scroggins89c6d362009-07-15 16:54:37 -04002430 private void updateScreenshot(WebView view) {
2431 // If this is a bookmarked site, add a screenshot to the database.
2432 // FIXME: When should we update? Every time?
2433 // FIXME: Would like to make sure there is actually something to
2434 // draw, but the API for that (WebViewCore.pictureReady()) is not
2435 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002436
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002437 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2438 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002439 if (bm == null) {
2440 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002441 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002442
2443 final ContentResolver cr = getContentResolver();
2444 final String url = view.getUrl();
2445 final String originalUrl = view.getOriginalUrl();
2446
2447 new AsyncTask<Void, Void, Void>() {
2448 @Override
2449 protected Void doInBackground(Void... unused) {
2450 Cursor c = null;
2451 try {
2452 c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2453 cr, originalUrl, url, true);
2454 if (c != null) {
2455 if (c.moveToFirst()) {
2456 ContentValues values = new ContentValues();
2457 final ByteArrayOutputStream os
2458 = new ByteArrayOutputStream();
2459 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2460 values.put(Browser.BookmarkColumns.THUMBNAIL,
2461 os.toByteArray());
2462 do {
2463 cr.update(ContentUris.withAppendedId(
2464 Browser.BOOKMARKS_URI, c.getInt(0)),
2465 values, null, null);
2466 } while (c.moveToNext());
2467 }
2468 }
2469 } catch (IllegalStateException e) {
2470 // Ignore
2471 } finally {
2472 if (c != null) c.close();
2473 }
2474 return null;
2475 }
2476 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002477 }
2478
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002479 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002480 * Values for the size of the thumbnail created when taking a screenshot.
2481 * Lazily initialized. Instead of using these directly, use
2482 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002483 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002484 private static int THUMBNAIL_WIDTH = 0;
2485 private static int THUMBNAIL_HEIGHT = 0;
2486
2487 /**
2488 * Return the desired width for thumbnail screenshots, which are stored in
2489 * the database, and used on the bookmarks screen.
2490 * @param context Context for finding out the density of the screen.
2491 * @return int desired width for thumbnail screenshot.
2492 */
2493 /* package */ static int getDesiredThumbnailWidth(Context context) {
2494 if (THUMBNAIL_WIDTH == 0) {
2495 float density = context.getResources().getDisplayMetrics().density;
2496 THUMBNAIL_WIDTH = (int) (90 * density);
2497 THUMBNAIL_HEIGHT = (int) (80 * density);
2498 }
2499 return THUMBNAIL_WIDTH;
2500 }
2501
2502 /**
2503 * Return the desired height for thumbnail screenshots, which are stored in
2504 * the database, and used on the bookmarks screen.
2505 * @param context Context for finding out the density of the screen.
2506 * @return int desired height for thumbnail screenshot.
2507 */
2508 /* package */ static int getDesiredThumbnailHeight(Context context) {
2509 // To ensure that they are both initialized.
2510 getDesiredThumbnailWidth(context);
2511 return THUMBNAIL_HEIGHT;
2512 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002513
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002514 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002515 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002516 if (thumbnail == null) {
2517 return null;
2518 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002519 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002520 Canvas canvas = new Canvas(bm);
2521 // May need to tweak these values to determine what is the
2522 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002523 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002524 int thumbnailHeight = thumbnail.getHeight();
2525 float scaleFactorX = 1.0f;
2526 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002527 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002528 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002529 } else {
2530 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002531 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002532
2533 if (view.getWidth() > view.getHeight() &&
2534 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2535 // If the device is in landscape and the page is shorter
2536 // than the height of the view, stretch the thumbnail to fill the
2537 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002538 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002539 } else {
2540 // In the portrait case, this looks nice.
2541 scaleFactorY = scaleFactorX;
2542 }
2543
2544 canvas.scale(scaleFactorX, scaleFactorY);
2545
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002546 thumbnail.draw(canvas);
2547 return bm;
2548 }
2549
The Android Open Source Project0c908882009-03-03 19:32:16 -08002550 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002551 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002552 //-------------------------------------------------------------------------
2553
2554 // Use in overrideUrlLoading
2555 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2556 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2557 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2558 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2559
Leon Scroggins92472e82010-02-17 16:32:28 -05002560 // Keep this initial progress in sync with initialProgressValue (* 100)
2561 // in ProgressTracker.cpp
2562 private final static int INITIAL_PROGRESS = 10;
2563
Grace Kloba22ac16e2009-10-07 18:00:23 -07002564 void onPageStarted(WebView view, String url, Bitmap favicon) {
2565 // when BrowserActivity just starts, onPageStarted may be called before
2566 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2567 // to start the timer. As we won't switch tabs while an activity is in
2568 // pause state, we can ensure calling resume and pause in pair.
2569 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002570
Grace Kloba22ac16e2009-10-07 18:00:23 -07002571 resetLockIcon(url);
2572 setUrlTitle(url, null);
2573 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002574 // Show some progress so that the user knows the page is beginning to
2575 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002576 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002577 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002578 if (!mIsNetworkUp) createAndShowNetworkDialog();
Cary Clark01cfcdd2010-06-04 16:36:45 -04002579 closeDialogs();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002580 if (mSettings.isTracing()) {
2581 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002582 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002583 WebAddress uri = new WebAddress(url);
2584 host = uri.mHost;
2585 } catch (android.net.ParseException ex) {
2586 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002587 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002588 host = host.replace('.', '_');
2589 host += ".trace";
2590 mInTrace = true;
2591 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2592 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002593
Grace Kloba22ac16e2009-10-07 18:00:23 -07002594 // Performance probe
2595 if (false) {
2596 mStart = SystemClock.uptimeMillis();
2597 mProcessStart = Process.getElapsedCpuTime();
2598 long[] sysCpu = new long[7];
2599 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2600 sysCpu, null)) {
2601 mUserStart = sysCpu[0] + sysCpu[1];
2602 mSystemStart = sysCpu[2];
2603 mIdleStart = sysCpu[3];
2604 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2605 }
2606 mUiStart = SystemClock.currentThreadTimeMillis();
2607 }
2608 }
2609
2610 void onPageFinished(WebView view, String url) {
2611 // Reset the title and icon in case we stopped a provisional load.
2612 resetTitleAndIcon(view);
2613 // Update the lock icon image only once we are done loading
2614 updateLockIconToLatest();
2615 // pause the WebView timer and release the wake lock if it is finished
2616 // while BrowserActivity is in pause state.
2617 if (mActivityInPause && pauseWebViewTimers()) {
2618 if (mWakeLock.isHeld()) {
2619 mHandler.removeMessages(RELEASE_WAKELOCK);
2620 mWakeLock.release();
2621 }
2622 }
2623
2624 // Performance probe
2625 if (false) {
2626 long[] sysCpu = new long[7];
2627 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2628 sysCpu, null)) {
2629 String uiInfo = "UI thread used "
2630 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2631 + " ms";
2632 if (LOGD_ENABLED) {
2633 Log.d(LOGTAG, uiInfo);
2634 }
2635 //The string that gets written to the log
2636 String performanceString = "It took total "
2637 + (SystemClock.uptimeMillis() - mStart)
2638 + " ms clock time to load the page."
2639 + "\nbrowser process used "
2640 + (Process.getElapsedCpuTime() - mProcessStart)
2641 + " ms, user processes used "
2642 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2643 + " ms, kernel used "
2644 + (sysCpu[2] - mSystemStart) * 10
2645 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2646 + " ms and irq took "
2647 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2648 * 10 + " ms, " + uiInfo;
2649 if (LOGD_ENABLED) {
2650 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2651 }
2652 if (url != null) {
2653 // strip the url to maintain consistency
2654 String newUrl = new String(url);
2655 if (newUrl.startsWith("http://www.")) {
2656 newUrl = newUrl.substring(11);
2657 } else if (newUrl.startsWith("http://")) {
2658 newUrl = newUrl.substring(7);
2659 } else if (newUrl.startsWith("https://www.")) {
2660 newUrl = newUrl.substring(12);
2661 } else if (newUrl.startsWith("https://")) {
2662 newUrl = newUrl.substring(8);
2663 }
2664 if (LOGD_ENABLED) {
2665 Log.d(LOGTAG, newUrl + " loaded");
2666 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002667 }
2668 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002669 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002670
Grace Kloba22ac16e2009-10-07 18:00:23 -07002671 if (mInTrace) {
2672 mInTrace = false;
2673 Debug.stopMethodTracing();
2674 }
2675 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002676
Grace Klobae7fe26b2010-06-28 16:23:33 -07002677 private void closeEmptyChildTab() {
2678 Tab current = mTabControl.getCurrentTab();
2679 if (current != null
2680 && current.getWebView().copyBackForwardList().getSize() == 0) {
2681 Tab parent = current.getParentTab();
2682 if (parent != null) {
2683 switchToTab(mTabControl.getTabIndex(parent));
2684 closeTab(current);
2685 }
2686 }
2687 }
2688
Grace Kloba22ac16e2009-10-07 18:00:23 -07002689 boolean shouldOverrideUrlLoading(WebView view, String url) {
2690 if (url.startsWith(SCHEME_WTAI)) {
2691 // wtai://wp/mc;number
2692 // number=string(phone-number)
2693 if (url.startsWith(SCHEME_WTAI_MC)) {
2694 Intent intent = new Intent(Intent.ACTION_VIEW,
2695 Uri.parse(WebView.SCHEME_TEL +
2696 url.substring(SCHEME_WTAI_MC.length())));
2697 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002698 // before leaving BrowserActivity, close the empty child tab.
2699 // If a new tab is created through JavaScript open to load this
2700 // url, we would like to close it as we will load this url in a
2701 // different Activity.
2702 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002703 return true;
2704 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002705 // wtai://wp/sd;dtmf
2706 // dtmf=string(dialstring)
2707 if (url.startsWith(SCHEME_WTAI_SD)) {
2708 // TODO: only send when there is active voice connection
2709 return false;
2710 }
2711 // wtai://wp/ap;number;name
2712 // number=string(phone-number)
2713 // name=string
2714 if (url.startsWith(SCHEME_WTAI_AP)) {
2715 // TODO
2716 return false;
2717 }
2718 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002719
Grace Kloba22ac16e2009-10-07 18:00:23 -07002720 // The "about:" schemes are internal to the browser; don't want these to
2721 // be dispatched to other apps.
2722 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002723 return false;
2724 }
2725
Grace Kloba22ac16e2009-10-07 18:00:23 -07002726 Intent intent;
2727 // perform generic parsing of the URI to turn it into an Intent.
2728 try {
2729 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2730 } catch (URISyntaxException ex) {
2731 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2732 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002733 }
2734
Grace Kloba22ac16e2009-10-07 18:00:23 -07002735 // check whether the intent can be resolved. If not, we will see
2736 // whether we can download it from the Market.
2737 if (getPackageManager().resolveActivity(intent, 0) == null) {
2738 String packagename = intent.getPackage();
2739 if (packagename != null) {
2740 intent = new Intent(Intent.ACTION_VIEW, Uri
2741 .parse("market://search?q=pname:" + packagename));
2742 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2743 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002744 // before leaving BrowserActivity, close the empty child tab.
2745 // If a new tab is created through JavaScript open to load this
2746 // url, we would like to close it as we will load this url in a
2747 // different Activity.
2748 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002749 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002750 } else {
2751 return false;
2752 }
2753 }
2754
Grace Kloba22ac16e2009-10-07 18:00:23 -07002755 // sanitize the Intent, ensuring web pages can not bypass browser
2756 // security (only access to BROWSABLE activities).
2757 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2758 intent.setComponent(null);
2759 try {
2760 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002761 // before leaving BrowserActivity, close the empty child tab.
2762 // If a new tab is created through JavaScript open to load this
2763 // url, we would like to close it as we will load this url in a
2764 // different Activity.
2765 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002766 return true;
2767 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002768 } catch (ActivityNotFoundException ex) {
2769 // ignore the error. If no application can handle the URL,
2770 // eg about:blank, assume the browser can handle it.
2771 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002772
Grace Kloba22ac16e2009-10-07 18:00:23 -07002773 if (mMenuIsDown) {
2774 openTab(url);
2775 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002776 return true;
2777 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002778 return false;
2779 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002780
Grace Kloba22ac16e2009-10-07 18:00:23 -07002781 // -------------------------------------------------------------------------
2782 // Helper function for WebChromeClient
2783 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002784
Grace Kloba22ac16e2009-10-07 18:00:23 -07002785 void onProgressChanged(WebView view, int newProgress) {
Leon Scrogginsd746a942010-05-19 13:21:44 -04002786 if (mXLargeScreenSize) {
2787 mTitleBar.setProgress(newProgress);
2788 } else {
2789 // On the phone, the fake title bar will always cover up the
2790 // regular title bar (or the regular one is offscreen), so only the
2791 // fake title bar needs to change its progress
2792 mFakeTitleBar.setProgress(newProgress);
2793 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002794
Grace Kloba22ac16e2009-10-07 18:00:23 -07002795 if (newProgress == 100) {
2796 // onProgressChanged() may continue to be called after the main
2797 // frame has finished loading, as any remaining sub frames continue
2798 // to load. We'll only get called once though with newProgress as
2799 // 100 when everything is loaded. (onPageFinished is called once
2800 // when the main frame completes loading regardless of the state of
2801 // any sub frames so calls to onProgressChanges may continue after
2802 // onPageFinished has executed)
2803 if (mInLoad) {
2804 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002805 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002806 // If the options menu is open, leave the title bar
2807 if (!mOptionsMenuOpen || !mIconView) {
2808 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002809 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002810 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002811 } else {
2812 if (!mInLoad) {
2813 // onPageFinished may have already been called but a subframe is
2814 // still loading and updating the progress. Reset mInLoad and
2815 // update the menu items.
2816 mInLoad = true;
2817 updateInLoadMenuItems();
2818 }
2819 // When the page first begins to load, the Activity may still be
2820 // paused, in which case showFakeTitleBar will do nothing. Call
2821 // again as the page continues to load so that it will be shown.
2822 // (Calling it will the fake title bar is already showing will also
2823 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002824 if (!mOptionsMenuOpen || mIconView) {
2825 // This page has begun to load, so show the title bar
2826 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002827 }
2828 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002829 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002830
Grace Kloba22ac16e2009-10-07 18:00:23 -07002831 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002832 // if a view already exists then immediately terminate the new one
2833 if (mCustomView != null) {
2834 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002835 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002836 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002837
2838 // Add the custom view to its container.
2839 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2840 mCustomView = view;
2841 mCustomViewCallback = callback;
2842 // Save the menu state and set it to empty while the custom
2843 // view is showing.
2844 mOldMenuState = mMenuState;
2845 mMenuState = EMPTY_MENU;
2846 // Hide the content view.
2847 mContentView.setVisibility(View.GONE);
2848 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002849 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002850 mCustomViewContainer.setVisibility(View.VISIBLE);
2851 mCustomViewContainer.bringToFront();
2852 }
2853
2854 void onHideCustomView() {
2855 if (mCustomView == null)
2856 return;
2857
2858 // Hide the custom view.
2859 mCustomView.setVisibility(View.GONE);
2860 // Remove the custom view from its container.
2861 mCustomViewContainer.removeView(mCustomView);
2862 mCustomView = null;
2863 // Reset the old menu state.
2864 mMenuState = mOldMenuState;
2865 mOldMenuState = EMPTY_MENU;
2866 mCustomViewContainer.setVisibility(View.GONE);
2867 mCustomViewCallback.onCustomViewHidden();
2868 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002869 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002870 mContentView.setVisibility(View.VISIBLE);
2871 }
2872
2873 Bitmap getDefaultVideoPoster() {
2874 if (mDefaultVideoPoster == null) {
2875 mDefaultVideoPoster = BitmapFactory.decodeResource(
2876 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002877 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002878 return mDefaultVideoPoster;
2879 }
Patrick Scott3918d442009-08-04 13:22:29 -04002880
Grace Kloba22ac16e2009-10-07 18:00:23 -07002881 View getVideoLoadingProgressView() {
2882 if (mVideoProgressView == null) {
2883 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2884 mVideoProgressView = inflater.inflate(
2885 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002886 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002887 return mVideoProgressView;
2888 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002889
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002890 /*
2891 * The Object used to inform the WebView of the file to upload.
2892 */
2893 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002894 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002895
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002896 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2897
2898 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002899 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01002900 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01002901 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002902 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01002903 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002904 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01002905 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002906
Ben Murdoch039bd472010-07-21 21:26:57 +01002907 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002908 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002909
Ben Murdoch6af492a2010-06-15 12:38:17 +01002910 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002911 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01002912 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
2913 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002914
Ben Murdoch6af492a2010-06-15 12:38:17 +01002915 if (mUploadMessage != null) {
2916 // Already a file picker operation in progress.
2917 return;
2918 }
2919
Grace Kloba22ac16e2009-10-07 18:00:23 -07002920 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002921
2922 // Parse the accept type.
2923 String params[] = acceptType.split(";");
2924 String mimeType = params[0];
2925
2926 for (String p : params) {
2927 String[] keyValue = p.split("=");
2928 if (keyValue.length == 2) {
2929 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002930 if (mediaSourceKey.equals(keyValue[0])) {
2931 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002932 }
2933 }
2934 }
2935
2936 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002937 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2938 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002939
2940 // Create an intent to add to the standard file picker that will
2941 // capture an image from the camera. We'll combine this intent with
2942 // the standard OPENABLE picker unless the web developer specifically
2943 // requested the camera or gallery be opened by passing a parameter
2944 // in the accept type.
2945 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
2946 File externalDataDir = Environment.getExternalStoragePublicDirectory(
2947 Environment.DIRECTORY_DCIM);
2948 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
2949 File.separator + "browser-photos");
2950 cameraDataDir.mkdirs();
2951 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
2952 System.currentTimeMillis() + ".jpg";
2953 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
2954
Ben Murdoch6af492a2010-06-15 12:38:17 +01002955 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
2956
Ben Murdoch039bd472010-07-21 21:26:57 +01002957 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
2958
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002959 if (mimeType.equals(imageMimeType)) {
2960 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01002961 addCamcorderIntent = false;
2962 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002963 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
2964 // directly.
2965 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
2966 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01002967 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
2968 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002969 addCameraIntent = false;
2970 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01002971 } else if (mimeType.equals(videoMimeType)) {
2972 i.setType(videoMimeType);
2973 addCameraIntent = false;
2974 // The camcorder saves it's own file and returns it to us in the intent, so
2975 // we don't need to generate one here.
2976 mCameraFilePath = null;
2977
2978 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01002979 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
2980 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002981 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
2982 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01002983 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
2984 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002985 addCamcorderIntent = false;
2986 }
Ben Murdoch039bd472010-07-21 21:26:57 +01002987 } else if (mimeType.equals(audioMimeType)) {
2988 i.setType(audioMimeType);
2989 addCameraIntent = false;
2990 addCamcorderIntent = false;
2991 if (mediaSource.equals(mediaSourceValueMicrophone)) {
2992 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
2993 // recorder.
2994 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
2995 return;
2996 }
2997 // On a default system, there is no single option to open an audio "gallery". Both the
2998 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
2999 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3000 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003001 } else {
3002 i.setType("*/*");
3003 }
3004
Ben Murdoch6af492a2010-06-15 12:38:17 +01003005 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003006 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3007 chooser.putExtra(Intent.EXTRA_INTENT, i);
3008
Ben Murdoch6af492a2010-06-15 12:38:17 +01003009 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3010
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003011 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003012 extraInitialIntents.add(cameraIntent);
3013 }
3014
3015 if (addCamcorderIntent) {
3016 extraInitialIntents.add(camcorderIntent);
3017 }
3018
3019 if (extraInitialIntents.size() > 0) {
3020 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3021 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003022 }
3023
3024 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3025 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003026 }
3027
3028 // -------------------------------------------------------------------------
3029 // Implement functions for DownloadListener
3030 // -------------------------------------------------------------------------
3031
The Android Open Source Project0c908882009-03-03 19:32:16 -08003032 /**
3033 * Notify the host application a download should be done, or that
3034 * the data should be streamed if a streaming viewer is available.
3035 * @param url The full url to the content that should be downloaded
3036 * @param contentDisposition Content-disposition http header, if
3037 * present.
3038 * @param mimetype The mimetype of the content reported by the server
3039 * @param contentLength The file size reported by the server
3040 */
3041 public void onDownloadStart(String url, String userAgent,
3042 String contentDisposition, String mimetype, long contentLength) {
3043 // if we're dealing wih A/V content that's not explicitly marked
3044 // for download, check if it's streamable.
3045 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003046 || !contentDisposition.regionMatches(
3047 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003048 // query the package manager to see if there's a registered handler
3049 // that matches.
3050 Intent intent = new Intent(Intent.ACTION_VIEW);
3051 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003052 ResolveInfo info = getPackageManager().resolveActivity(intent,
3053 PackageManager.MATCH_DEFAULT_ONLY);
3054 if (info != null) {
3055 ComponentName myName = getComponentName();
3056 // If we resolved to ourselves, we don't want to attempt to
3057 // load the url only to try and download it again.
3058 if (!myName.getPackageName().equals(
3059 info.activityInfo.packageName)
3060 || !myName.getClassName().equals(
3061 info.activityInfo.name)) {
3062 // someone (other than us) knows how to handle this mime
3063 // type with this scheme, don't download.
3064 try {
3065 startActivity(intent);
3066 return;
3067 } catch (ActivityNotFoundException ex) {
3068 if (LOGD_ENABLED) {
3069 Log.d(LOGTAG, "activity not found for " + mimetype
3070 + " over " + Uri.parse(url).getScheme(),
3071 ex);
3072 }
3073 // Best behavior is to fall back to a download in this
3074 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003075 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003076 }
3077 }
3078 }
3079 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3080 }
3081
Kristian Monsenfa52d172010-03-25 18:29:21 +00003082 // This is to work around the fact that java.net.URI throws Exceptions
3083 // instead of just encoding URL's properly
3084 // Helper method for onDownloadStartNoStream
3085 private static String encodePath(String path) {
3086 char[] chars = path.toCharArray();
3087
3088 boolean needed = false;
3089 for (char c : chars) {
3090 if (c == '[' || c == ']') {
3091 needed = true;
3092 break;
3093 }
3094 }
3095 if (needed == false) {
3096 return path;
3097 }
3098
3099 StringBuilder sb = new StringBuilder("");
3100 for (char c : chars) {
3101 if (c == '[' || c == ']') {
3102 sb.append('%');
3103 sb.append(Integer.toHexString(c));
3104 } else {
3105 sb.append(c);
3106 }
3107 }
3108
3109 return sb.toString();
3110 }
3111
The Android Open Source Project0c908882009-03-03 19:32:16 -08003112 /**
3113 * Notify the host application a download should be done, even if there
3114 * is a streaming viewer available for thise type.
3115 * @param url The full url to the content that should be downloaded
3116 * @param contentDisposition Content-disposition http header, if
3117 * present.
3118 * @param mimetype The mimetype of the content reported by the server
3119 * @param contentLength The file size reported by the server
3120 */
3121 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3122 String contentDisposition, String mimetype, long contentLength) {
3123
3124 String filename = URLUtil.guessFileName(url,
3125 contentDisposition, mimetype);
3126
3127 // Check to see if we have an SDCard
3128 String status = Environment.getExternalStorageState();
3129 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3130 int title;
3131 String msg;
3132
3133 // Check to see if the SDCard is busy, same as the music app
3134 if (status.equals(Environment.MEDIA_SHARED)) {
3135 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3136 title = R.string.download_sdcard_busy_dlg_title;
3137 } else {
3138 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3139 title = R.string.download_no_sdcard_dlg_title;
3140 }
3141
3142 new AlertDialog.Builder(this)
3143 .setTitle(title)
3144 .setIcon(android.R.drawable.ic_dialog_alert)
3145 .setMessage(msg)
3146 .setPositiveButton(R.string.ok, null)
3147 .show();
3148 return;
3149 }
3150
Kristian Monsenfa52d172010-03-25 18:29:21 +00003151 // java.net.URI is a lot stricter than KURL so we have to encode some
3152 // extra characters. Fix for b 2538060 and b 1634719
3153 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003154 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003155 webAddress = new WebAddress(url);
3156 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003157 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003158 // This only happens for very bad urls, we want to chatch the
3159 // exception here
3160 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003161 return;
3162 }
3163
3164 // XXX: Have to use the old url since the cookies were stored using the
3165 // old percent-encoded url.
3166 String cookies = CookieManager.getInstance().getCookie(url);
3167
3168 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003169 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003170 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3171 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3172 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003173 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003174 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003175 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003176 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3177 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3178 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3179 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003180 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003181 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003182 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003183 }
3184 if (mimetype == null) {
3185 // We must have long pressed on a link or image to download it. We
3186 // are not sure of the mimetype in this case, so do a head request
3187 new FetchUrlMimeType(this).execute(values);
3188 } else {
3189 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003190 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003191 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003192 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3193 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003194 }
3195
Grace Kloba22ac16e2009-10-07 18:00:23 -07003196 // -------------------------------------------------------------------------
3197
The Android Open Source Project0c908882009-03-03 19:32:16 -08003198 /**
3199 * Resets the lock icon. This method is called when we start a new load and
3200 * know the url to be loaded.
3201 */
3202 private void resetLockIcon(String url) {
3203 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003204 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003205 updateLockIconImage(LOCK_ICON_UNSECURE);
3206 }
3207
The Android Open Source Project0c908882009-03-03 19:32:16 -08003208 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003209 * Update the lock icon to correspond to our latest state.
3210 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003211 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003212 Tab t = mTabControl.getCurrentTab();
3213 if (t != null) {
3214 updateLockIconImage(t.getLockIconType());
3215 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003216 }
3217
3218 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003219 * Updates the lock-icon image in the title-bar.
3220 */
3221 private void updateLockIconImage(int lockIconType) {
3222 Drawable d = null;
3223 if (lockIconType == LOCK_ICON_SECURE) {
3224 d = mSecLockIcon;
3225 } else if (lockIconType == LOCK_ICON_MIXED) {
3226 d = mMixLockIcon;
3227 }
Leon Scroggins68579392009-09-15 15:31:54 -04003228 mTitleBar.setLock(d);
Leon Scrogginsd746a942010-05-19 13:21:44 -04003229 if (!mXLargeScreenSize) {
3230 mFakeTitleBar.setLock(d);
3231 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003232 }
3233
3234 /**
3235 * Displays a page-info dialog.
3236 * @param tab The tab to show info about
3237 * @param fromShowSSLCertificateOnError The flag that indicates whether
3238 * this dialog was opened from the SSL-certificate-on-error dialog or
3239 * not. This is important, since we need to know whether to return to
3240 * the parent dialog or simply dismiss.
3241 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003242 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003243 final boolean fromShowSSLCertificateOnError) {
3244 final LayoutInflater factory = LayoutInflater
3245 .from(this);
3246
3247 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3248
3249 final WebView view = tab.getWebView();
3250
3251 String url = null;
3252 String title = null;
3253
3254 if (view == null) {
3255 url = tab.getUrl();
3256 title = tab.getTitle();
3257 } else if (view == mTabControl.getCurrentWebView()) {
3258 // Use the cached title and url if this is the current WebView
3259 url = mUrl;
3260 title = mTitle;
3261 } else {
3262 url = view.getUrl();
3263 title = view.getTitle();
3264 }
3265
3266 if (url == null) {
3267 url = "";
3268 }
3269 if (title == null) {
3270 title = "";
3271 }
3272
3273 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3274 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3275
3276 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003277 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003278
3279 AlertDialog.Builder alertDialogBuilder =
3280 new AlertDialog.Builder(this)
3281 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3282 .setView(pageInfoView)
3283 .setPositiveButton(
3284 R.string.ok,
3285 new DialogInterface.OnClickListener() {
3286 public void onClick(DialogInterface dialog,
3287 int whichButton) {
3288 mPageInfoDialog = null;
3289 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003290
3291 // if we came here from the SSL error dialog
3292 if (fromShowSSLCertificateOnError) {
3293 // go back to the SSL error dialog
3294 showSSLCertificateOnError(
3295 mSSLCertificateOnErrorView,
3296 mSSLCertificateOnErrorHandler,
3297 mSSLCertificateOnErrorError);
3298 }
3299 }
3300 })
3301 .setOnCancelListener(
3302 new DialogInterface.OnCancelListener() {
3303 public void onCancel(DialogInterface dialog) {
3304 mPageInfoDialog = null;
3305 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003306
3307 // if we came here from the SSL error dialog
3308 if (fromShowSSLCertificateOnError) {
3309 // go back to the SSL error dialog
3310 showSSLCertificateOnError(
3311 mSSLCertificateOnErrorView,
3312 mSSLCertificateOnErrorHandler,
3313 mSSLCertificateOnErrorError);
3314 }
3315 }
3316 });
3317
3318 // if we have a main top-level page SSL certificate set or a certificate
3319 // error
3320 if (fromShowSSLCertificateOnError ||
3321 (view != null && view.getCertificate() != null)) {
3322 // add a 'View Certificate' button
3323 alertDialogBuilder.setNeutralButton(
3324 R.string.view_certificate,
3325 new DialogInterface.OnClickListener() {
3326 public void onClick(DialogInterface dialog,
3327 int whichButton) {
3328 mPageInfoDialog = null;
3329 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003330
3331 // if we came here from the SSL error dialog
3332 if (fromShowSSLCertificateOnError) {
3333 // go back to the SSL error dialog
3334 showSSLCertificateOnError(
3335 mSSLCertificateOnErrorView,
3336 mSSLCertificateOnErrorHandler,
3337 mSSLCertificateOnErrorError);
3338 } else {
3339 // otherwise, display the top-most certificate from
3340 // the chain
3341 if (view.getCertificate() != null) {
3342 showSSLCertificate(tab);
3343 }
3344 }
3345 }
3346 });
3347 }
3348
3349 mPageInfoDialog = alertDialogBuilder.show();
3350 }
3351
3352 /**
3353 * Displays the main top-level page SSL certificate dialog
3354 * (accessible from the Page-Info dialog).
3355 * @param tab The tab to show certificate for.
3356 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003357 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003358 final View certificateView =
3359 inflateCertificateView(tab.getWebView().getCertificate());
3360 if (certificateView == null) {
3361 return;
3362 }
3363
3364 LayoutInflater factory = LayoutInflater.from(this);
3365
3366 final LinearLayout placeholder =
3367 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3368
3369 LinearLayout ll = (LinearLayout) factory.inflate(
3370 R.layout.ssl_success, placeholder);
3371 ((TextView)ll.findViewById(R.id.success))
3372 .setText(R.string.ssl_certificate_is_valid);
3373
3374 mSSLCertificateView = tab;
3375 mSSLCertificateDialog =
3376 new AlertDialog.Builder(this)
3377 .setTitle(R.string.ssl_certificate).setIcon(
3378 R.drawable.ic_dialog_browser_certificate_secure)
3379 .setView(certificateView)
3380 .setPositiveButton(R.string.ok,
3381 new DialogInterface.OnClickListener() {
3382 public void onClick(DialogInterface dialog,
3383 int whichButton) {
3384 mSSLCertificateDialog = null;
3385 mSSLCertificateView = null;
3386
3387 showPageInfo(tab, false);
3388 }
3389 })
3390 .setOnCancelListener(
3391 new DialogInterface.OnCancelListener() {
3392 public void onCancel(DialogInterface dialog) {
3393 mSSLCertificateDialog = null;
3394 mSSLCertificateView = null;
3395
3396 showPageInfo(tab, false);
3397 }
3398 })
3399 .show();
3400 }
3401
3402 /**
3403 * Displays the SSL error certificate dialog.
3404 * @param view The target web-view.
3405 * @param handler The SSL error handler responsible for cancelling the
3406 * connection that resulted in an SSL error or proceeding per user request.
3407 * @param error The SSL error object.
3408 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003409 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003410 final WebView view, final SslErrorHandler handler, final SslError error) {
3411
3412 final View certificateView =
3413 inflateCertificateView(error.getCertificate());
3414 if (certificateView == null) {
3415 return;
3416 }
3417
3418 LayoutInflater factory = LayoutInflater.from(this);
3419
3420 final LinearLayout placeholder =
3421 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3422
3423 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3424 LinearLayout ll = (LinearLayout)factory
3425 .inflate(R.layout.ssl_warning, placeholder);
3426 ((TextView)ll.findViewById(R.id.warning))
3427 .setText(R.string.ssl_untrusted);
3428 }
3429
3430 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3431 LinearLayout ll = (LinearLayout)factory
3432 .inflate(R.layout.ssl_warning, placeholder);
3433 ((TextView)ll.findViewById(R.id.warning))
3434 .setText(R.string.ssl_mismatch);
3435 }
3436
3437 if (error.hasError(SslError.SSL_EXPIRED)) {
3438 LinearLayout ll = (LinearLayout)factory
3439 .inflate(R.layout.ssl_warning, placeholder);
3440 ((TextView)ll.findViewById(R.id.warning))
3441 .setText(R.string.ssl_expired);
3442 }
3443
3444 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3445 LinearLayout ll = (LinearLayout)factory
3446 .inflate(R.layout.ssl_warning, placeholder);
3447 ((TextView)ll.findViewById(R.id.warning))
3448 .setText(R.string.ssl_not_yet_valid);
3449 }
3450
3451 mSSLCertificateOnErrorHandler = handler;
3452 mSSLCertificateOnErrorView = view;
3453 mSSLCertificateOnErrorError = error;
3454 mSSLCertificateOnErrorDialog =
3455 new AlertDialog.Builder(this)
3456 .setTitle(R.string.ssl_certificate).setIcon(
3457 R.drawable.ic_dialog_browser_certificate_partially_secure)
3458 .setView(certificateView)
3459 .setPositiveButton(R.string.ok,
3460 new DialogInterface.OnClickListener() {
3461 public void onClick(DialogInterface dialog,
3462 int whichButton) {
3463 mSSLCertificateOnErrorDialog = null;
3464 mSSLCertificateOnErrorView = null;
3465 mSSLCertificateOnErrorHandler = null;
3466 mSSLCertificateOnErrorError = null;
3467
Grace Kloba22ac16e2009-10-07 18:00:23 -07003468 view.getWebViewClient().onReceivedSslError(
3469 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003470 }
3471 })
3472 .setNeutralButton(R.string.page_info_view,
3473 new DialogInterface.OnClickListener() {
3474 public void onClick(DialogInterface dialog,
3475 int whichButton) {
3476 mSSLCertificateOnErrorDialog = null;
3477
3478 // do not clear the dialog state: we will
3479 // need to show the dialog again once the
3480 // user is done exploring the page-info details
3481
3482 showPageInfo(mTabControl.getTabFromView(view),
3483 true);
3484 }
3485 })
3486 .setOnCancelListener(
3487 new DialogInterface.OnCancelListener() {
3488 public void onCancel(DialogInterface dialog) {
3489 mSSLCertificateOnErrorDialog = null;
3490 mSSLCertificateOnErrorView = null;
3491 mSSLCertificateOnErrorHandler = null;
3492 mSSLCertificateOnErrorError = null;
3493
Grace Kloba22ac16e2009-10-07 18:00:23 -07003494 view.getWebViewClient().onReceivedSslError(
3495 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003496 }
3497 })
3498 .show();
3499 }
3500
3501 /**
3502 * Inflates the SSL certificate view (helper method).
3503 * @param certificate The SSL certificate.
3504 * @return The resultant certificate view with issued-to, issued-by,
3505 * issued-on, expires-on, and possibly other fields set.
3506 * If the input certificate is null, returns null.
3507 */
3508 private View inflateCertificateView(SslCertificate certificate) {
3509 if (certificate == null) {
3510 return null;
3511 }
3512
3513 LayoutInflater factory = LayoutInflater.from(this);
3514
3515 View certificateView = factory.inflate(
3516 R.layout.ssl_certificate, null);
3517
3518 // issued to:
3519 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3520 if (issuedTo != null) {
3521 ((TextView) certificateView.findViewById(R.id.to_common))
3522 .setText(issuedTo.getCName());
3523 ((TextView) certificateView.findViewById(R.id.to_org))
3524 .setText(issuedTo.getOName());
3525 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3526 .setText(issuedTo.getUName());
3527 }
3528
3529 // issued by:
3530 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3531 if (issuedBy != null) {
3532 ((TextView) certificateView.findViewById(R.id.by_common))
3533 .setText(issuedBy.getCName());
3534 ((TextView) certificateView.findViewById(R.id.by_org))
3535 .setText(issuedBy.getOName());
3536 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3537 .setText(issuedBy.getUName());
3538 }
3539
3540 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003541 String issuedOn = formatCertificateDate(
3542 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003543 ((TextView) certificateView.findViewById(R.id.issued_on))
3544 .setText(issuedOn);
3545
3546 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003547 String expiresOn = formatCertificateDate(
3548 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003549 ((TextView) certificateView.findViewById(R.id.expires_on))
3550 .setText(expiresOn);
3551
3552 return certificateView;
3553 }
3554
3555 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003556 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003557 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003558 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003559 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003560 private String formatCertificateDate(Date certificateDate) {
3561 if (certificateDate == null) {
3562 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003563 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003564 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3565 if (formattedDate == null) {
3566 return "";
3567 }
3568 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003569 }
3570
3571 /**
3572 * Displays an http-authentication dialog.
3573 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003574 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003575 final String host, final String realm, final String title,
3576 final String name, final String password, int focusId) {
3577 LayoutInflater factory = LayoutInflater.from(this);
3578 final View v = factory
3579 .inflate(R.layout.http_authentication, null);
3580 if (name != null) {
3581 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3582 }
3583 if (password != null) {
3584 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3585 }
3586
3587 String titleText = title;
3588 if (titleText == null) {
3589 titleText = getText(R.string.sign_in_to).toString().replace(
3590 "%s1", host).replace("%s2", realm);
3591 }
3592
3593 mHttpAuthHandler = handler;
3594 AlertDialog dialog = new AlertDialog.Builder(this)
3595 .setTitle(titleText)
3596 .setIcon(android.R.drawable.ic_dialog_alert)
3597 .setView(v)
3598 .setPositiveButton(R.string.action,
3599 new DialogInterface.OnClickListener() {
3600 public void onClick(DialogInterface dialog,
3601 int whichButton) {
3602 String nm = ((EditText) v
3603 .findViewById(R.id.username_edit))
3604 .getText().toString();
3605 String pw = ((EditText) v
3606 .findViewById(R.id.password_edit))
3607 .getText().toString();
3608 BrowserActivity.this.setHttpAuthUsernamePassword
3609 (host, realm, nm, pw);
3610 handler.proceed(nm, pw);
3611 mHttpAuthenticationDialog = null;
3612 mHttpAuthHandler = null;
3613 }})
3614 .setNegativeButton(R.string.cancel,
3615 new DialogInterface.OnClickListener() {
3616 public void onClick(DialogInterface dialog,
3617 int whichButton) {
3618 handler.cancel();
3619 BrowserActivity.this.resetTitleAndRevertLockIcon();
3620 mHttpAuthenticationDialog = null;
3621 mHttpAuthHandler = null;
3622 }})
3623 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3624 public void onCancel(DialogInterface dialog) {
3625 handler.cancel();
3626 BrowserActivity.this.resetTitleAndRevertLockIcon();
3627 mHttpAuthenticationDialog = null;
3628 mHttpAuthHandler = null;
3629 }})
3630 .create();
3631 // Make the IME appear when the dialog is displayed if applicable.
3632 dialog.getWindow().setSoftInputMode(
3633 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3634 dialog.show();
3635 if (focusId != 0) {
3636 dialog.findViewById(focusId).requestFocus();
3637 } else {
3638 v.findViewById(R.id.username_edit).requestFocus();
3639 }
3640 mHttpAuthenticationDialog = dialog;
3641 }
3642
3643 public int getProgress() {
3644 WebView w = mTabControl.getCurrentWebView();
3645 if (w != null) {
3646 return w.getProgress();
3647 } else {
3648 return 100;
3649 }
3650 }
3651
3652 /**
3653 * Set HTTP authentication password.
3654 *
3655 * @param host The host for the password
3656 * @param realm The realm for the password
3657 * @param username The username for the password. If it is null, it means
3658 * password can't be saved.
3659 * @param password The password
3660 */
3661 public void setHttpAuthUsernamePassword(String host, String realm,
3662 String username,
3663 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003664 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003665 if (w != null) {
3666 w.setHttpAuthUsernamePassword(host, realm, username, password);
3667 }
3668 }
3669
3670 /**
3671 * connectivity manager says net has come or gone... inform the user
3672 * @param up true if net has come up, false if net has gone down
3673 */
3674 public void onNetworkToggle(boolean up) {
3675 if (up == mIsNetworkUp) {
3676 return;
3677 } else if (up) {
3678 mIsNetworkUp = true;
3679 if (mAlertDialog != null) {
3680 mAlertDialog.cancel();
3681 mAlertDialog = null;
3682 }
3683 } else {
3684 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003685 if (mInLoad) {
3686 createAndShowNetworkDialog();
3687 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003688 }
3689 WebView w = mTabControl.getCurrentWebView();
3690 if (w != null) {
3691 w.setNetworkAvailable(up);
3692 }
3693 }
3694
Grace Kloba22ac16e2009-10-07 18:00:23 -07003695 boolean isNetworkUp() {
3696 return mIsNetworkUp;
3697 }
3698
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003699 // This method shows the network dialog alerting the user that the net is
3700 // down. It will only show the dialog if mAlertDialog is null.
3701 private void createAndShowNetworkDialog() {
3702 if (mAlertDialog == null) {
3703 mAlertDialog = new AlertDialog.Builder(this)
3704 .setTitle(R.string.loadSuspendedTitle)
3705 .setMessage(R.string.loadSuspended)
3706 .setPositiveButton(R.string.ok, null)
3707 .show();
3708 }
3709 }
3710
The Android Open Source Project0c908882009-03-03 19:32:16 -08003711 @Override
3712 protected void onActivityResult(int requestCode, int resultCode,
3713 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003714 if (getTopWindow() == null) return;
3715
The Android Open Source Project0c908882009-03-03 19:32:16 -08003716 switch (requestCode) {
3717 case COMBO_PAGE:
3718 if (resultCode == RESULT_OK && intent != null) {
3719 String data = intent.getAction();
3720 Bundle extras = intent.getExtras();
3721 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003722 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003723 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003724 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003725 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003726 dismissSubWindow(currentTab);
3727 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003728 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003729 }
3730 }
3731 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003732 // Deliberately fall through to PREFERENCES_PAGE, since the
3733 // same extra may be attached to the COMBO_PAGE
3734 case PREFERENCES_PAGE:
3735 if (resultCode == RESULT_OK && intent != null) {
3736 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3737 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3738 mTabControl.removeParentChildRelationShips();
3739 }
3740 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003741 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003742 // Choose a file from the file picker.
3743 case FILE_SELECTED:
3744 if (null == mUploadMessage) break;
3745 Uri result = intent == null || resultCode != RESULT_OK ? null
3746 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003747
3748 // As we ask the camera to save the result of the user taking
3749 // a picture, the camera application does not return anything other
3750 // than RESULT_OK. So we need to check whether the file we expected
3751 // was written to disk in the in the case that we
3752 // did not get an intent returned but did get a RESULT_OK. If it was,
3753 // we assume that this result has came back from the camera.
3754 if (result == null && intent == null && resultCode == RESULT_OK) {
3755 File cameraFile = new File(mCameraFilePath);
3756 if (cameraFile.exists()) {
3757 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003758 // Broadcast to the media scanner that we have a new photo
3759 // so it will be added into the gallery for the user.
3760 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003761 }
3762 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003763 mUploadMessage.onReceiveValue(result);
3764 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003765 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003766 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003767 default:
3768 break;
3769 }
Leon Scroggins30444232009-09-04 18:36:20 -04003770 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003771 }
3772
3773 /*
3774 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003775 * menu to see the download window. It shows the download window on top of
3776 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003777 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003778 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003779 Intent intent = new Intent(this,
3780 BrowserDownloadPage.class);
3781 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003782 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003783
3784 }
3785
Ben Murdocheecb4e62010-07-06 16:30:38 +01003786 /* package*/ void promptAddOrInstallBookmark() {
3787 final Tab current = mTabControl.getCurrentTab();
3788 Resources resources = getResources();
3789 CharSequence[] choices = {
3790 resources.getString(R.string.save_to_bookmarks),
3791 resources.getString(R.string.create_shortcut_bookmark)
3792 };
3793
3794 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3795 builder.setTitle(R.string.add_new_bookmark);
3796 builder.setItems(choices, new DialogInterface.OnClickListener() {
3797 public void onClick(DialogInterface dialog, int item) {
3798 if (item == 0) {
3799 bookmarkCurrentPage();
3800 } else if (item == 1) {
3801 current.populatePickerData();
3802 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3803 if (touchIconUrl != null) {
3804 // Download the touch icon for this site then save it to the
3805 // homescreen.
3806 Bundle b = new Bundle();
3807 b.putString("url", current.getUrl());
3808 b.putString("title", current.getTitle());
3809 b.putParcelable("favicon", current.getFavicon());
3810 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3811 msg.setData(b);
Ben Murdochccb5de02010-07-19 18:38:17 +01003812 new DownloadTouchIcon(BrowserActivity.this, msg,
Ben Murdocheecb4e62010-07-06 16:30:38 +01003813 mTabControl.getCurrentWebView().getSettings()
3814 .getUserAgentString()).execute(touchIconUrl);
3815 } else {
3816 // add to homescreen, can do it immediately as there is no touch
3817 // icon.
3818 showSaveToHomescreenDialog(current.getUrl(), current.getTitle(),
3819 null, current.getFavicon());
3820 }
3821 }
3822 }
3823 });
3824 builder.create().show();
3825 }
3826
Leon Scroggins160a7e72009-08-14 18:28:01 -04003827 /**
3828 * Open the Go page.
3829 * @param startWithHistory If true, open starting on the history tab.
3830 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003831 */
Leon Scroggins30444232009-09-04 18:36:20 -04003832 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003833 WebView current = mTabControl.getCurrentWebView();
3834 if (current == null) {
3835 return;
3836 }
3837 Intent intent = new Intent(this,
3838 CombinedBookmarkHistoryActivity.class);
3839 String title = current.getTitle();
3840 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003841 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3842 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003843
The Android Open Source Project0c908882009-03-03 19:32:16 -08003844 // Just in case the user opens bookmarks before a page finishes loading
3845 // so the current history item, and therefore the page, is null.
3846 if (null == url) {
3847 url = mLastEnteredUrl;
3848 // This can happen.
3849 if (null == url) {
3850 url = mSettings.getHomePage();
3851 }
3852 }
3853 // In case the web page has not yet received its associated title.
3854 if (title == null) {
3855 title = url;
3856 }
3857 intent.putExtra("title", title);
3858 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003859 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003860 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003861 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003862 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003863 if (startWithHistory) {
3864 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3865 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3866 }
3867 startActivityForResult(intent, COMBO_PAGE);
3868 }
3869
Ben Murdocheecb4e62010-07-06 16:30:38 +01003870 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
3871 Bitmap favicon) {
3872 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
3873
3874 // Just in case the user tries to save before a page finishes loading
3875 // so the current history item, and therefore the page, is null.
3876 if (null == url) {
3877 url = mLastEnteredUrl;
3878 // This can happen.
3879 if (null == url) {
3880 url = mSettings.getHomePage();
3881 }
3882 }
3883
3884 // In case the web page has not yet received its associated title.
3885 if (title == null) {
3886 title = url;
3887 }
3888
3889 intent.putExtra("title", title);
3890 intent.putExtra("url", url);
3891 intent.putExtra("favicon", favicon);
3892 intent.putExtra("touchIcon", touchIcon);
3893 startActivity(intent);
3894 }
3895
3896
The Android Open Source Project0c908882009-03-03 19:32:16 -08003897 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003898 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003899 // In case the user enters nothing.
3900 if (url != null && url.length() != 0 && view != null) {
3901 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003902 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003903 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003904 }
3905 }
3906 }
3907
Leon Scroggins92472e82010-02-17 16:32:28 -05003908 /**
3909 * Load the URL into the given WebView and update the title bar
3910 * to reflect the new load. Call this instead of WebView.loadUrl
3911 * directly.
3912 * @param view The WebView used to load url.
3913 * @param url The URL to load.
3914 */
3915 private void loadUrl(WebView view, String url) {
3916 updateTitleBarForNewLoad(view, url);
3917 view.loadUrl(url);
3918 }
3919
3920 /**
3921 * Load UrlData into a Tab and update the title bar to reflect the new
3922 * load. Call this instead of UrlData.loadIn directly.
3923 * @param t The Tab used to load.
3924 * @param data The UrlData being loaded.
3925 */
3926 private void loadUrlDataIn(Tab t, UrlData data) {
3927 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3928 data.loadIn(t);
3929 }
3930
3931 /**
3932 * If the WebView is the top window, update the title bar to reflect
3933 * loading the new URL. i.e. set its text, clear the favicon (which
3934 * will be set once the page begins loading), and set the progress to
3935 * INITIAL_PROGRESS to show that the page has begun to load. Called
3936 * by loadUrl and loadUrlDataIn.
3937 * @param view The WebView that is starting a load.
3938 * @param url The URL that is being loaded.
3939 */
3940 private void updateTitleBarForNewLoad(WebView view, String url) {
3941 if (view == getTopWindow()) {
3942 setUrlTitle(url, null);
3943 setFavicon(null);
3944 onProgressChanged(view, INITIAL_PROGRESS);
3945 }
3946 }
3947
The Android Open Source Project0c908882009-03-03 19:32:16 -08003948 private String smartUrlFilter(Uri inUri) {
3949 if (inUri != null) {
3950 return smartUrlFilter(inUri.toString());
3951 }
3952 return null;
3953 }
3954
Feng Qianb34f87a2009-03-24 21:27:26 -07003955 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003956 "(?i)" + // switch on case insensitive matching
3957 "(" + // begin group for schema
3958 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003959 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003960 ")" +
3961 "(.*)" );
3962
3963 /**
3964 * Attempts to determine whether user input is a URL or search
3965 * terms. Anything with a space is passed to search.
3966 *
3967 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3968 * "Http://" converts to "http://"
3969 *
3970 * @return Original or modified URL
3971 *
3972 */
3973 String smartUrlFilter(String url) {
3974
3975 String inUrl = url.trim();
3976 boolean hasSpace = inUrl.indexOf(' ') != -1;
3977
3978 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3979 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003980 // force scheme to lowercase
3981 String scheme = matcher.group(1);
3982 String lcScheme = scheme.toLowerCase();
3983 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003984 inUrl = lcScheme + matcher.group(2);
3985 }
3986 if (hasSpace) {
3987 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003988 }
3989 return inUrl;
3990 }
3991 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003992 // FIXME: Is this the correct place to add to searches?
3993 // what if someone else calls this function?
3994 int shortcut = parseUrlShortcut(inUrl);
3995 if (shortcut != SHORTCUT_INVALID) {
3996 Browser.addSearchUrl(mResolver, inUrl);
3997 String query = inUrl.substring(2);
3998 switch (shortcut) {
3999 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004000 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004001 case SHORTCUT_WIKIPEDIA_SEARCH:
4002 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4003 case SHORTCUT_DICTIONARY_SEARCH:
4004 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4005 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004006 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004007 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004008 }
4009 }
4010 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004011 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004012 return URLUtil.guessUrl(inUrl);
4013 }
4014 }
4015
4016 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004017 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004018 }
4019
Ben Murdochbff2d602009-07-01 20:19:05 +01004020 /* package */ void setShouldShowErrorConsole(boolean flag) {
4021 if (flag == mShouldShowErrorConsole) {
4022 // Nothing to do.
4023 return;
4024 }
4025
4026 mShouldShowErrorConsole = flag;
4027
Grace Kloba22ac16e2009-10-07 18:00:23 -07004028 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
4029 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004030
4031 if (flag) {
4032 // Setting the show state of the console will cause it's the layout to be inflated.
4033 if (errorConsole.numberOfErrors() > 0) {
4034 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4035 } else {
4036 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4037 }
4038
4039 // Now we can add it to the main view.
4040 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004041 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004042 ViewGroup.LayoutParams.WRAP_CONTENT));
4043 } else {
4044 mErrorConsoleContainer.removeView(errorConsole);
4045 }
4046
4047 }
4048
Grace Kloba22ac16e2009-10-07 18:00:23 -07004049 boolean shouldShowErrorConsole() {
4050 return mShouldShowErrorConsole;
4051 }
4052
Andrei Popescu163ab742009-10-20 17:58:23 +01004053 private void setStatusBarVisibility(boolean visible) {
4054 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4055 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4056 }
4057
Andrei Popescu56199cc2010-01-12 22:39:16 +00004058
4059 private void sendNetworkType(String type, String subtype) {
4060 WebView w = mTabControl.getCurrentWebView();
4061 if (w != null) {
4062 w.setNetworkType(type, subtype);
4063 }
4064 }
4065
Andrei Popescu30995e72010-02-09 16:59:58 +00004066 private void packageChanged(String packageName, boolean wasAdded) {
4067 WebView w = mTabControl.getCurrentWebView();
4068 if (w == null) {
4069 return;
4070 }
4071
4072 if (wasAdded) {
4073 w.addPackageName(packageName);
4074 } else {
4075 w.removePackageName(packageName);
4076 }
4077 }
4078
4079 private void addPackageNames(Set<String> packageNames) {
4080 WebView w = mTabControl.getCurrentWebView();
4081 if (w == null) {
4082 return;
4083 }
4084
4085 w.addPackageNames(packageNames);
4086 }
4087
4088 private void getInstalledPackages() {
4089 AsyncTask<Void, Void, Set<String> > task =
4090 new AsyncTask<Void, Void, Set<String> >() {
Michael Kolbe0a36662010-06-29 10:37:12 -07004091 @Override
Andrei Popescu30995e72010-02-09 16:59:58 +00004092 protected Set<String> doInBackground(Void... unused) {
4093 Set<String> installedPackages = new HashSet<String>();
4094 PackageManager pm = BrowserActivity.this.getPackageManager();
4095 if (pm != null) {
4096 List<PackageInfo> packages = pm.getInstalledPackages(0);
4097 for (PackageInfo p : packages) {
4098 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
4099 installedPackages.add(p.packageName);
4100 }
4101 }
4102 }
4103
4104 return installedPackages;
4105 }
4106
4107 // Executes on the UI thread
Michael Kolbe0a36662010-06-29 10:37:12 -07004108 @Override
Andrei Popescu30995e72010-02-09 16:59:58 +00004109 protected void onPostExecute(Set<String> installedPackages) {
4110 addPackageNames(installedPackages);
4111 }
4112 };
4113 task.execute();
4114 }
4115
Grace Klobaeb6eef42009-09-15 17:56:32 -07004116 final static int LOCK_ICON_UNSECURE = 0;
4117 final static int LOCK_ICON_SECURE = 1;
4118 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004119
The Android Open Source Project0c908882009-03-03 19:32:16 -08004120 private BrowserSettings mSettings;
4121 private TabControl mTabControl;
4122 private ContentResolver mResolver;
4123 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004124 private View mCustomView;
4125 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004126 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004127
4128 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4129 // view, we should rewrite this.
4130 private int mCurrentMenuState = 0;
4131 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004132 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004133 private static final int EMPTY_MENU = -1;
4134 private Menu mMenu;
4135
4136 private FindDialog mFindDialog;
Cary Clark01cfcdd2010-06-04 16:36:45 -04004137 private SelectDialog mSelectDialog;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004138 // Used to prevent chording to result in firing two shortcuts immediately
4139 // one after another. Fixes bug 1211714.
4140 boolean mCanChord;
4141
4142 private boolean mInLoad;
4143 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004144 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004145
Cary Clark1f10cbf2010-03-22 11:45:23 -04004146 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004147
4148 private boolean mMenuIsDown;
4149
The Android Open Source Project0c908882009-03-03 19:32:16 -08004150 private static boolean mInTrace;
4151
4152 // Performance probe
4153 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4154 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4155 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4156 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4157 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4158 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4159 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4160 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4161 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4162 };
4163
4164 private long mStart;
4165 private long mProcessStart;
4166 private long mUserStart;
4167 private long mSystemStart;
4168 private long mIdleStart;
4169 private long mIrqStart;
4170
4171 private long mUiStart;
4172
4173 private Drawable mMixLockIcon;
4174 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004175
4176 /* hold a ref so we can auto-cancel if necessary */
4177 private AlertDialog mAlertDialog;
4178
The Android Open Source Project0c908882009-03-03 19:32:16 -08004179 // The up-to-date URL and title (these can be different from those stored
4180 // in WebView, since it takes some time for the information in WebView to
4181 // get updated)
4182 private String mUrl;
4183 private String mTitle;
4184
4185 // As PageInfo has different style for landscape / portrait, we have
4186 // to re-open it when configuration changed
4187 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004188 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004189 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4190 // dialog, we should not just dismiss it, but should get back to the
4191 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004192 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004193
4194 // as SSLCertificateOnError has different style for landscape / portrait,
4195 // we have to re-open it when configuration changed
4196 private AlertDialog mSSLCertificateOnErrorDialog;
4197 private WebView mSSLCertificateOnErrorView;
4198 private SslErrorHandler mSSLCertificateOnErrorHandler;
4199 private SslError mSSLCertificateOnErrorError;
4200
4201 // as SSLCertificate has different style for landscape / portrait, we
4202 // have to re-open it when configuration changed
4203 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004204 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004205
4206 // as HttpAuthentication has different style for landscape / portrait, we
4207 // have to re-open it when configuration changed
4208 private AlertDialog mHttpAuthenticationDialog;
4209 private HttpAuthHandler mHttpAuthHandler;
4210
4211 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4212 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004213 ViewGroup.LayoutParams.MATCH_PARENT,
4214 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004215 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4216 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004217 ViewGroup.LayoutParams.MATCH_PARENT,
4218 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004219 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004220 // Google search
4221 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004222 // Wikipedia search
4223 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4224 // Dictionary search
4225 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4226 // Google Mobile Local search
4227 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4228
4229 final static String QUERY_PLACE_HOLDER = "%s";
4230
4231 // "source" parameter for Google search through search key
4232 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4233 // "source" parameter for Google search through goto menu
4234 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4235 // "source" parameter for Google search through simplily type
4236 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4237 // "source" parameter for Google search suggested by the browser
4238 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4239 // "source" parameter for Google search from unknown source
4240 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4241
4242 private final static String LOGTAG = "browser";
4243
The Android Open Source Project0c908882009-03-03 19:32:16 -08004244 private String mLastEnteredUrl;
4245
4246 private PowerManager.WakeLock mWakeLock;
4247 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4248
4249 private Toast mStopToast;
4250
Leon Scroggins571b3762010-05-26 10:25:01 -04004251 private TitleBarBase mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004252
Ben Murdochbff2d602009-07-01 20:19:05 +01004253 private LinearLayout mErrorConsoleContainer = null;
4254 private boolean mShouldShowErrorConsole = false;
4255
The Android Open Source Project0c908882009-03-03 19:32:16 -08004256 // As the ids are dynamically created, we can't guarantee that they will
4257 // be in sequence, so this static array maps ids to a window number.
4258 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4259 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4260 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4261 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4262
4263 // monitor platform changes
4264 private IntentFilter mNetworkStateChangedFilter;
4265 private BroadcastReceiver mNetworkStateIntentReceiver;
4266
Grace Klobab4da0ad2009-05-14 14:45:40 -07004267 private BroadcastReceiver mPackageInstallationReceiver;
4268
Bjorn Bringerta7611812010-03-24 11:12:02 +00004269 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4270
The Android Open Source Project0c908882009-03-03 19:32:16 -08004271 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004272 final static int COMBO_PAGE = 1;
4273 final static int DOWNLOAD_PAGE = 2;
4274 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004275 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004276
Andrei Popescu540035d2009-09-18 18:59:20 +01004277 // the default <video> poster
4278 private Bitmap mDefaultVideoPoster;
4279 // the video progress view
4280 private View mVideoProgressView;
4281
Andrei Popescu30995e72010-02-09 16:59:58 +00004282 // The Google packages we monitor for the navigator.isApplicationInstalled()
4283 // API. Add as needed.
4284 private static Set<String> sGoogleApps;
4285 static {
4286 sGoogleApps = new HashSet<String>();
4287 sGoogleApps.add("com.google.android.youtube");
4288 }
4289
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004290 /**
4291 * A UrlData class to abstract how the content will be set to WebView.
4292 * This base class uses loadUrl to show the content.
4293 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004294 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004295 final String mUrl;
4296 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004297 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004298
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004299 UrlData(String url) {
4300 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004301 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004302 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004303 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004304
Leon Scroggins58d56c62010-01-28 15:12:40 -05004305 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004306 this.mUrl = url;
4307 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004308 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4309 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004310 this.mVoiceIntent = intent;
4311 } else {
4312 this.mVoiceIntent = null;
4313 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004314 }
4315
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004316 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004317 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004318 }
4319
Leon Scroggins92472e82010-02-17 16:32:28 -05004320 /**
4321 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4322 * the title bar as well.
4323 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004324 public void loadIn(Tab t) {
4325 if (mVoiceIntent != null) {
4326 t.activateVoiceSearchMode(mVoiceIntent);
4327 } else {
4328 t.getWebView().loadUrl(mUrl, mHeaders);
4329 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004330 }
4331 };
4332
Leon Scroggins1f005d32009-08-10 17:36:42 -04004333 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004334}