blob: 2260200e847d3b90f4492630f9a8aec9e591ad64 [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
Michael Kolb3f65c382010-08-20 15:31:16 -070019import com.android.browser.ScrollWebView.ScrollListener;
20import com.android.common.Search;
21import com.android.common.speech.LoggingEvents;
22
Michael Kolbed217742010-08-10 17:52:34 -070023import android.app.ActionBar;
The Android Open Source Project0c908882009-03-03 19:32:16 -080024import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080025import android.app.AlertDialog;
26import android.app.ProgressDialog;
27import android.app.SearchManager;
28import android.content.ActivityNotFoundException;
29import android.content.BroadcastReceiver;
Dianne Hackborn80f32622010-08-05 14:17:53 -070030import android.content.ClipboardManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080031import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050032import android.content.ContentProvider;
33import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080034import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040035import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080036import android.content.ContentValues;
37import android.content.Context;
38import android.content.DialogInterface;
39import android.content.Intent;
40import android.content.IntentFilter;
The Android Open Source Project0c908882009-03-03 19:32:16 -080041import android.content.pm.PackageManager;
42import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080043import android.content.res.Configuration;
44import android.content.res.Resources;
45import android.database.Cursor;
The Android Open Source Project0c908882009-03-03 19:32:16 -080046import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010047import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080048import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040050import android.graphics.PixelFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080052import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000053import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080054import android.net.Uri;
55import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080056import android.net.http.SslCertificate;
57import android.net.http.SslError;
58import android.os.AsyncTask;
59import android.os.Bundle;
60import android.os.Debug;
61import android.os.Environment;
62import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080063import android.os.Message;
64import android.os.PowerManager;
65import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080066import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080067import android.provider.Browser;
Jeff Hamilton8ce956c2010-08-17 11:13:53 -050068import android.provider.BrowserContract;
Cary Clark5e335a32009-09-22 14:53:11 -040069import android.provider.ContactsContract;
Michael Kolba2b2ba82010-08-04 17:54:03 -070070import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080071import android.provider.Downloads;
72import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050073import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080074import android.text.TextUtils;
75import android.text.format.DateFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080076import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080077import android.util.Patterns;
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -040078import android.view.ActionMode;
The Android Open Source Project0c908882009-03-03 19:32:16 -080079import android.view.ContextMenu;
Michael Kolba2b2ba82010-08-04 17:54:03 -070080import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080081import android.view.Gravity;
82import android.view.KeyEvent;
83import android.view.LayoutInflater;
84import android.view.Menu;
85import android.view.MenuInflater;
86import android.view.MenuItem;
Michael Kolba2b2ba82010-08-04 17:54:03 -070087import android.view.MenuItem.OnMenuItemClickListener;
Michael Kolb3f65c382010-08-20 15:31:16 -070088import android.view.MotionEvent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080089import android.view.View;
90import android.view.ViewGroup;
91import android.view.Window;
92import android.view.WindowManager;
Svetoslav Ganov2b345992010-05-06 06:13:54 -070093import android.view.accessibility.AccessibilityManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080094import android.webkit.CookieManager;
95import android.webkit.CookieSyncManager;
96import android.webkit.DownloadListener;
97import android.webkit.HttpAuthHandler;
98import android.webkit.SslErrorHandler;
99import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +0100100import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800101import android.webkit.WebChromeClient;
102import android.webkit.WebHistoryItem;
103import android.webkit.WebIconDatabase;
104import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800105import android.widget.EditText;
106import android.widget.FrameLayout;
107import android.widget.LinearLayout;
108import android.widget.TextView;
109import android.widget.Toast;
110
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400111import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800112import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000113import java.io.IOException;
114import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800115import java.net.MalformedURLException;
Dianne Hackborn99189432009-06-17 18:06:18 -0700116import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800117import java.net.URL;
118import java.net.URLEncoder;
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700119import java.util.Calendar;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800121import java.util.HashMap;
Grace Kloba00f54c52010-01-27 14:53:51 -0800122import java.util.Iterator;
Grace Kloba068e48b2010-01-26 18:11:27 -0800123import java.util.Map;
Michael Kolbfe251992010-07-08 15:41:55 -0700124import java.util.Vector;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800125import java.util.regex.Matcher;
126import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800127
128public class BrowserActivity extends Activity
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700129 implements View.OnCreateContextMenuListener, DownloadListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800130
Dave Bort31a6d1c2009-04-13 15:56:49 -0700131 /* Define some aliases to make these debugging flags easier to refer to.
132 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
133 */
134 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
135 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
136 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
137
Satish Sampath565505b2009-05-29 15:37:27 +0100138 // These are single-character shortcuts for searching popular sources.
139 private static final int SHORTCUT_INVALID = 0;
140 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
141 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
142 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
143 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
144
Cary Clarka9771242009-08-11 16:42:26 -0400145 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800146 @Override
147 public Void doInBackground(File... files) {
148 if (files != null) {
149 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400150 if (!f.delete()) {
151 Log.e(LOGTAG, f.getPath() + " was not deleted");
152 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800153 }
154 }
155 return null;
156 }
157 }
158
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400159 /**
160 * This layout holds everything you see below the status bar, including the
161 * error console, the custom view container, and the webviews.
162 */
163 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400164
Leon Scrogginsd746a942010-05-19 13:21:44 -0400165 private boolean mXLargeScreenSize;
166
Jeff Davidson43610292010-07-16 16:03:58 -0700167 private Boolean mIsProviderPresent = null;
168 private Uri mRlzUri = null;
169
Grace Kloba22ac16e2009-10-07 18:00:23 -0700170 @Override
171 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700172 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800173 Log.v(LOGTAG, this + " onStart");
174 }
175 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800176 // test the browser in OpenGL
177 // requestWindowFeature(Window.FEATURE_OPENGL);
178
Mike Reedd334bf52010-01-26 15:21:44 -0500179 // enable this to test the browser in 32bit
180 if (false) {
181 getWindow().setFormat(PixelFormat.RGBX_8888);
182 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
183 }
184
Svetoslav Ganov2b345992010-05-06 06:13:54 -0700185 if (AccessibilityManager.getInstance(this).isEnabled()) {
186 setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
187 } else {
188 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
189 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800190
191 mResolver = getContentResolver();
192
Grace Kloba0923d692009-09-23 21:37:25 -0700193 // If this was a web search request, pass it on to the default web
194 // search provider and finish this activity.
195 if (handleWebSearchIntent(getIntent())) {
196 finish();
197 return;
198 }
199
The Android Open Source Project0c908882009-03-03 19:32:16 -0800200 mSecLockIcon = Resources.getSystem().getDrawable(
201 android.R.drawable.ic_secure);
202 mMixLockIcon = Resources.getSystem().getDrawable(
203 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800204
Michael Kolbed217742010-08-10 17:52:34 -0700205 // Create the tab control and our initial tab
206 mTabControl = new TabControl(this);
207
208 mXLargeScreenSize = (getResources().getConfiguration().screenLayout
209 & Configuration.SCREENLAYOUT_SIZE_MASK)
210 == Configuration.SCREENLAYOUT_SIZE_XLARGE;
211
Leon Scroggins81db3662009-06-04 17:45:11 -0400212 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
213 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400214 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
215 .inflate(R.layout.custom_screen, null);
216 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
217 R.id.main_content);
218 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
219 .findViewById(R.id.error_console);
220 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
221 .findViewById(R.id.fullscreen_custom_content);
222 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Michael Kolbe0a36662010-06-29 10:37:12 -0700223
Leon Scrogginsd746a942010-05-19 13:21:44 -0400224 if (mXLargeScreenSize) {
Michael Kolba2b2ba82010-08-04 17:54:03 -0700225 mTitleBar = new TitleBarXLarge(this);
226 mTitleBar.setProgress(100);
227 mFakeTitleBar = new TitleBarXLarge(this);
Michael Kolbed217742010-08-10 17:52:34 -0700228 ActionBar actionBar = getActionBar();
Michael Kolba2b2ba82010-08-04 17:54:03 -0700229 mTabBar = new TabBar(this, mTabControl, (TitleBarXLarge) mFakeTitleBar);
Michael Kolbed217742010-08-10 17:52:34 -0700230 actionBar.setCustomNavigationMode(mTabBar);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400231 } else {
Leon Scroggins571b3762010-05-26 10:25:01 -0400232 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400233 // mTitleBar will be always be shown in the fully loaded mode on
234 // phone
235 mTitleBar.setProgress(100);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400236 mFakeTitleBar = new TitleBar(this);
237 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800238
The Android Open Source Project0c908882009-03-03 19:32:16 -0800239 // Open the icon database and retain all the bookmark urls for favicons
240 retainIconsOnStartup();
241
242 // Keep a settings instance handy.
243 mSettings = BrowserSettings.getInstance();
244 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800245
246 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
247 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
248
Patrick Scott6adacc92010-03-05 08:24:51 -0500249 // Find out if the network is currently up.
250 ConnectivityManager cm = (ConnectivityManager) getSystemService(
251 Context.CONNECTIVITY_SERVICE);
252 NetworkInfo info = cm.getActiveNetworkInfo();
253 if (info != null) {
254 mIsNetworkUp = info.isAvailable();
255 }
256
Grace Klobaa34f6862009-07-31 16:28:17 -0700257 /* enables registration for changes in network status from
258 http stack */
259 mNetworkStateChangedFilter = new IntentFilter();
260 mNetworkStateChangedFilter.addAction(
261 ConnectivityManager.CONNECTIVITY_ACTION);
262 mNetworkStateIntentReceiver = new BroadcastReceiver() {
263 @Override
264 public void onReceive(Context context, Intent intent) {
265 if (intent.getAction().equals(
266 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000267
268 NetworkInfo info = intent.getParcelableExtra(
269 ConnectivityManager.EXTRA_NETWORK_INFO);
270 String typeName = info.getTypeName();
271 String subtypeName = info.getSubtypeName();
272 sendNetworkType(typeName.toLowerCase(),
273 (subtypeName != null ? subtypeName.toLowerCase() : ""));
274
275 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700276 }
277 }
278 };
279
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700280 // Unless the last browser usage was within 24 hours, destroy any
281 // remaining incognito tabs.
282
283 Calendar lastActiveDate = icicle != null ? (Calendar) icicle.getSerializable("lastActiveDate") : null;
284 Calendar today = Calendar.getInstance();
285 Calendar yesterday = Calendar.getInstance();
286 yesterday.add(Calendar.DATE, -1);
287
288 boolean dontRestoreIncognitoTabs = lastActiveDate == null
289 || lastActiveDate.before(yesterday)
290 || lastActiveDate.after(today);
291
292 if (!mTabControl.restoreState(icicle, dontRestoreIncognitoTabs)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800293 // clear up the thumbnail directory if we can't restore the state as
294 // none of the files in the directory are referenced any more.
295 new ClearThumbnails().execute(
296 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700297 // there is no quit on Android. But if we can't restore the state,
298 // we can treat it as a new Browser, remove the old session cookies.
299 CookieManager.getInstance().removeSessionCookie();
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700300 // remove any incognito files
301 WebView.cleanupPrivateBrowsingFiles(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800302 final Intent intent = getIntent();
303 final Bundle extra = intent.getExtras();
304 // Create an initial tab.
305 // If the intent is ACTION_VIEW and data is not null, the Browser is
306 // invoked to view the content by another application. In this case,
307 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700308 UrlData urlData = getUrlDataFromIntent(intent);
309
Leon Scroggins58d56c62010-01-28 15:12:40 -0500310 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700311 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500312 (Intent.ACTION_VIEW.equals(action) &&
313 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500314 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
315 .equals(action),
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700316 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
317 urlData.mUrl, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800318 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800319 attachTabToContentView(t);
320 WebView webView = t.getWebView();
321 if (extra != null) {
322 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
323 if (scale > 0 && scale <= 1000) {
324 webView.setInitialScale(scale);
325 }
326 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800327
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700328 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700329 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800330 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500331 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800332 }
333 } else {
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700334 if (dontRestoreIncognitoTabs) {
335 WebView.cleanupPrivateBrowsingFiles(this);
336 }
337
The Android Open Source Project0c908882009-03-03 19:32:16 -0800338 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400339 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800340 attachTabToContentView(mTabControl.getCurrentTab());
341 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700342
Cary Clarkb4b83182010-07-01 12:36:56 -0400343 // Delete old thumbnails to save space
344 File dir = mTabControl.getThumbnailDir();
345 if (dir.exists()) {
346 for (String child : dir.list()) {
347 File f = new File(dir, child);
348 f.delete();
349 }
350 }
351
Feng Qianb3c02da2009-06-29 15:58:08 -0700352 // Read JavaScript flags if it exists.
353 String jsFlags = mSettings.getJsFlags();
354 if (jsFlags.trim().length() != 0) {
355 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
356 }
Bjorn Bringerta7611812010-03-24 11:12:02 +0000357
358 // Start watching the default geolocation permissions
359 mSystemAllowGeolocationOrigins
360 = new SystemAllowGeolocationOrigins(getApplicationContext());
361 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800362 }
363
Michael Kolba2b2ba82010-08-04 17:54:03 -0700364 ScrollListener getScrollListener() {
365 return mTabBar;
366 }
367
Leon Scroggins58d56c62010-01-28 15:12:40 -0500368 /**
369 * Feed the previously stored results strings to the BrowserProvider so that
370 * the SearchDialog will show them instead of the standard searches.
371 * @param result String to show on the editable line of the SearchDialog.
372 */
373 /* package */ void showVoiceSearchResults(String result) {
374 ContentProviderClient client = mResolver.acquireContentProviderClient(
375 Browser.BOOKMARKS_URI);
376 ContentProvider prov = client.getLocalContentProvider();
377 BrowserProvider bp = (BrowserProvider) prov;
378 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
379 client.release();
380
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500381 Bundle bundle = createGoogleSearchSourceBundle(
382 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
383 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
384 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500385 }
386
The Android Open Source Project0c908882009-03-03 19:32:16 -0800387 @Override
388 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700389 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800390 // When a tab is closed on exit, the current tab index is set to -1.
391 // Reset before proceed as Browser requires the current tab to be set.
392 if (current == null) {
393 // Try to reset the tab in case the index was incorrect.
394 current = mTabControl.getTab(0);
395 if (current == null) {
396 // No tabs at all so just ignore this intent.
397 return;
398 }
399 mTabControl.setCurrentTab(current);
400 attachTabToContentView(current);
401 resetTitleAndIcon(current.getWebView());
402 }
403 final String action = intent.getAction();
404 final int flags = intent.getFlags();
405 if (Intent.ACTION_MAIN.equals(action) ||
406 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
407 // just resume the browser
408 return;
409 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400410 // In case the SearchDialog is open.
411 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
412 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500413 boolean activateVoiceSearch = RecognizerResultsIntent
414 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800415 if (Intent.ACTION_VIEW.equals(action)
416 || Intent.ACTION_SEARCH.equals(action)
417 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500418 || Intent.ACTION_WEB_SEARCH.equals(action)
419 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500420 if (current.isInVoiceSearchMode()) {
421 String title = current.getVoiceDisplayTitle();
422 if (title != null && title.equals(intent.getStringExtra(
423 SearchManager.QUERY))) {
424 // The user submitted the same search as the last voice
425 // search, so do nothing.
426 return;
427 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500428 if (Intent.ACTION_SEARCH.equals(action)
429 && current.voiceSearchSourceIsGoogle()) {
430 Intent logIntent = new Intent(
431 LoggingEvents.ACTION_LOG_EVENT);
432 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
433 LoggingEvents.VoiceSearch.QUERY_UPDATED);
434 logIntent.putExtra(
435 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
436 intent.getDataString());
437 sendBroadcast(logIntent);
438 // Note, onPageStarted will revert the voice title bar
439 // When http://b/issue?id=2379215 is fixed, we should update
440 // the title bar here.
441 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500442 }
Satish Sampath565505b2009-05-29 15:37:27 +0100443 // If this was a search request (e.g. search query directly typed into the address bar),
444 // pass it on to the default web search provider.
445 if (handleWebSearchIntent(intent)) {
446 return;
447 }
448
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700449 UrlData urlData = getUrlDataFromIntent(intent);
450 if (urlData.isEmpty()) {
451 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800452 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700453
Grace Klobacc634032009-07-28 15:58:19 -0700454 final String appId = intent
455 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400456 if ((Intent.ACTION_VIEW.equals(action)
457 // If a voice search has no appId, it means that it came
458 // from the browser. In that case, reuse the current tab.
459 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700460 && !getPackageName().equals(appId)
461 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700462 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700463 if (appTab != null) {
464 Log.i(LOGTAG, "Reusing tab for " + appId);
465 // Dismiss the subwindow if applicable.
466 dismissSubWindow(appTab);
467 // Since we might kill the WebView, remove it from the
468 // content view first.
469 removeTabFromContentView(appTab);
470 // Recreate the main WebView after destroying the old one.
471 // If the WebView has the same original url and is on that
472 // page, it can be reused.
473 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400474 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100475
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700476 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400477 switchToTab(mTabControl.getTabIndex(appTab));
478 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500479 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400480 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700481 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400482 // If the tab was the current tab, we have to attach
483 // it to the view system again.
484 attachTabToContentView(appTab);
485 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500486 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700487 }
488 }
489 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400490 } else {
491 // No matching application tab, try to find a regular tab
492 // with a matching url.
493 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400494 if (appTab != null) {
495 if (current != appTab) {
496 switchToTab(mTabControl.getTabIndex(appTab));
497 }
498 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400499 } else {
500 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
501 // will be opened in a new tab unless we have reached
502 // MAX_TABS. Then the url will be opened in the current
503 // tab. If a new tab is created, it will have "true" for
504 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400505 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400506 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700507 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800508 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800509 if (!urlData.isEmpty()
510 && urlData.mUrl.startsWith("about:debug")) {
511 if ("about:debug.dom".equals(urlData.mUrl)) {
512 current.getWebView().dumpDomTree(false);
513 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
514 current.getWebView().dumpDomTree(true);
515 } else if ("about:debug.render".equals(urlData.mUrl)) {
516 current.getWebView().dumpRenderTree(false);
517 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
518 current.getWebView().dumpRenderTree(true);
519 } else if ("about:debug.display".equals(urlData.mUrl)) {
520 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800521 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
522 int index = urlData.mUrl.codePointAt(16) - '0';
523 if (index <= 0 || index > 9) {
524 current.getWebView().setDragTracker(null);
525 } else {
526 current.getWebView().setDragTracker(new MeshTracker(index));
527 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800528 } else {
529 mSettings.toggleDebugSettings();
530 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800531 return;
532 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400533 // Get rid of the subwindow if it exists
534 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400535 // If the current Tab is being used as an application tab,
536 // remove the association, since the new Intent means that it is
537 // no longer associated with that application.
538 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500539 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800540 }
541 }
542 }
543
Satish Sampath565505b2009-05-29 15:37:27 +0100544 private int parseUrlShortcut(String url) {
545 if (url == null) return SHORTCUT_INVALID;
546
547 // FIXME: quick search, need to be customized by setting
548 if (url.length() > 2 && url.charAt(1) == ' ') {
549 switch (url.charAt(0)) {
550 case 'g': return SHORTCUT_GOOGLE_SEARCH;
551 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
552 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
553 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
554 }
555 }
556 return SHORTCUT_INVALID;
557 }
558
559 /**
560 * Launches the default web search activity with the query parameters if the given intent's data
561 * are identified as plain search terms and not URLs/shortcuts.
562 * @return true if the intent was handled and web search activity was launched, false if not.
563 */
564 private boolean handleWebSearchIntent(Intent intent) {
565 if (intent == null) return false;
566
567 String url = null;
568 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500569 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
570 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500571 return false;
572 }
Satish Sampath565505b2009-05-29 15:37:27 +0100573 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700574 Uri data = intent.getData();
575 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100576 } else if (Intent.ACTION_SEARCH.equals(action)
577 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
578 || Intent.ACTION_WEB_SEARCH.equals(action)) {
579 url = intent.getStringExtra(SearchManager.QUERY);
580 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100581 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
582 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100583 }
584
585 /**
586 * Launches the default web search activity with the query parameters if the given url string
587 * was identified as plain search terms and not URL/shortcut.
588 * @return true if the request was handled and web search activity was launched, false if not.
589 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100590 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100591 if (inUrl == null) return false;
592
593 // In general, we shouldn't modify URL from Intent.
594 // But currently, we get the user-typed URL from search box as well.
595 String url = fixUrl(inUrl).trim();
596
597 // URLs and site specific search shortcuts are handled by the regular flow of control, so
598 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800599 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100600 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100601 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
602 return false;
603 }
604
Leon Scroggins8d06e362010-03-24 14:45:57 -0400605 final ContentResolver cr = mResolver;
606 final String newUrl = url;
Elliott Slaughter627d96f2010-08-18 16:35:30 -0700607 if (mTabControl == null || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700608 new AsyncTask<Void, Void, Void>() {
609 @Override
610 protected Void doInBackground(Void... unused) {
611 Browser.updateVisitedHistory(cr, newUrl, false);
612 Browser.addSearchUrl(cr, newUrl);
613 return null;
614 }
615 }.execute();
616 }
Satish Sampath565505b2009-05-29 15:37:27 +0100617
618 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
619 intent.addCategory(Intent.CATEGORY_DEFAULT);
620 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100621 if (appData != null) {
622 intent.putExtra(SearchManager.APP_DATA, appData);
623 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100624 if (extraData != null) {
625 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
626 }
Grace Klobacc634032009-07-28 15:58:19 -0700627 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Mattias Falk552751e2010-08-23 12:03:57 +0200628
629 // can't be sure there is an activity for the Intent
630 try {
631 startActivity(intent);
632 } catch (ActivityNotFoundException ex) {
633 return false;
634 }
Satish Sampath565505b2009-05-29 15:37:27 +0100635
636 return true;
637 }
638
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700639 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500640 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800641 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800642 if (intent != null) {
643 final String action = intent.getAction();
644 if (Intent.ACTION_VIEW.equals(action)) {
645 url = smartUrlFilter(intent.getData());
646 if (url != null && url.startsWith("content:")) {
647 /* Append mimetype so webview knows how to display */
648 String mimeType = intent.resolveType(getContentResolver());
649 if (mimeType != null) {
650 url += "?" + mimeType;
651 }
652 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800653 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800654 final Bundle pairs = intent
655 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800656 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800657 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800658 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800659 while (iter.hasNext()) {
660 String key = iter.next();
661 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800662 }
663 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700664 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800665 } else if (Intent.ACTION_SEARCH.equals(action)
666 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
667 || Intent.ACTION_WEB_SEARCH.equals(action)) {
668 url = intent.getStringExtra(SearchManager.QUERY);
669 if (url != null) {
670 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800671 // In general, we shouldn't modify URL from Intent.
672 // But currently, we get the user-typed URL from search box as well.
673 url = fixUrl(url);
674 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400675 final ContentResolver cr = mResolver;
676 final String newUrl = url;
Elliott Slaughter8389e992010-08-20 15:44:08 -0700677 if (mTabControl == null
678 || mTabControl.getCurrentWebView() == null
679 || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
680 new AsyncTask<Void, Void, Void>() {
681 @Override
682 protected Void doInBackground(Void... unused) {
683 Browser.updateVisitedHistory(cr, newUrl, false);
684 return null;
685 }
686 }.execute();
687 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800688 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
689 if (url.contains(searchSource)) {
690 String source = null;
691 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
692 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000693 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800694 }
695 if (TextUtils.isEmpty(source)) {
696 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
697 }
698 url = url.replace(searchSource, "&source=android-"+source+"&");
699 }
700 }
701 }
702 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500703 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800704 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500705 /* package */ void showVoiceTitleBar(String title) {
706 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500707 mTitleBar.setDisplayTitle(title);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700708 mFakeTitleBar.setInVoiceMode(true);
709 mFakeTitleBar.setDisplayTitle(title);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500710 }
711 /* package */ void revertVoiceTitleBar() {
712 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500713 mTitleBar.setDisplayTitle(mUrl);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700714 mFakeTitleBar.setInVoiceMode(false);
715 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500716 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800717 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400718 // FIXME: Converting the url to lower case
719 // duplicates functionality in smartUrlFilter().
720 // However, changing all current callers of fixUrl to
721 // call smartUrlFilter in addition may have unwanted
722 // consequences, and is deferred for now.
723 int colon = inUrl.indexOf(':');
724 boolean allLower = true;
725 for (int index = 0; index < colon; index++) {
726 char ch = inUrl.charAt(index);
727 if (!Character.isLetter(ch)) {
728 break;
729 }
730 allLower &= Character.isLowerCase(ch);
731 if (index == colon - 1 && !allLower) {
732 inUrl = inUrl.substring(0, colon).toLowerCase()
733 + inUrl.substring(colon);
734 }
735 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800736 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
737 return inUrl;
738 if (inUrl.startsWith("http:") ||
739 inUrl.startsWith("https:")) {
740 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
741 inUrl = inUrl.replaceFirst("/", "//");
742 } else inUrl = inUrl.replaceFirst(":", "://");
743 }
744 return inUrl;
745 }
746
Grace Kloba22ac16e2009-10-07 18:00:23 -0700747 @Override
748 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800749 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700750 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800751 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
752 }
753
754 if (!mActivityInPause) {
755 Log.e(LOGTAG, "BrowserActivity is already resumed.");
756 return;
757 }
758
Mike Reed7bfa63b2009-05-28 11:08:32 -0400759 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800760 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400761 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800762
763 if (mWakeLock.isHeld()) {
764 mHandler.removeMessages(RELEASE_WAKELOCK);
765 mWakeLock.release();
766 }
767
The Android Open Source Project0c908882009-03-03 19:32:16 -0800768 registerReceiver(mNetworkStateIntentReceiver,
769 mNetworkStateChangedFilter);
770 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800771 }
772
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400773 /**
774 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400775 * would change its appearance, use a different TitleBar to show overlayed
776 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400777 */
Michael Kolba2b2ba82010-08-04 17:54:03 -0700778 private TitleBarBase mFakeTitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400779
780 /**
781 * Keeps track of whether the options menu is open. This is important in
782 * determining whether to show or hide the title bar overlay.
783 */
784 private boolean mOptionsMenuOpen;
785
786 /**
787 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
788 * of whether the configuration has changed. The first onMenuOpened call
789 * after a configuration change is simply a reopening of the same menu
790 * (i.e. mIconView did not change).
791 */
792 private boolean mConfigChanged;
793
794 /**
795 * Whether or not the options menu is in its smaller, icon menu form. When
796 * true, we want the title bar overlay to be up. When false, we do not.
797 * Only meaningful if mOptionsMenuOpen is true.
798 */
799 private boolean mIconView;
800
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400801 @Override
802 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400803 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
804 if (mOptionsMenuOpen) {
805 if (mConfigChanged) {
806 // We do not need to make any changes to the state of the
807 // title bar, since the only thing that happened was a
808 // change in orientation
809 mConfigChanged = false;
810 } else {
811 if (mIconView) {
812 // Switching the menu to expanded view, so hide the
813 // title bar.
814 hideFakeTitleBar();
815 mIconView = false;
816 } else {
817 // Switching the menu back to icon view, so show the
818 // title bar once again.
819 showFakeTitleBar();
820 mIconView = true;
821 }
822 }
823 } else {
824 // The options menu is closed, so open it, and show the title
825 showFakeTitleBar();
826 mOptionsMenuOpen = true;
827 mConfigChanged = false;
828 mIconView = true;
829 }
830 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400831 return true;
832 }
833
Michael Kolba2b2ba82010-08-04 17:54:03 -0700834 void showFakeTitleBar() {
835 if (!isFakeTitleBarShowing() && mActiveTabsPage == null && !mActivityInPause) {
Grace Kloba847c25b2010-03-30 16:00:26 -0700836 WebView mainView = mTabControl.getCurrentWebView();
837 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700838 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400839 return;
840 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100841 // Do not need to check for null, since the current tab will have
842 // at least a main WebView, or we would have returned above.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -0400843 if (isInCustomActionMode()) {
844 // Do not show the fake title bar, while a custom ActionMode
845 // (i.e. find or select) is showing.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100846 return;
847 }
Michael Kolba2b2ba82010-08-04 17:54:03 -0700848 if (mXLargeScreenSize) {
849 mContentView.addView(mFakeTitleBar);
850 mTabBar.onShowTitleBar();
851 } else {
852 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400853
Michael Kolba2b2ba82010-08-04 17:54:03 -0700854 // Add the title bar to the window manager so it can receive
855 // touches
856 // while the menu is up
857 WindowManager.LayoutParams params =
858 new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
859 ViewGroup.LayoutParams.WRAP_CONTENT,
860 WindowManager.LayoutParams.TYPE_APPLICATION,
861 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
862 PixelFormat.TRANSLUCENT);
863 params.gravity = Gravity.TOP;
864 boolean atTop = mainView.getScrollY() == 0;
865 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
866 manager.addView(mFakeTitleBar, params);
867 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400868 }
869 }
870
871 @Override
872 public void onOptionsMenuClosed(Menu menu) {
873 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400874 if (!mInLoad) {
875 hideFakeTitleBar();
876 } else if (!mIconView) {
877 // The page is currently loading, and we are in expanded mode, so
878 // we were not showing the menu. Show it once again. It will be
879 // removed when the page finishes.
880 showFakeTitleBar();
881 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400882 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700883
Michael Kolba2b2ba82010-08-04 17:54:03 -0700884 void stopScrolling() {
885 ((ScrollWebView) mTabControl.getCurrentWebView()).stopScroll();
886 }
887
888 void hideFakeTitleBar() {
889 if (!isFakeTitleBarShowing()) return;
890 if (mXLargeScreenSize) {
891 mContentView.removeView(mFakeTitleBar);
892 mTabBar.onHideTitleBar();
893 } else {
894 WindowManager.LayoutParams params =
895 (WindowManager.LayoutParams) mFakeTitleBar.getLayoutParams();
896 WebView mainView = mTabControl.getCurrentWebView();
897 // Although we decided whether or not to animate based on the
898 // current
899 // scroll position, the scroll position may have changed since the
900 // fake title bar was displayed. Make sure it has the appropriate
901 // animation/lack thereof before removing.
902 params.windowAnimations =
903 mainView != null && mainView.getScrollY() == 0 ? 0 : R.style.TitleBar;
904 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
905 manager.updateViewLayout(mFakeTitleBar, params);
906 manager.removeView(mFakeTitleBar);
907 }
908 }
909
910 boolean isFakeTitleBarShowing() {
911 return (mFakeTitleBar.getParent() != null);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400912 }
913
The Android Open Source Project0c908882009-03-03 19:32:16 -0800914 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400915 * Special method for the fake title bar to call when displaying its context
916 * menu, since it is in its own Window, and its parent does not show a
917 * context menu.
918 */
919 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400920 if (null == mTitleBar.getParent()) {
921 return;
922 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400923 openContextMenu(mTitleBar);
924 }
925
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400926 @Override
927 public void onContextMenuClosed(Menu menu) {
928 super.onContextMenuClosed(menu);
929 if (mInLoad) {
930 showFakeTitleBar();
931 }
932 }
933
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400934 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800935 * onSaveInstanceState(Bundle map)
936 * onSaveInstanceState is called right before onStop(). The map contains
937 * the saved state.
938 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700939 @Override
940 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700941 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800942 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
943 }
944 // the default implementation requires each view to have an id. As the
945 // browser handles the state itself and it doesn't use id for the views,
946 // don't call the default implementation. Otherwise it will trigger the
947 // warning like this, "couldn't save which view has focus because the
948 // focused view XXX has no id".
949
950 // Save all the tabs
951 mTabControl.saveState(outState);
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700952
953 // Save time so that we know how old incognito tabs (if any) are.
954 outState.putSerializable("lastActiveDate", Calendar.getInstance());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800955 }
956
Grace Kloba22ac16e2009-10-07 18:00:23 -0700957 @Override
958 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800959 super.onPause();
960
961 if (mActivityInPause) {
962 Log.e(LOGTAG, "BrowserActivity is already paused.");
963 return;
964 }
965
Mike Reed7bfa63b2009-05-28 11:08:32 -0400966 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800967 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400968 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800969 mWakeLock.acquire();
970 mHandler.sendMessageDelayed(mHandler
971 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
972 }
973
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400974 // FIXME: This removes the active tabs page and resets the menu to
975 // MAIN_MENU. A better solution might be to do this work in onNewIntent
976 // but then we would need to save it in onSaveInstanceState and restore
977 // it in onCreate/onRestoreInstanceState
978 if (mActiveTabsPage != null) {
979 removeActiveTabPage(true);
980 }
981
The Android Open Source Project0c908882009-03-03 19:32:16 -0800982 cancelStopToast();
983
984 // unregister network state listener
985 unregisterReceiver(mNetworkStateIntentReceiver);
986 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800987 }
988
Grace Kloba22ac16e2009-10-07 18:00:23 -0700989 @Override
990 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700991 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800992 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
993 }
994 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700995
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400996 if (mUploadMessage != null) {
997 mUploadMessage.onReceiveValue(null);
998 mUploadMessage = null;
999 }
1000
Grace Kloba0923d692009-09-23 21:37:25 -07001001 if (mTabControl == null) return;
1002
Grace Kloba1fc98a32009-10-21 13:23:08 -07001003 // Remove the fake title bar if it is there
1004 hideFakeTitleBar();
1005
The Android Open Source Project0c908882009-03-03 19:32:16 -08001006 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001007 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001008 if (t != null) {
1009 dismissSubWindow(t);
1010 removeTabFromContentView(t);
1011 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001012 // Destroy all the tabs
1013 mTabControl.destroy();
1014 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001015
Bjorn Bringerta7611812010-03-24 11:12:02 +00001016 // Stop watching the default geolocation permissions
1017 mSystemAllowGeolocationOrigins.stop();
1018 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001019 }
1020
1021 @Override
1022 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001023 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001024 super.onConfigurationChanged(newConfig);
1025
1026 if (mPageInfoDialog != null) {
1027 mPageInfoDialog.dismiss();
1028 showPageInfo(
1029 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001030 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001031 }
1032 if (mSSLCertificateDialog != null) {
1033 mSSLCertificateDialog.dismiss();
1034 showSSLCertificate(
1035 mSSLCertificateView);
1036 }
1037 if (mSSLCertificateOnErrorDialog != null) {
1038 mSSLCertificateOnErrorDialog.dismiss();
1039 showSSLCertificateOnError(
1040 mSSLCertificateOnErrorView,
1041 mSSLCertificateOnErrorHandler,
1042 mSSLCertificateOnErrorError);
1043 }
1044 if (mHttpAuthenticationDialog != null) {
1045 String title = ((TextView) mHttpAuthenticationDialog
1046 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1047 .toString();
1048 String name = ((TextView) mHttpAuthenticationDialog
1049 .findViewById(R.id.username_edit)).getText().toString();
1050 String password = ((TextView) mHttpAuthenticationDialog
1051 .findViewById(R.id.password_edit)).getText().toString();
1052 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1053 .getId();
1054 mHttpAuthenticationDialog.dismiss();
1055 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1056 name, password, focusId);
1057 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001058 }
1059
Grace Kloba22ac16e2009-10-07 18:00:23 -07001060 @Override
1061 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001062 super.onLowMemory();
1063 mTabControl.freeMemory();
1064 }
1065
Cary Clarkff4d92c2010-03-25 11:17:03 -04001066 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001067 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001068 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001069 boolean inLoad = tab.inLoad();
1070 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001071 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001072 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001073 if (w != null) {
1074 w.resumeTimers();
1075 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001076 }
1077 }
1078
Mike Reed7bfa63b2009-05-28 11:08:32 -04001079 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001080 Tab tab = mTabControl.getCurrentTab();
1081 boolean inLoad = tab.inLoad();
1082 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001083 CookieSyncManager.getInstance().stopSync();
1084 WebView w = mTabControl.getCurrentWebView();
1085 if (w != null) {
1086 w.pauseTimers();
1087 }
1088 return true;
1089 } else {
1090 return false;
1091 }
1092 }
1093
The Android Open Source Project0c908882009-03-03 19:32:16 -08001094 // Open the icon database and retain all the icons for visited sites.
1095 private void retainIconsOnStartup() {
1096 final WebIconDatabase db = WebIconDatabase.getInstance();
1097 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001098 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001099 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001100 c = Browser.getAllBookmarks(mResolver);
1101 if (c.moveToFirst()) {
1102 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1103 do {
1104 String url = c.getString(urlIndex);
1105 db.retainIconForPageUrl(url);
1106 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001107 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001108 } catch (IllegalStateException e) {
1109 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001110 } finally {
1111 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001112 }
1113 }
1114
1115 // Helper method for getting the top window.
1116 WebView getTopWindow() {
1117 return mTabControl.getCurrentTopWebView();
1118 }
1119
Grace Kloba22ac16e2009-10-07 18:00:23 -07001120 TabControl getTabControl() {
1121 return mTabControl;
1122 }
1123
The Android Open Source Project0c908882009-03-03 19:32:16 -08001124 @Override
1125 public boolean onCreateOptionsMenu(Menu menu) {
1126 super.onCreateOptionsMenu(menu);
1127
1128 MenuInflater inflater = getMenuInflater();
1129 inflater.inflate(R.menu.browser, menu);
1130 mMenu = menu;
1131 updateInLoadMenuItems();
1132 return true;
1133 }
1134
1135 /**
1136 * As the menu can be open when loading state changes
1137 * we must manually update the state of the stop/reload menu
1138 * item
1139 */
1140 private void updateInLoadMenuItems() {
1141 if (mMenu == null) {
1142 return;
1143 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001144 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001145 MenuItem src = mInLoad ?
1146 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001147 mMenu.findItem(R.id.reload_menu_id);
1148 if (src != null) {
1149 dest.setIcon(src.getIcon());
1150 dest.setTitle(src.getTitle());
1151 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001152 }
1153
1154 @Override
1155 public boolean onContextItemSelected(MenuItem item) {
1156 // chording is not an issue with context menus, but we use the same
1157 // options selector, so set mCanChord to true so we can access them.
1158 mCanChord = true;
1159 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001160 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001161 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001162 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001163 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001164 Tab currentTab = mTabControl.getCurrentTab();
1165 if (null == currentTab) {
1166 result = false;
1167 break;
1168 }
1169 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001170 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001171 result = false;
1172 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001173 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001174 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001175 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001176 // -- Browser context menu
1177 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001178 case R.id.bookmark_context_menu_id:
1179 case R.id.save_link_context_menu_id:
1180 case R.id.share_link_context_menu_id:
1181 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001182 final WebView webView = getTopWindow();
1183 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001184 result = false;
1185 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001186 }
1187 final HashMap hrefMap = new HashMap();
1188 hrefMap.put("webview", webView);
1189 final Message msg = mHandler.obtainMessage(
1190 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001191 webView.requestFocusNodeHref(msg);
1192 break;
1193
1194 default:
1195 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001196 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001197 }
1198 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001199 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001200 }
1201
1202 private Bundle createGoogleSearchSourceBundle(String source) {
1203 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001204 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001205 return bundle;
1206 }
1207
Leon Scroggins8ad29922010-02-16 12:33:55 -05001208 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001209 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001210 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001211 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001212 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001213 }
1214
Leon Scroggins8ad29922010-02-16 12:33:55 -05001215 /**
1216 * Overriding this to insert a local information bundle
1217 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001218 @Override
1219 public void startSearch(String initialQuery, boolean selectInitialQuery,
1220 Bundle appSearchData, boolean globalSearch) {
1221 if (appSearchData == null) {
1222 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1223 }
1224 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1225 }
1226
Leon Scroggins1f005d32009-08-10 17:36:42 -04001227 /**
1228 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1229 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001230 * @param index Index of the tab to change to, as defined by
1231 * mTabControl.getTabIndex(Tab t).
1232 * @return boolean True if we successfully switched to a different tab. If
1233 * the indexth tab is null, or if that tab is the same as
1234 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001235 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001236 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001237 Tab tab = mTabControl.getTab(index);
1238 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001239 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001240 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001241 }
1242 if (currentTab != null) {
1243 // currentTab may be null if it was just removed. In that case,
1244 // we do not need to remove it
1245 removeTabFromContentView(currentTab);
1246 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001247 mTabControl.setCurrentTab(tab);
1248 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001249 resetTitleIconAndProgress();
1250 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001251 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001252 }
1253
Grace Kloba22ac16e2009-10-07 18:00:23 -07001254 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001255 return openTabAndShow(mSettings.getHomePage(), false, null);
1256 }
1257
Leon Scroggins1f005d32009-08-10 17:36:42 -04001258 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001259 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001260 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001261 // This is the last tab. Open a new one, with the home
1262 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001263 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001264 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001265 return;
1266 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001267 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001268 int indexToShow = -1;
1269 if (parent != null) {
1270 indexToShow = mTabControl.getTabIndex(parent);
1271 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001272 final int currentIndex = mTabControl.getCurrentIndex();
1273 // Try to move to the tab to the right
1274 indexToShow = currentIndex + 1;
1275 if (indexToShow > mTabControl.getTabCount() - 1) {
1276 // Try to move to the tab to the left
1277 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001278 }
1279 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001280 if (switchToTab(indexToShow)) {
1281 // Close window
1282 closeTab(current);
1283 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001284 }
1285
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001286 private ActiveTabsPage mActiveTabsPage;
1287
1288 /**
1289 * Remove the active tabs page.
1290 * @param needToAttach If true, the active tabs page did not attach a tab
1291 * to the content view, so we need to do that here.
1292 */
1293 /* package */ void removeActiveTabPage(boolean needToAttach) {
1294 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001295 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001296 mActiveTabsPage = null;
1297 mMenuState = R.id.MAIN_MENU;
1298 if (needToAttach) {
1299 attachTabToContentView(mTabControl.getCurrentTab());
1300 }
1301 getTopWindow().requestFocus();
1302 }
1303
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001304 @Override
1305 public ActionMode onStartActionMode(ActionMode.Callback callback) {
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001306 mActionMode = super.onStartActionMode(callback);
1307 hideFakeTitleBar();
1308 // Would like to change the MENU, but onEndActionMode may not be called
1309 return mActionMode;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001310 }
1311
The Android Open Source Project0c908882009-03-03 19:32:16 -08001312 @Override
1313 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolbed217742010-08-10 17:52:34 -07001314 // check the action bar button before mCanChord check, as the prepare call
1315 // doesn't come for action bar buttons
1316 if (item.getItemId() == R.id.newtab) {
Michael Kolb300b7f02010-08-25 13:47:24 -07001317 openTabToHomePage();
1318 mHandler.sendMessage(mHandler.obtainMessage(OPEN_BOOKMARKS));
Michael Kolbed217742010-08-10 17:52:34 -07001319 return true;
1320 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001321 if (!mCanChord) {
1322 // The user has already fired a shortcut with this hold down of the
1323 // menu key.
1324 return false;
1325 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001326 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001327 return false;
1328 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001329 if (mMenuIsDown) {
1330 // The shortcut action consumes the MENU. Even if it is still down,
1331 // it won't trigger the next shortcut action. In the case of the
1332 // shortcut action triggering a new activity, like Bookmarks, we
1333 // won't get onKeyUp for MENU. So it is important to reset it here.
1334 mMenuIsDown = false;
1335 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001336 switch (item.getItemId()) {
1337 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001338 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001339 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001340 break;
1341
Michael Kolbae62fd42010-08-18 16:33:28 -07001342 case R.id.incognito_menu_id:
1343 openIncognitoTab();
1344 break;
1345
Leon Scroggins64b80f32009-08-07 12:03:34 -04001346 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001347 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001348 break;
1349
1350 case R.id.bookmarks_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001351 bookmarksOrHistoryPicker(false, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001352 break;
1353
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001354 case R.id.active_tabs_menu_id:
1355 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1356 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001357 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001358 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001359 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1360 mActiveTabsPage.requestFocus();
1361 mMenuState = EMPTY_MENU;
1362 break;
1363
Leon Scroggins1f005d32009-08-10 17:36:42 -04001364 case R.id.add_bookmark_menu_id:
Leon Scroggins571b3762010-05-26 10:25:01 -04001365 bookmarkCurrentPage();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001366 break;
1367
1368 case R.id.stop_reload_menu_id:
1369 if (mInLoad) {
1370 stopLoading();
1371 } else {
1372 getTopWindow().reload();
1373 }
1374 break;
1375
1376 case R.id.back_menu_id:
1377 getTopWindow().goBack();
1378 break;
1379
1380 case R.id.forward_menu_id:
1381 getTopWindow().goForward();
1382 break;
1383
1384 case R.id.close_menu_id:
1385 // Close the subwindow if it exists.
1386 if (mTabControl.getCurrentSubWindow() != null) {
1387 dismissSubWindow(mTabControl.getCurrentTab());
1388 break;
1389 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001390 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001391 break;
1392
1393 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001394 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001395 if (current != null) {
1396 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001397 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001398 }
1399 break;
1400
1401 case R.id.preferences_menu_id:
1402 Intent intent = new Intent(this,
1403 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001404 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1405 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001406 startActivityForResult(intent, PREFERENCES_PAGE);
1407 break;
1408
1409 case R.id.find_menu_id:
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001410 getTopWindow().showFindDialog(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001411 break;
1412
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001413 case R.id.save_webarchive_menu_id:
1414 if (LOGD_ENABLED) {
1415 Log.d(LOGTAG, "Save as Web Archive");
1416 }
1417 String directory = getExternalFilesDir(null).getAbsolutePath() + File.separator;
1418 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1419 @Override
1420 public void onReceiveValue(String value) {
1421 if (value != null) {
1422 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved, Toast.LENGTH_SHORT).show();
1423 } else {
1424 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed, Toast.LENGTH_SHORT).show();
1425 }
1426 }
1427 });
1428 break;
1429
The Android Open Source Project0c908882009-03-03 19:32:16 -08001430 case R.id.page_info_menu_id:
1431 showPageInfo(mTabControl.getCurrentTab(), false);
1432 break;
1433
1434 case R.id.classic_history_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001435 bookmarksOrHistoryPicker(true, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001436 break;
1437
Leon Scroggins96afcb12009-12-10 12:35:56 -05001438 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001439 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001440 Tab currentTab = mTabControl.getCurrentTab();
1441 if (null == currentTab) {
1442 mCanChord = false;
1443 return false;
1444 }
1445 currentTab.populatePickerData();
1446 sharePage(this, currentTab.getTitle(),
1447 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001448 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1449 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001450 break;
1451
1452 case R.id.dump_nav_menu_id:
1453 getTopWindow().debugDump();
1454 break;
1455
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001456 case R.id.dump_counters_menu_id:
1457 getTopWindow().dumpV8Counters();
1458 break;
1459
The Android Open Source Project0c908882009-03-03 19:32:16 -08001460 case R.id.zoom_in_menu_id:
1461 getTopWindow().zoomIn();
1462 break;
1463
1464 case R.id.zoom_out_menu_id:
1465 getTopWindow().zoomOut();
1466 break;
1467
1468 case R.id.view_downloads_menu_id:
1469 viewDownloads(null);
1470 break;
1471
The Android Open Source Project0c908882009-03-03 19:32:16 -08001472 case R.id.window_one_menu_id:
1473 case R.id.window_two_menu_id:
1474 case R.id.window_three_menu_id:
1475 case R.id.window_four_menu_id:
1476 case R.id.window_five_menu_id:
1477 case R.id.window_six_menu_id:
1478 case R.id.window_seven_menu_id:
1479 case R.id.window_eight_menu_id:
1480 {
1481 int menuid = item.getItemId();
1482 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1483 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001484 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001485 if (desiredTab != null &&
1486 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001487 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001488 }
1489 break;
1490 }
1491 }
1492 }
1493 break;
1494
1495 default:
1496 if (!super.onOptionsItemSelected(item)) {
1497 return false;
1498 }
1499 // Otherwise fall through.
1500 }
1501 mCanChord = false;
1502 return true;
1503 }
1504
Leon Scroggins571b3762010-05-26 10:25:01 -04001505 /* package */ void bookmarkCurrentPage() {
1506 Intent i = new Intent(BrowserActivity.this,
1507 AddBookmarkPage.class);
1508 WebView w = getTopWindow();
1509 i.putExtra("url", w.getUrl());
1510 i.putExtra("title", w.getTitle());
1511 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001512 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1513 getDesiredThumbnailHeight(this)));
Ben Murdocheecb4e62010-07-06 16:30:38 +01001514 i.putExtra("url_editable", false);
Leon Scroggins571b3762010-05-26 10:25:01 -04001515 startActivity(i);
1516 }
1517
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001518 /*
1519 * True if a custom ActionMode (i.e. find or select) is in use.
1520 */
1521 private boolean isInCustomActionMode() {
1522 return mActionMode != null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001523 }
1524
1525 /*
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001526 * End the current ActionMode.
Cary Clark01cfcdd2010-06-04 16:36:45 -04001527 */
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001528 void endActionMode() {
1529 if (mActionMode != null) {
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001530 ActionMode mode = mActionMode;
1531 onEndActionMode();
1532 mode.finish();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001533 }
1534 }
1535
1536 /*
1537 * Called by find and select when they are finished. Replace title bars
1538 * as necessary.
1539 */
1540 public void onEndActionMode() {
1541 if (!isInCustomActionMode()) return;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001542 if (mInLoad) {
1543 // The title bar was hidden, because otherwise it would cover up the
Michael Kolba2b2ba82010-08-04 17:54:03 -07001544 // find or select dialog. Now that the dialog has been removed,
Cary Clark01cfcdd2010-06-04 16:36:45 -04001545 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001546 showFakeTitleBar();
1547 }
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001548 // Would like to return the menu state to normal, but this does not
1549 // necessarily get called.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001550 mActionMode = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001551 }
1552
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001553 // For select and find, we keep track of the ActionMode so that
1554 // finish() can be called as desired.
1555 private ActionMode mActionMode;
1556
Grace Kloba22ac16e2009-10-07 18:00:23 -07001557 @Override
1558 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001559 // This happens when the user begins to hold down the menu key, so
1560 // allow them to chord to get a shortcut.
1561 mCanChord = true;
1562 // Note: setVisible will decide whether an item is visible; while
1563 // setEnabled() will decide whether an item is enabled, which also means
1564 // whether the matching shortcut key will function.
1565 super.onPrepareOptionsMenu(menu);
1566 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001567 case EMPTY_MENU:
1568 if (mCurrentMenuState != mMenuState) {
1569 menu.setGroupVisible(R.id.MAIN_MENU, false);
1570 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1571 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001572 }
1573 break;
1574 default:
1575 if (mCurrentMenuState != mMenuState) {
1576 menu.setGroupVisible(R.id.MAIN_MENU, true);
1577 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1578 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001579 }
1580 final WebView w = getTopWindow();
1581 boolean canGoBack = false;
1582 boolean canGoForward = false;
1583 boolean isHome = false;
1584 if (w != null) {
1585 canGoBack = w.canGoBack();
1586 canGoForward = w.canGoForward();
1587 isHome = mSettings.getHomePage().equals(w.getUrl());
1588 }
1589 final MenuItem back = menu.findItem(R.id.back_menu_id);
1590 back.setEnabled(canGoBack);
1591
1592 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1593 home.setEnabled(!isHome);
1594
Michael Kolbe0a36662010-06-29 10:37:12 -07001595 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1596 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001597
Michael Kolbed217742010-08-10 17:52:34 -07001598 if (!mXLargeScreenSize) {
1599 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1600 newtab.setEnabled(mTabControl.canCreateNewTab());
1601 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001602
The Android Open Source Project0c908882009-03-03 19:32:16 -08001603 // decide whether to show the share link option
1604 PackageManager pm = getPackageManager();
1605 Intent send = new Intent(Intent.ACTION_SEND);
1606 send.setType("text/plain");
1607 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1608 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1609
The Android Open Source Project0c908882009-03-03 19:32:16 -08001610 boolean isNavDump = mSettings.isNavDump();
1611 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1612 nav.setVisible(isNavDump);
1613 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001614
1615 boolean showDebugSettings = mSettings.showDebugSettings();
1616 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1617 counter.setVisible(showDebugSettings);
1618 counter.setEnabled(showDebugSettings);
1619
The Android Open Source Project0c908882009-03-03 19:32:16 -08001620 break;
1621 }
1622 mCurrentMenuState = mMenuState;
1623 return true;
1624 }
1625
1626 @Override
1627 public void onCreateContextMenu(ContextMenu menu, View v,
1628 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001629 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001630 return;
1631 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001632 WebView webview = (WebView) v;
1633 WebView.HitTestResult result = webview.getHitTestResult();
1634 if (result == null) {
1635 return;
1636 }
1637
1638 int type = result.getType();
1639 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1640 Log.w(LOGTAG,
1641 "We should not show context menu when nothing is touched");
1642 return;
1643 }
1644 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1645 // let TextView handles context menu
1646 return;
1647 }
1648
1649 // Note, http://b/issue?id=1106666 is requesting that
1650 // an inflated menu can be used again. This is not available
1651 // yet, so inflate each time (yuk!)
1652 MenuInflater inflater = getMenuInflater();
1653 inflater.inflate(R.menu.browsercontext, menu);
1654
1655 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001656 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001657 menu.setGroupVisible(R.id.PHONE_MENU,
1658 type == WebView.HitTestResult.PHONE_TYPE);
1659 menu.setGroupVisible(R.id.EMAIL_MENU,
1660 type == WebView.HitTestResult.EMAIL_TYPE);
1661 menu.setGroupVisible(R.id.GEO_MENU,
1662 type == WebView.HitTestResult.GEO_TYPE);
1663 menu.setGroupVisible(R.id.IMAGE_MENU,
1664 type == WebView.HitTestResult.IMAGE_TYPE
1665 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1666 menu.setGroupVisible(R.id.ANCHOR_MENU,
1667 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1668 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1669
1670 // Setup custom handling depending on the type
1671 switch (type) {
1672 case WebView.HitTestResult.PHONE_TYPE:
1673 menu.setHeaderTitle(Uri.decode(extra));
1674 menu.findItem(R.id.dial_context_menu_id).setIntent(
1675 new Intent(Intent.ACTION_VIEW, Uri
1676 .parse(WebView.SCHEME_TEL + extra)));
1677 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1678 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001679 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001680 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1681 addIntent);
1682 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1683 new Copy(extra));
1684 break;
1685
1686 case WebView.HitTestResult.EMAIL_TYPE:
1687 menu.setHeaderTitle(extra);
1688 menu.findItem(R.id.email_context_menu_id).setIntent(
1689 new Intent(Intent.ACTION_VIEW, Uri
1690 .parse(WebView.SCHEME_MAILTO + extra)));
1691 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1692 new Copy(extra));
1693 break;
1694
1695 case WebView.HitTestResult.GEO_TYPE:
1696 menu.setHeaderTitle(extra);
1697 menu.findItem(R.id.map_context_menu_id).setIntent(
1698 new Intent(Intent.ACTION_VIEW, Uri
1699 .parse(WebView.SCHEME_GEO
1700 + URLEncoder.encode(extra))));
1701 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1702 new Copy(extra));
1703 break;
1704
1705 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1706 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1707 TextView titleView = (TextView) LayoutInflater.from(this)
1708 .inflate(android.R.layout.browser_link_context_header,
1709 null);
1710 titleView.setText(extra);
1711 menu.setHeaderView(titleView);
1712 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001713 boolean showNewTab = mTabControl.canCreateNewTab();
1714 MenuItem newTabItem
1715 = menu.findItem(R.id.open_newtab_context_menu_id);
1716 newTabItem.setVisible(showNewTab);
1717 if (showNewTab) {
1718 newTabItem.setOnMenuItemClickListener(
1719 new MenuItem.OnMenuItemClickListener() {
1720 public boolean onMenuItemClick(MenuItem item) {
1721 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb68792c82010-08-09 16:39:18 -07001722 final Tab newTab = openTab(extra, false);
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001723 if (newTab != parent) {
1724 parent.addChildTab(newTab);
1725 }
1726 return true;
1727 }
1728 });
1729 }
Ben Murdochde353622009-10-12 10:29:00 +01001730 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1731 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001732 PackageManager pm = getPackageManager();
1733 Intent send = new Intent(Intent.ACTION_SEND);
1734 send.setType("text/plain");
1735 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1736 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1737 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1738 break;
1739 }
1740 // otherwise fall through to handle image part
1741 case WebView.HitTestResult.IMAGE_TYPE:
1742 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1743 menu.setHeaderTitle(extra);
1744 }
1745 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1746 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1747 menu.findItem(R.id.download_context_menu_id).
1748 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001749 menu.findItem(R.id.set_wallpaper_context_menu_id).
1750 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001751 break;
1752
1753 default:
1754 Log.w(LOGTAG, "We should not get here.");
1755 break;
1756 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001757 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001758 }
1759
The Android Open Source Project0c908882009-03-03 19:32:16 -08001760 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001761 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001762 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001763 // Attach the container that contains the main WebView and any other UI
1764 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001765 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001766
1767 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001768 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001769 if (errorConsole.numberOfErrors() == 0) {
1770 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1771 } else {
1772 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1773 }
1774
1775 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001776 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001777 ViewGroup.LayoutParams.WRAP_CONTENT));
1778 }
1779
Michael Kolba2b2ba82010-08-04 17:54:03 -07001780 WebView view = t.getWebView();
1781 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001782 if (t.isInVoiceSearchMode()) {
1783 showVoiceTitleBar(t.getVoiceDisplayTitle());
1784 } else {
1785 revertVoiceTitleBar();
1786 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001787 // Request focus on the top window.
1788 t.getTopWindow().requestFocus();
Michael Kolba2b2ba82010-08-04 17:54:03 -07001789 if (mTabControl.getTabChangeListener() != null) {
1790 mTabControl.getTabChangeListener().onCurrentTab(t);
1791 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001792 }
1793
1794 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001795 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001796 t.attachSubWindow(mContentView);
1797 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001798 }
1799
1800 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001801 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001802 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001803 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001804
Grace Kloba22ac16e2009-10-07 18:00:23 -07001805 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1806 if (errorConsole != null) {
1807 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001808 }
1809
Michael Kolba2b2ba82010-08-04 17:54:03 -07001810 WebView view = t.getWebView();
1811 if (view != null) {
1812 view.setEmbeddedTitleBar(null);
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001813 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001814 }
1815
1816 // Remove the sub window if it exists. Also called by TabControl when the
1817 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001818 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001819 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001820 // dismiss the subwindow. This will destroy the WebView.
1821 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001822 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001823 }
1824
Leon Scroggins1f005d32009-08-10 17:36:42 -04001825 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001826 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001827 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001828 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001829 }
1830
1831 // This method does a ton of stuff. It will attempt to create a new tab
1832 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001833 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001834 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1835 String appId) {
1836 final Tab currentTab = mTabControl.getCurrentTab();
1837 if (mTabControl.canCreateNewTab()) {
1838 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001839 urlData.mUrl, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001840 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001841 // If the last tab was removed from the active tabs page, currentTab
1842 // will be null.
1843 if (currentTab != null) {
1844 removeTabFromContentView(currentTab);
1845 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001846 // We must set the new tab as the current tab to reflect the old
1847 // animation behavior.
1848 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001849 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001850 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001851 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001852 }
1853 return tab;
1854 } else {
1855 // Get rid of the subwindow if it exists
1856 dismissSubWindow(currentTab);
1857 if (!urlData.isEmpty()) {
1858 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001859 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001860 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001861 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001862 }
1863 }
1864
Michael Kolb68792c82010-08-09 16:39:18 -07001865 private Tab openTab(String url, boolean forceForeground) {
1866 if (mSettings.openInBackground() && !forceForeground) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001867 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001868 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001869 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001870 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001871 }
Grace Klobac9181842009-04-14 08:53:22 -07001872 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001873 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001874 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001875 }
1876 }
1877
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001878 /* package */ Tab openIncognitoTab() {
1879 if (mTabControl.canCreateNewTab()) {
1880 Tab currentTab = mTabControl.getCurrentTab();
1881 Tab tab = mTabControl.createNewTab(false, null, null, true);
1882 if (currentTab != null) {
1883 removeTabFromContentView(currentTab);
1884 }
1885 mTabControl.setCurrentTab(tab);
1886 attachTabToContentView(tab);
1887 return tab;
1888 }
1889 return null;
1890 }
1891
The Android Open Source Project0c908882009-03-03 19:32:16 -08001892 private class Copy implements OnMenuItemClickListener {
1893 private CharSequence mText;
1894
1895 public boolean onMenuItemClick(MenuItem item) {
1896 copy(mText);
1897 return true;
1898 }
1899
1900 public Copy(CharSequence toCopy) {
1901 mText = toCopy;
1902 }
1903 }
1904
1905 private class Download implements OnMenuItemClickListener {
1906 private String mText;
1907
1908 public boolean onMenuItemClick(MenuItem item) {
1909 onDownloadStartNoStream(mText, null, null, null, -1);
1910 return true;
1911 }
1912
1913 public Download(String toDownload) {
1914 mText = toDownload;
1915 }
1916 }
1917
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001918 private class SetAsWallpaper extends Thread implements
1919 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1920 private URL mUrl;
1921 private ProgressDialog mWallpaperProgress;
1922 private boolean mCanceled = false;
1923
1924 public SetAsWallpaper(String url) {
1925 try {
1926 mUrl = new URL(url);
1927 } catch (MalformedURLException e) {
1928 mUrl = null;
1929 }
1930 }
1931
1932 public void onCancel(DialogInterface dialog) {
1933 mCanceled = true;
1934 }
1935
1936 public boolean onMenuItemClick(MenuItem item) {
1937 if (mUrl != null) {
1938 // The user may have tried to set a image with a large file size as their
1939 // background so it may take a few moments to perform the operation. Display
1940 // a progress spinner while it is working.
1941 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1942 mWallpaperProgress.setIndeterminate(true);
1943 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1944 mWallpaperProgress.setCancelable(true);
1945 mWallpaperProgress.setOnCancelListener(this);
1946 mWallpaperProgress.show();
1947 start();
1948 }
1949 return true;
1950 }
1951
Michael Kolbe0a36662010-06-29 10:37:12 -07001952 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001953 public void run() {
1954 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1955 try {
1956 // TODO: This will cause the resource to be downloaded again, when we
1957 // should in most cases be able to grab it from the cache. To fix this
1958 // we should query WebCore to see if we can access a cached version and
1959 // instead open an input stream on that. This pattern could also be used
1960 // in the download manager where the same problem exists.
1961 InputStream inputstream = mUrl.openStream();
1962 if (inputstream != null) {
1963 setWallpaper(inputstream);
1964 }
1965 } catch (IOException e) {
1966 Log.e(LOGTAG, "Unable to set new wallpaper");
1967 // Act as though the user canceled the operation so we try to
1968 // restore the old wallpaper.
1969 mCanceled = true;
1970 }
1971
1972 if (mCanceled) {
1973 // Restore the old wallpaper if the user cancelled whilst we were setting
1974 // the new wallpaper.
1975 int width = oldWallpaper.getIntrinsicWidth();
1976 int height = oldWallpaper.getIntrinsicHeight();
1977 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1978 Canvas canvas = new Canvas(bm);
1979 oldWallpaper.setBounds(0, 0, width, height);
1980 oldWallpaper.draw(canvas);
1981 try {
1982 setWallpaper(bm);
1983 } catch (IOException e) {
1984 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1985 }
1986 mCanceled = false;
1987 }
1988
1989 if (mWallpaperProgress.isShowing()) {
1990 mWallpaperProgress.dismiss();
1991 }
1992 }
1993 }
1994
The Android Open Source Project0c908882009-03-03 19:32:16 -08001995 private void copy(CharSequence text) {
Dianne Hackborn80f32622010-08-05 14:17:53 -07001996 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
1997 cm.setText(text);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001998 }
1999
2000 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002001 * Resets the browser title-view to whatever it must be
2002 * (for example, if we had a loading error)
2003 * When we have a new page, we call resetTitle, when we
2004 * have to reset the titlebar to whatever it used to be
2005 * (for example, if the user chose to stop loading), we
2006 * call resetTitleAndRevertLockIcon.
2007 */
2008 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002009 mTabControl.getCurrentTab().revertLockIcon();
2010 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002011 resetTitleIconAndProgress();
2012 }
2013
2014 /**
2015 * Reset the title, favicon, and progress.
2016 */
2017 private void resetTitleIconAndProgress() {
2018 WebView current = mTabControl.getCurrentWebView();
2019 if (current == null) {
2020 return;
2021 }
2022 resetTitleAndIcon(current);
2023 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002024 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002025 }
2026
2027 // Reset the title and the icon based on the given item.
2028 private void resetTitleAndIcon(WebView view) {
2029 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2030 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002031 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002032 setFavicon(item.getFavicon());
2033 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002034 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002035 setFavicon(null);
2036 }
2037 }
2038
2039 /**
2040 * Sets a title composed of the URL and the title string.
2041 * @param url The URL of the site being loaded.
2042 * @param title The title of the site being loaded.
2043 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002044 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002045 mUrl = url;
2046 mTitle = title;
2047
Leon Scroggins58d56c62010-01-28 15:12:40 -05002048 // If we are in voice search mode, the title has already been set.
2049 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2050 mTitleBar.setDisplayTitle(url);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002051 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002052 }
2053
2054 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002055 * @param url The URL to build a title version of the URL from.
2056 * @return The title version of the URL or null if fails.
2057 * The title version of the URL can be either the URL hostname,
2058 * or the hostname with an "https://" prefix (for secure URLs),
2059 * or an empty string if, for example, the URL in question is a
2060 * file:// URL with no hostname.
2061 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002062 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002063 String titleUrl = null;
2064
2065 if (url != null) {
2066 try {
2067 // parse the url string
2068 URL urlObj = new URL(url);
2069 if (urlObj != null) {
2070 titleUrl = "";
2071
2072 String protocol = urlObj.getProtocol();
2073 String host = urlObj.getHost();
2074
2075 if (host != null && 0 < host.length()) {
2076 titleUrl = host;
2077 if (protocol != null) {
2078 // if a secure site, add an "https://" prefix!
2079 if (protocol.equalsIgnoreCase("https")) {
2080 titleUrl = protocol + "://" + host;
2081 }
2082 }
2083 }
2084 }
2085 } catch (MalformedURLException e) {}
2086 }
2087
2088 return titleUrl;
2089 }
2090
2091 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002092 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002093 mTitleBar.setFavicon(icon);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002094 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002095 }
2096
2097 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002098 * Close the tab, remove its associated title bar, and adjust mTabControl's
2099 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002100 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002101 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002102 int currentIndex = mTabControl.getCurrentIndex();
2103 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002104 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002105 if (currentIndex >= removeIndex && currentIndex != 0) {
2106 currentIndex--;
2107 }
2108 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002109 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002110 updateLockIconToLatest();
Elliott Slaughtere440a882010-08-20 13:54:45 -07002111
2112 if (!mTabControl.hasAnyOpenIncognitoTabs()) {
2113 WebView.cleanupPrivateBrowsingFiles(this);
2114 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002115 }
2116
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002117 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002118 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002119 if (current == null) {
2120 /*
2121 * Instead of finishing the activity, simply push this to the back
2122 * of the stack and let ActivityManager to choose the foreground
2123 * activity. As BrowserActivity is singleTask, it will be always the
2124 * root of the task. So we can use either true or false for
2125 * moveTaskToBack().
2126 */
2127 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002128 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002129 }
2130 WebView w = current.getWebView();
2131 if (w.canGoBack()) {
2132 w.goBack();
2133 } else {
2134 // Check to see if we are closing a window that was created by
2135 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002136 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002137 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002138 switchToTab(mTabControl.getTabIndex(parent));
2139 // Now we close the other tab
2140 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002141 } else {
2142 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002143 // force the tab's inLoad() to be false as we are going to
2144 // either finish the activity or remove the tab. This will
2145 // ensure pauseWebViewTimers() taking action.
2146 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002147 if (mTabControl.getTabCount() == 1) {
2148 finish();
2149 return;
2150 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002151 // call pauseWebViewTimers() now, we won't be able to call
2152 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002153 // Temporarily change mActivityInPause to be true as
2154 // pauseWebViewTimers() will do nothing if mActivityInPause
2155 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002156 boolean savedState = mActivityInPause;
2157 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002158 Log.e(LOGTAG, "BrowserActivity is already paused "
2159 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002160 }
2161 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002162 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002163 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002164 removeTabFromContentView(current);
2165 mTabControl.removeTab(current);
2166 }
2167 /*
2168 * Instead of finishing the activity, simply push this to the back
2169 * of the stack and let ActivityManager to choose the foreground
2170 * activity. As BrowserActivity is singleTask, it will be always the
2171 * root of the task. So we can use either true or false for
2172 * moveTaskToBack().
2173 */
2174 moveTaskToBack(true);
2175 }
2176 }
2177 }
2178
Grace Kloba22ac16e2009-10-07 18:00:23 -07002179 boolean isMenuDown() {
2180 return mMenuIsDown;
2181 }
2182
Grace Kloba5942df02009-09-18 11:48:29 -07002183 @Override
2184 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002185 // Even if MENU is already held down, we need to call to super to open
2186 // the IME on long press.
2187 if (KeyEvent.KEYCODE_MENU == keyCode) {
2188 mMenuIsDown = true;
2189 return super.onKeyDown(keyCode, event);
2190 }
Grace Kloba5942df02009-09-18 11:48:29 -07002191 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2192 // still down, we don't want to trigger the search. Pretend to consume
2193 // the key and do nothing.
2194 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002195
Grace Kloba5942df02009-09-18 11:48:29 -07002196 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002197 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002198 // WebView/WebTextView handle the keys in the KeyDown. As
2199 // the Activity's shortcut keys are only handled when WebView
2200 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2201 if (event.isShiftPressed()) {
2202 getTopWindow().pageUp(false);
2203 } else {
2204 getTopWindow().pageDown(false);
2205 }
Grace Kloba5942df02009-09-18 11:48:29 -07002206 return true;
2207 case KeyEvent.KEYCODE_BACK:
2208 if (event.getRepeatCount() == 0) {
2209 event.startTracking();
2210 return true;
2211 } else if (mCustomView == null && mActiveTabsPage == null
2212 && event.isLongPress()) {
Michael Kolb68792c82010-08-09 16:39:18 -07002213 bookmarksOrHistoryPicker(true, false);
Grace Kloba5942df02009-09-18 11:48:29 -07002214 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002215 }
Grace Kloba5942df02009-09-18 11:48:29 -07002216 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002217 }
Grace Kloba5942df02009-09-18 11:48:29 -07002218 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002219 }
2220
Grace Kloba5942df02009-09-18 11:48:29 -07002221 @Override
2222 public boolean onKeyUp(int keyCode, KeyEvent event) {
2223 switch(keyCode) {
2224 case KeyEvent.KEYCODE_MENU:
2225 mMenuIsDown = false;
2226 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002227 case KeyEvent.KEYCODE_BACK:
2228 if (event.isTracking() && !event.isCanceled()) {
2229 if (mCustomView != null) {
2230 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002231 mTabControl.getCurrentWebView().getWebChromeClient()
2232 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002233 } else if (mActiveTabsPage != null) {
2234 // if tab page is showing, hide it
2235 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002236 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002237 WebView subwindow = mTabControl.getCurrentSubWindow();
2238 if (subwindow != null) {
2239 if (subwindow.canGoBack()) {
2240 subwindow.goBack();
2241 } else {
2242 dismissSubWindow(mTabControl.getCurrentTab());
2243 }
2244 } else {
2245 goBackOnePageOrQuit();
2246 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002247 }
Grace Kloba5942df02009-09-18 11:48:29 -07002248 return true;
2249 }
2250 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002251 }
Grace Kloba5942df02009-09-18 11:48:29 -07002252 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002253 }
2254
Leon Scroggins68579392009-09-15 15:31:54 -04002255 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002256 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002257 resetTitleAndRevertLockIcon();
2258 WebView w = getTopWindow();
2259 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002260 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2261 // same logic here. But for subwindow case, should we call into the main
2262 // WebView's onPageFinished as we never call its onPageStarted and if
2263 // the page finishes itself, we don't call onPageFinished.
2264 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2265 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002266
2267 cancelStopToast();
2268 mStopToast = Toast
2269 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2270 mStopToast.show();
2271 }
2272
Grace Kloba22ac16e2009-10-07 18:00:23 -07002273 boolean didUserStopLoading() {
2274 return mDidStopLoad;
2275 }
2276
The Android Open Source Project0c908882009-03-03 19:32:16 -08002277 private void cancelStopToast() {
2278 if (mStopToast != null) {
2279 mStopToast.cancel();
2280 mStopToast = null;
2281 }
2282 }
2283
Grace Kloba22ac16e2009-10-07 18:00:23 -07002284 // called by a UI or non-UI thread to post the message
2285 public void postMessage(int what, int arg1, int arg2, Object obj,
2286 long delayMillis) {
2287 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2288 obj), delayMillis);
2289 }
2290
2291 // called by a UI or non-UI thread to remove the message
2292 void removeMessages(int what, Object object) {
2293 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002294 }
2295
2296 // public message ids
2297 public final static int LOAD_URL = 1001;
2298 public final static int STOP_LOAD = 1002;
2299
2300 // Message Ids
2301 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002302 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002303
Grace Kloba22ac16e2009-10-07 18:00:23 -07002304 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002305
Ben Murdocheecb4e62010-07-06 16:30:38 +01002306 private static final int TOUCH_ICON_DOWNLOADED = 109;
2307
Michael Kolb300b7f02010-08-25 13:47:24 -07002308 private static final int OPEN_BOOKMARKS = 201;
2309
The Android Open Source Project0c908882009-03-03 19:32:16 -08002310 // Private handler for handling javascript and saving passwords
2311 private Handler mHandler = new Handler() {
2312
Michael Kolbe0a36662010-06-29 10:37:12 -07002313 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002314 public void handleMessage(Message msg) {
2315 switch (msg.what) {
Michael Kolb300b7f02010-08-25 13:47:24 -07002316 case OPEN_BOOKMARKS:
2317 bookmarksOrHistoryPicker(false, false);
2318 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002319 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002320 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002321 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002322 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002323 if (url == null || url.length() == 0) {
2324 break;
2325 }
2326 HashMap focusNodeMap = (HashMap) msg.obj;
2327 WebView view = (WebView) focusNodeMap.get("webview");
2328 // Only apply the action if the top window did not change.
2329 if (getTopWindow() != view) {
2330 break;
2331 }
2332 switch (msg.arg1) {
2333 case R.id.open_context_menu_id:
2334 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002335 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002336 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002337 case R.id.bookmark_context_menu_id:
2338 Intent intent = new Intent(BrowserActivity.this,
2339 AddBookmarkPage.class);
2340 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002341 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002342 startActivity(intent);
2343 break;
2344 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002345 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002346 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002347 break;
2348 case R.id.copy_link_context_menu_id:
2349 copy(url);
2350 break;
2351 case R.id.save_link_context_menu_id:
2352 case R.id.download_context_menu_id:
2353 onDownloadStartNoStream(url, null, null, null, -1);
2354 break;
2355 }
2356 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002357 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002358
2359 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002360 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002361 break;
2362
2363 case STOP_LOAD:
2364 stopLoading();
2365 break;
2366
The Android Open Source Project0c908882009-03-03 19:32:16 -08002367 case RELEASE_WAKELOCK:
2368 if (mWakeLock.isHeld()) {
2369 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002370 // if we reach here, Browser should be still in the
2371 // background loading after WAKELOCK_TIMEOUT (5-min).
2372 // To avoid burning the battery, stop loading.
2373 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002374 }
2375 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002376
2377 case UPDATE_BOOKMARK_THUMBNAIL:
2378 WebView view = (WebView) msg.obj;
2379 if (view != null) {
2380 updateScreenshot(view);
2381 }
2382 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002383
2384 case TOUCH_ICON_DOWNLOADED:
2385 Bundle b = msg.getData();
2386 showSaveToHomescreenDialog(b.getString("url"),
2387 b.getString("title"),
2388 (Bitmap) b.getParcelable("touchIcon"),
2389 (Bitmap) b.getParcelable("favicon"));
2390 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002391 }
2392 }
2393 };
2394
Leon Scroggins96afcb12009-12-10 12:35:56 -05002395 /**
2396 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2397 * an {@link Intent} to launch the Activity chooser.
2398 * @param c Context used to launch a new Activity.
2399 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002400 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002401 * @param url URL of the page. Stored in the Intent with
2402 * {@link Intent#EXTRA_TEXT}
2403 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2404 * with {@link Browser#EXTRA_SHARE_FAVICON}
2405 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2406 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2407 */
2408 public static final void sharePage(Context c, String title, String url,
2409 Bitmap favicon, Bitmap screenshot) {
2410 Intent send = new Intent(Intent.ACTION_SEND);
2411 send.setType("text/plain");
2412 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002413 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002414 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2415 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2416 try {
2417 c.startActivity(Intent.createChooser(send, c.getString(
2418 R.string.choosertitle_sharevia)));
2419 } catch(android.content.ActivityNotFoundException ex) {
2420 // if no app handles it, do nothing
2421 }
2422 }
2423
Leon Scroggins89c6d362009-07-15 16:54:37 -04002424 private void updateScreenshot(WebView view) {
2425 // If this is a bookmarked site, add a screenshot to the database.
2426 // FIXME: When should we update? Every time?
2427 // FIXME: Would like to make sure there is actually something to
2428 // draw, but the API for that (WebViewCore.pictureReady()) is not
2429 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002430
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002431 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2432 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002433 if (bm == null) {
2434 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002435 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002436
2437 final ContentResolver cr = getContentResolver();
2438 final String url = view.getUrl();
2439 final String originalUrl = view.getOriginalUrl();
2440
2441 new AsyncTask<Void, Void, Void>() {
2442 @Override
2443 protected Void doInBackground(Void... unused) {
2444 Cursor c = null;
2445 try {
Jeff Hamilton84029622010-08-05 14:29:28 -05002446 c = Bookmarks.queryBookmarksForUrl(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002447 cr, originalUrl, url);
Patrick Scottcb192b52010-04-14 14:38:55 -04002448 if (c != null) {
2449 if (c.moveToFirst()) {
2450 ContentValues values = new ContentValues();
2451 final ByteArrayOutputStream os
2452 = new ByteArrayOutputStream();
2453 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002454 values.put(BrowserContract.Bookmarks.THUMBNAIL,
Patrick Scottcb192b52010-04-14 14:38:55 -04002455 os.toByteArray());
2456 do {
2457 cr.update(ContentUris.withAppendedId(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002458 BrowserContract.Bookmarks.CONTENT_URI, c.getLong(0)),
Patrick Scottcb192b52010-04-14 14:38:55 -04002459 values, null, null);
2460 } while (c.moveToNext());
2461 }
2462 }
2463 } catch (IllegalStateException e) {
2464 // Ignore
2465 } finally {
2466 if (c != null) c.close();
2467 }
2468 return null;
2469 }
2470 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002471 }
2472
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002473 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002474 * Values for the size of the thumbnail created when taking a screenshot.
2475 * Lazily initialized. Instead of using these directly, use
2476 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002477 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002478 private static int THUMBNAIL_WIDTH = 0;
2479 private static int THUMBNAIL_HEIGHT = 0;
2480
2481 /**
2482 * Return the desired width for thumbnail screenshots, which are stored in
2483 * the database, and used on the bookmarks screen.
2484 * @param context Context for finding out the density of the screen.
2485 * @return int desired width for thumbnail screenshot.
2486 */
2487 /* package */ static int getDesiredThumbnailWidth(Context context) {
2488 if (THUMBNAIL_WIDTH == 0) {
2489 float density = context.getResources().getDisplayMetrics().density;
2490 THUMBNAIL_WIDTH = (int) (90 * density);
2491 THUMBNAIL_HEIGHT = (int) (80 * density);
2492 }
2493 return THUMBNAIL_WIDTH;
2494 }
2495
2496 /**
2497 * Return the desired height for thumbnail screenshots, which are stored in
2498 * the database, and used on the bookmarks screen.
2499 * @param context Context for finding out the density of the screen.
2500 * @return int desired height for thumbnail screenshot.
2501 */
2502 /* package */ static int getDesiredThumbnailHeight(Context context) {
2503 // To ensure that they are both initialized.
2504 getDesiredThumbnailWidth(context);
2505 return THUMBNAIL_HEIGHT;
2506 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002507
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002508 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002509 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002510 if (thumbnail == null) {
2511 return null;
2512 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002513 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002514 Canvas canvas = new Canvas(bm);
2515 // May need to tweak these values to determine what is the
2516 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002517 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002518 int thumbnailHeight = thumbnail.getHeight();
2519 float scaleFactorX = 1.0f;
2520 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002521 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002522 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002523 } else {
2524 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002525 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002526
2527 if (view.getWidth() > view.getHeight() &&
2528 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2529 // If the device is in landscape and the page is shorter
2530 // than the height of the view, stretch the thumbnail to fill the
2531 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002532 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002533 } else {
2534 // In the portrait case, this looks nice.
2535 scaleFactorY = scaleFactorX;
2536 }
2537
2538 canvas.scale(scaleFactorX, scaleFactorY);
2539
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002540 thumbnail.draw(canvas);
2541 return bm;
2542 }
2543
The Android Open Source Project0c908882009-03-03 19:32:16 -08002544 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002545 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002546 //-------------------------------------------------------------------------
2547
2548 // Use in overrideUrlLoading
2549 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2550 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2551 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2552 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2553
Leon Scroggins92472e82010-02-17 16:32:28 -05002554 // Keep this initial progress in sync with initialProgressValue (* 100)
2555 // in ProgressTracker.cpp
2556 private final static int INITIAL_PROGRESS = 10;
2557
Grace Kloba22ac16e2009-10-07 18:00:23 -07002558 void onPageStarted(WebView view, String url, Bitmap favicon) {
2559 // when BrowserActivity just starts, onPageStarted may be called before
2560 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2561 // to start the timer. As we won't switch tabs while an activity is in
2562 // pause state, we can ensure calling resume and pause in pair.
2563 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002564
Grace Kloba22ac16e2009-10-07 18:00:23 -07002565 resetLockIcon(url);
2566 setUrlTitle(url, null);
2567 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002568 // Show some progress so that the user knows the page is beginning to
2569 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002570 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002571 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002572 if (!mIsNetworkUp) createAndShowNetworkDialog();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04002573 endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002574 if (mSettings.isTracing()) {
2575 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002576 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002577 WebAddress uri = new WebAddress(url);
2578 host = uri.mHost;
2579 } catch (android.net.ParseException ex) {
2580 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002581 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002582 host = host.replace('.', '_');
2583 host += ".trace";
2584 mInTrace = true;
2585 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2586 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002587
Grace Kloba22ac16e2009-10-07 18:00:23 -07002588 // Performance probe
2589 if (false) {
2590 mStart = SystemClock.uptimeMillis();
2591 mProcessStart = Process.getElapsedCpuTime();
2592 long[] sysCpu = new long[7];
2593 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2594 sysCpu, null)) {
2595 mUserStart = sysCpu[0] + sysCpu[1];
2596 mSystemStart = sysCpu[2];
2597 mIdleStart = sysCpu[3];
2598 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2599 }
2600 mUiStart = SystemClock.currentThreadTimeMillis();
2601 }
2602 }
2603
2604 void onPageFinished(WebView view, String url) {
2605 // Reset the title and icon in case we stopped a provisional load.
2606 resetTitleAndIcon(view);
2607 // Update the lock icon image only once we are done loading
2608 updateLockIconToLatest();
2609 // pause the WebView timer and release the wake lock if it is finished
2610 // while BrowserActivity is in pause state.
2611 if (mActivityInPause && pauseWebViewTimers()) {
2612 if (mWakeLock.isHeld()) {
2613 mHandler.removeMessages(RELEASE_WAKELOCK);
2614 mWakeLock.release();
2615 }
2616 }
2617
2618 // Performance probe
2619 if (false) {
2620 long[] sysCpu = new long[7];
2621 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2622 sysCpu, null)) {
2623 String uiInfo = "UI thread used "
2624 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2625 + " ms";
2626 if (LOGD_ENABLED) {
2627 Log.d(LOGTAG, uiInfo);
2628 }
2629 //The string that gets written to the log
2630 String performanceString = "It took total "
2631 + (SystemClock.uptimeMillis() - mStart)
2632 + " ms clock time to load the page."
2633 + "\nbrowser process used "
2634 + (Process.getElapsedCpuTime() - mProcessStart)
2635 + " ms, user processes used "
2636 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2637 + " ms, kernel used "
2638 + (sysCpu[2] - mSystemStart) * 10
2639 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2640 + " ms and irq took "
2641 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2642 * 10 + " ms, " + uiInfo;
2643 if (LOGD_ENABLED) {
2644 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2645 }
2646 if (url != null) {
2647 // strip the url to maintain consistency
2648 String newUrl = new String(url);
2649 if (newUrl.startsWith("http://www.")) {
2650 newUrl = newUrl.substring(11);
2651 } else if (newUrl.startsWith("http://")) {
2652 newUrl = newUrl.substring(7);
2653 } else if (newUrl.startsWith("https://www.")) {
2654 newUrl = newUrl.substring(12);
2655 } else if (newUrl.startsWith("https://")) {
2656 newUrl = newUrl.substring(8);
2657 }
2658 if (LOGD_ENABLED) {
2659 Log.d(LOGTAG, newUrl + " loaded");
2660 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002661 }
2662 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002663 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002664
Grace Kloba22ac16e2009-10-07 18:00:23 -07002665 if (mInTrace) {
2666 mInTrace = false;
2667 Debug.stopMethodTracing();
2668 }
2669 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002670
Grace Klobae7fe26b2010-06-28 16:23:33 -07002671 private void closeEmptyChildTab() {
2672 Tab current = mTabControl.getCurrentTab();
2673 if (current != null
2674 && current.getWebView().copyBackForwardList().getSize() == 0) {
2675 Tab parent = current.getParentTab();
2676 if (parent != null) {
2677 switchToTab(mTabControl.getTabIndex(parent));
2678 closeTab(current);
2679 }
2680 }
2681 }
2682
Grace Kloba22ac16e2009-10-07 18:00:23 -07002683 boolean shouldOverrideUrlLoading(WebView view, String url) {
2684 if (url.startsWith(SCHEME_WTAI)) {
2685 // wtai://wp/mc;number
2686 // number=string(phone-number)
2687 if (url.startsWith(SCHEME_WTAI_MC)) {
2688 Intent intent = new Intent(Intent.ACTION_VIEW,
2689 Uri.parse(WebView.SCHEME_TEL +
2690 url.substring(SCHEME_WTAI_MC.length())));
2691 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002692 // before leaving BrowserActivity, close the empty child tab.
2693 // If a new tab is created through JavaScript open to load this
2694 // url, we would like to close it as we will load this url in a
2695 // different Activity.
2696 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002697 return true;
2698 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002699 // wtai://wp/sd;dtmf
2700 // dtmf=string(dialstring)
2701 if (url.startsWith(SCHEME_WTAI_SD)) {
2702 // TODO: only send when there is active voice connection
2703 return false;
2704 }
2705 // wtai://wp/ap;number;name
2706 // number=string(phone-number)
2707 // name=string
2708 if (url.startsWith(SCHEME_WTAI_AP)) {
2709 // TODO
2710 return false;
2711 }
2712 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002713
Grace Kloba22ac16e2009-10-07 18:00:23 -07002714 // The "about:" schemes are internal to the browser; don't want these to
2715 // be dispatched to other apps.
2716 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002717 return false;
2718 }
2719
Jeff Davidson43610292010-07-16 16:03:58 -07002720 // If this is a Google search, attempt to add an RLZ string (if one isn't already present).
2721 if (rlzProviderPresent()) {
2722 Uri siteUri = Uri.parse(url);
2723 if (needsRlzString(siteUri)) {
2724 String rlz = null;
2725 Cursor cur = null;
2726 try {
2727 cur = getContentResolver().query(getRlzUri(), null, null, null, null);
2728 if (cur != null && cur.moveToFirst() && !cur.isNull(0)) {
2729 url = siteUri.buildUpon()
2730 .appendQueryParameter("rlz", cur.getString(0))
2731 .build().toString();
2732 }
2733 } finally {
2734 if (cur != null) {
2735 cur.close();
2736 }
2737 }
2738 loadUrl(view, url);
2739 return true;
2740 }
2741 }
2742
Grace Kloba22ac16e2009-10-07 18:00:23 -07002743 Intent intent;
2744 // perform generic parsing of the URI to turn it into an Intent.
2745 try {
2746 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2747 } catch (URISyntaxException ex) {
2748 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2749 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002750 }
2751
Grace Kloba22ac16e2009-10-07 18:00:23 -07002752 // check whether the intent can be resolved. If not, we will see
2753 // whether we can download it from the Market.
2754 if (getPackageManager().resolveActivity(intent, 0) == null) {
2755 String packagename = intent.getPackage();
2756 if (packagename != null) {
2757 intent = new Intent(Intent.ACTION_VIEW, Uri
2758 .parse("market://search?q=pname:" + packagename));
2759 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2760 startActivity(intent);
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();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002766 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002767 } else {
2768 return false;
2769 }
2770 }
2771
Grace Kloba22ac16e2009-10-07 18:00:23 -07002772 // sanitize the Intent, ensuring web pages can not bypass browser
2773 // security (only access to BROWSABLE activities).
2774 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2775 intent.setComponent(null);
2776 try {
2777 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002778 // before leaving BrowserActivity, close the empty child tab.
2779 // If a new tab is created through JavaScript open to load this
2780 // url, we would like to close it as we will load this url in a
2781 // different Activity.
2782 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002783 return true;
2784 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002785 } catch (ActivityNotFoundException ex) {
2786 // ignore the error. If no application can handle the URL,
2787 // eg about:blank, assume the browser can handle it.
2788 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002789
Grace Kloba22ac16e2009-10-07 18:00:23 -07002790 if (mMenuIsDown) {
Michael Kolb68792c82010-08-09 16:39:18 -07002791 openTab(url, false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002792 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002793 return true;
2794 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002795 return false;
2796 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002797
Jeff Davidson43610292010-07-16 16:03:58 -07002798 // Determine whether the RLZ provider is present on the system.
2799 private boolean rlzProviderPresent() {
2800 if (mIsProviderPresent == null) {
2801 PackageManager pm = getPackageManager();
2802 mIsProviderPresent = pm.resolveContentProvider(BrowserSettings.RLZ_PROVIDER, 0) != null;
2803 }
2804 return mIsProviderPresent;
2805 }
2806
2807 // Retrieve the RLZ access point string and cache the URI used to retrieve RLZ values.
2808 private Uri getRlzUri() {
2809 if (mRlzUri == null) {
2810 String ap = getResources().getString(R.string.rlz_access_point);
2811 mRlzUri = Uri.withAppendedPath(BrowserSettings.RLZ_PROVIDER_URI, ap);
2812 }
2813 return mRlzUri;
2814 }
2815
2816 // Determine if this URI appears to be for a Google search and does not have an RLZ parameter.
2817 // Taken largely from Chrome source, src/chrome/browser/google_url_tracker.cc
2818 private static boolean needsRlzString(Uri uri) {
Bill Napierc50e71a2010-08-27 14:03:03 -07002819 String scheme = uri.getScheme();
2820 if (("http".equals(scheme) || "https".equals(scheme)) &&
2821 (uri.getQueryParameter("q") != null) && (uri.getQueryParameter("rlz") == null)) {
Jeff Davidson43610292010-07-16 16:03:58 -07002822 String host = uri.getHost();
2823 if (host == null) {
2824 return false;
2825 }
2826 String[] hostComponents = host.split("\\.");
2827
2828 if (hostComponents.length < 2) {
2829 return false;
2830 }
2831 int googleComponent = hostComponents.length - 2;
2832 String component = hostComponents[googleComponent];
2833 if (!"google".equals(component)) {
2834 if (hostComponents.length < 3 ||
2835 (!"co".equals(component) && !"com".equals(component))) {
2836 return false;
2837 }
2838 googleComponent = hostComponents.length - 3;
2839 if (!"google".equals(hostComponents[googleComponent])) {
2840 return false;
2841 }
2842 }
2843
2844 // Google corp network handling.
2845 if (googleComponent > 0 && "corp".equals(hostComponents[googleComponent - 1])) {
2846 return false;
2847 }
2848
2849 return true;
2850 }
2851 return false;
2852 }
2853
Grace Kloba22ac16e2009-10-07 18:00:23 -07002854 // -------------------------------------------------------------------------
2855 // Helper function for WebChromeClient
2856 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002857
Grace Kloba22ac16e2009-10-07 18:00:23 -07002858 void onProgressChanged(WebView view, int newProgress) {
Michael Kolba2b2ba82010-08-04 17:54:03 -07002859
2860 // On the phone, the fake title bar will always cover up the
2861 // regular title bar (or the regular one is offscreen), so only the
2862 // fake title bar needs to change its progress
2863 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002864
Grace Kloba22ac16e2009-10-07 18:00:23 -07002865 if (newProgress == 100) {
2866 // onProgressChanged() may continue to be called after the main
2867 // frame has finished loading, as any remaining sub frames continue
2868 // to load. We'll only get called once though with newProgress as
2869 // 100 when everything is loaded. (onPageFinished is called once
2870 // when the main frame completes loading regardless of the state of
2871 // any sub frames so calls to onProgressChanges may continue after
2872 // onPageFinished has executed)
2873 if (mInLoad) {
2874 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002875 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002876 // If the options menu is open, leave the title bar
2877 if (!mOptionsMenuOpen || !mIconView) {
2878 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002879 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002880 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002881 } else {
2882 if (!mInLoad) {
2883 // onPageFinished may have already been called but a subframe is
2884 // still loading and updating the progress. Reset mInLoad and
2885 // update the menu items.
2886 mInLoad = true;
2887 updateInLoadMenuItems();
2888 }
2889 // When the page first begins to load, the Activity may still be
2890 // paused, in which case showFakeTitleBar will do nothing. Call
2891 // again as the page continues to load so that it will be shown.
2892 // (Calling it will the fake title bar is already showing will also
2893 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002894 if (!mOptionsMenuOpen || mIconView) {
2895 // This page has begun to load, so show the title bar
2896 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002897 }
2898 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002899 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002900
Grace Kloba22ac16e2009-10-07 18:00:23 -07002901 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002902 // if a view already exists then immediately terminate the new one
2903 if (mCustomView != null) {
2904 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002905 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002906 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002907
2908 // Add the custom view to its container.
2909 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2910 mCustomView = view;
2911 mCustomViewCallback = callback;
2912 // Save the menu state and set it to empty while the custom
2913 // view is showing.
2914 mOldMenuState = mMenuState;
2915 mMenuState = EMPTY_MENU;
2916 // Hide the content view.
2917 mContentView.setVisibility(View.GONE);
2918 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002919 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002920 mCustomViewContainer.setVisibility(View.VISIBLE);
2921 mCustomViewContainer.bringToFront();
2922 }
2923
2924 void onHideCustomView() {
2925 if (mCustomView == null)
2926 return;
2927
2928 // Hide the custom view.
2929 mCustomView.setVisibility(View.GONE);
2930 // Remove the custom view from its container.
2931 mCustomViewContainer.removeView(mCustomView);
2932 mCustomView = null;
2933 // Reset the old menu state.
2934 mMenuState = mOldMenuState;
2935 mOldMenuState = EMPTY_MENU;
2936 mCustomViewContainer.setVisibility(View.GONE);
2937 mCustomViewCallback.onCustomViewHidden();
2938 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002939 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002940 mContentView.setVisibility(View.VISIBLE);
2941 }
2942
2943 Bitmap getDefaultVideoPoster() {
2944 if (mDefaultVideoPoster == null) {
2945 mDefaultVideoPoster = BitmapFactory.decodeResource(
2946 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002947 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002948 return mDefaultVideoPoster;
2949 }
Patrick Scott3918d442009-08-04 13:22:29 -04002950
Grace Kloba22ac16e2009-10-07 18:00:23 -07002951 View getVideoLoadingProgressView() {
2952 if (mVideoProgressView == null) {
2953 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2954 mVideoProgressView = inflater.inflate(
2955 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002956 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002957 return mVideoProgressView;
2958 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002959
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002960 /*
2961 * The Object used to inform the WebView of the file to upload.
2962 */
2963 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002964 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002965
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002966 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2967
2968 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002969 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01002970 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01002971 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002972 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01002973 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002974 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01002975 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002976
Ben Murdoch039bd472010-07-21 21:26:57 +01002977 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002978 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002979
Ben Murdoch6af492a2010-06-15 12:38:17 +01002980 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002981 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01002982 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
2983 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002984
Ben Murdoch6af492a2010-06-15 12:38:17 +01002985 if (mUploadMessage != null) {
2986 // Already a file picker operation in progress.
2987 return;
2988 }
2989
Grace Kloba22ac16e2009-10-07 18:00:23 -07002990 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002991
2992 // Parse the accept type.
2993 String params[] = acceptType.split(";");
2994 String mimeType = params[0];
2995
2996 for (String p : params) {
2997 String[] keyValue = p.split("=");
2998 if (keyValue.length == 2) {
2999 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003000 if (mediaSourceKey.equals(keyValue[0])) {
3001 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003002 }
3003 }
3004 }
3005
3006 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07003007 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
3008 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003009
3010 // Create an intent to add to the standard file picker that will
3011 // capture an image from the camera. We'll combine this intent with
3012 // the standard OPENABLE picker unless the web developer specifically
3013 // requested the camera or gallery be opened by passing a parameter
3014 // in the accept type.
3015 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
3016 File externalDataDir = Environment.getExternalStoragePublicDirectory(
3017 Environment.DIRECTORY_DCIM);
3018 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
3019 File.separator + "browser-photos");
3020 cameraDataDir.mkdirs();
3021 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
3022 System.currentTimeMillis() + ".jpg";
3023 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
3024
Ben Murdoch6af492a2010-06-15 12:38:17 +01003025 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
3026
Ben Murdoch039bd472010-07-21 21:26:57 +01003027 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
3028
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003029 if (mimeType.equals(imageMimeType)) {
3030 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01003031 addCamcorderIntent = false;
3032 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003033 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
3034 // directly.
3035 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
3036 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003037 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3038 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003039 addCameraIntent = false;
3040 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01003041 } else if (mimeType.equals(videoMimeType)) {
3042 i.setType(videoMimeType);
3043 addCameraIntent = false;
3044 // The camcorder saves it's own file and returns it to us in the intent, so
3045 // we don't need to generate one here.
3046 mCameraFilePath = null;
3047
3048 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01003049 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
3050 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003051 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
3052 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003053 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3054 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003055 addCamcorderIntent = false;
3056 }
Ben Murdoch039bd472010-07-21 21:26:57 +01003057 } else if (mimeType.equals(audioMimeType)) {
3058 i.setType(audioMimeType);
3059 addCameraIntent = false;
3060 addCamcorderIntent = false;
3061 if (mediaSource.equals(mediaSourceValueMicrophone)) {
3062 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
3063 // recorder.
3064 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
3065 return;
3066 }
3067 // On a default system, there is no single option to open an audio "gallery". Both the
3068 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3069 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3070 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003071 } else {
3072 i.setType("*/*");
3073 }
3074
Ben Murdoch6af492a2010-06-15 12:38:17 +01003075 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003076 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3077 chooser.putExtra(Intent.EXTRA_INTENT, i);
3078
Ben Murdoch6af492a2010-06-15 12:38:17 +01003079 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3080
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003081 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003082 extraInitialIntents.add(cameraIntent);
3083 }
3084
3085 if (addCamcorderIntent) {
3086 extraInitialIntents.add(camcorderIntent);
3087 }
3088
3089 if (extraInitialIntents.size() > 0) {
3090 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3091 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003092 }
3093
3094 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3095 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003096 }
3097
3098 // -------------------------------------------------------------------------
3099 // Implement functions for DownloadListener
3100 // -------------------------------------------------------------------------
3101
The Android Open Source Project0c908882009-03-03 19:32:16 -08003102 /**
3103 * Notify the host application a download should be done, or that
3104 * the data should be streamed if a streaming viewer is available.
3105 * @param url The full url to the content that should be downloaded
3106 * @param contentDisposition Content-disposition http header, if
3107 * present.
3108 * @param mimetype The mimetype of the content reported by the server
3109 * @param contentLength The file size reported by the server
3110 */
3111 public void onDownloadStart(String url, String userAgent,
3112 String contentDisposition, String mimetype, long contentLength) {
3113 // if we're dealing wih A/V content that's not explicitly marked
3114 // for download, check if it's streamable.
3115 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003116 || !contentDisposition.regionMatches(
3117 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003118 // query the package manager to see if there's a registered handler
3119 // that matches.
3120 Intent intent = new Intent(Intent.ACTION_VIEW);
3121 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003122 ResolveInfo info = getPackageManager().resolveActivity(intent,
3123 PackageManager.MATCH_DEFAULT_ONLY);
3124 if (info != null) {
3125 ComponentName myName = getComponentName();
3126 // If we resolved to ourselves, we don't want to attempt to
3127 // load the url only to try and download it again.
3128 if (!myName.getPackageName().equals(
3129 info.activityInfo.packageName)
3130 || !myName.getClassName().equals(
3131 info.activityInfo.name)) {
3132 // someone (other than us) knows how to handle this mime
3133 // type with this scheme, don't download.
3134 try {
3135 startActivity(intent);
3136 return;
3137 } catch (ActivityNotFoundException ex) {
3138 if (LOGD_ENABLED) {
3139 Log.d(LOGTAG, "activity not found for " + mimetype
3140 + " over " + Uri.parse(url).getScheme(),
3141 ex);
3142 }
3143 // Best behavior is to fall back to a download in this
3144 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003145 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003146 }
3147 }
3148 }
3149 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3150 }
3151
Kristian Monsenfa52d172010-03-25 18:29:21 +00003152 // This is to work around the fact that java.net.URI throws Exceptions
3153 // instead of just encoding URL's properly
3154 // Helper method for onDownloadStartNoStream
3155 private static String encodePath(String path) {
3156 char[] chars = path.toCharArray();
3157
3158 boolean needed = false;
3159 for (char c : chars) {
3160 if (c == '[' || c == ']') {
3161 needed = true;
3162 break;
3163 }
3164 }
3165 if (needed == false) {
3166 return path;
3167 }
3168
3169 StringBuilder sb = new StringBuilder("");
3170 for (char c : chars) {
3171 if (c == '[' || c == ']') {
3172 sb.append('%');
3173 sb.append(Integer.toHexString(c));
3174 } else {
3175 sb.append(c);
3176 }
3177 }
3178
3179 return sb.toString();
3180 }
3181
The Android Open Source Project0c908882009-03-03 19:32:16 -08003182 /**
3183 * Notify the host application a download should be done, even if there
3184 * is a streaming viewer available for thise type.
3185 * @param url The full url to the content that should be downloaded
3186 * @param contentDisposition Content-disposition http header, if
3187 * present.
3188 * @param mimetype The mimetype of the content reported by the server
3189 * @param contentLength The file size reported by the server
3190 */
3191 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3192 String contentDisposition, String mimetype, long contentLength) {
3193
3194 String filename = URLUtil.guessFileName(url,
3195 contentDisposition, mimetype);
3196
3197 // Check to see if we have an SDCard
3198 String status = Environment.getExternalStorageState();
3199 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3200 int title;
3201 String msg;
3202
3203 // Check to see if the SDCard is busy, same as the music app
3204 if (status.equals(Environment.MEDIA_SHARED)) {
3205 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3206 title = R.string.download_sdcard_busy_dlg_title;
3207 } else {
3208 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3209 title = R.string.download_no_sdcard_dlg_title;
3210 }
3211
3212 new AlertDialog.Builder(this)
3213 .setTitle(title)
3214 .setIcon(android.R.drawable.ic_dialog_alert)
3215 .setMessage(msg)
3216 .setPositiveButton(R.string.ok, null)
3217 .show();
3218 return;
3219 }
3220
Kristian Monsenfa52d172010-03-25 18:29:21 +00003221 // java.net.URI is a lot stricter than KURL so we have to encode some
3222 // extra characters. Fix for b 2538060 and b 1634719
3223 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003224 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003225 webAddress = new WebAddress(url);
3226 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003227 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003228 // This only happens for very bad urls, we want to chatch the
3229 // exception here
3230 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003231 return;
3232 }
3233
3234 // XXX: Have to use the old url since the cookies were stored using the
3235 // old percent-encoded url.
3236 String cookies = CookieManager.getInstance().getCookie(url);
3237
3238 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003239 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003240 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3241 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3242 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003243 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003244 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003245 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003246 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3247 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3248 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3249 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003250 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003251 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003252 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003253 }
3254 if (mimetype == null) {
3255 // We must have long pressed on a link or image to download it. We
3256 // are not sure of the mimetype in this case, so do a head request
3257 new FetchUrlMimeType(this).execute(values);
3258 } else {
3259 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003260 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003261 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003262 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3263 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003264 }
3265
Grace Kloba22ac16e2009-10-07 18:00:23 -07003266 // -------------------------------------------------------------------------
3267
The Android Open Source Project0c908882009-03-03 19:32:16 -08003268 /**
3269 * Resets the lock icon. This method is called when we start a new load and
3270 * know the url to be loaded.
3271 */
3272 private void resetLockIcon(String url) {
3273 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003274 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003275 updateLockIconImage(LOCK_ICON_UNSECURE);
3276 }
3277
The Android Open Source Project0c908882009-03-03 19:32:16 -08003278 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003279 * Update the lock icon to correspond to our latest state.
3280 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003281 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003282 Tab t = mTabControl.getCurrentTab();
3283 if (t != null) {
3284 updateLockIconImage(t.getLockIconType());
3285 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003286 }
3287
3288 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003289 * Updates the lock-icon image in the title-bar.
3290 */
3291 private void updateLockIconImage(int lockIconType) {
3292 Drawable d = null;
3293 if (lockIconType == LOCK_ICON_SECURE) {
3294 d = mSecLockIcon;
3295 } else if (lockIconType == LOCK_ICON_MIXED) {
3296 d = mMixLockIcon;
3297 }
Leon Scroggins68579392009-09-15 15:31:54 -04003298 mTitleBar.setLock(d);
Michael Kolba2b2ba82010-08-04 17:54:03 -07003299 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003300 }
3301
3302 /**
3303 * Displays a page-info dialog.
3304 * @param tab The tab to show info about
3305 * @param fromShowSSLCertificateOnError The flag that indicates whether
3306 * this dialog was opened from the SSL-certificate-on-error dialog or
3307 * not. This is important, since we need to know whether to return to
3308 * the parent dialog or simply dismiss.
3309 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003310 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003311 final boolean fromShowSSLCertificateOnError) {
3312 final LayoutInflater factory = LayoutInflater
3313 .from(this);
3314
3315 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3316
3317 final WebView view = tab.getWebView();
3318
3319 String url = null;
3320 String title = null;
3321
3322 if (view == null) {
3323 url = tab.getUrl();
3324 title = tab.getTitle();
3325 } else if (view == mTabControl.getCurrentWebView()) {
3326 // Use the cached title and url if this is the current WebView
3327 url = mUrl;
3328 title = mTitle;
3329 } else {
3330 url = view.getUrl();
3331 title = view.getTitle();
3332 }
3333
3334 if (url == null) {
3335 url = "";
3336 }
3337 if (title == null) {
3338 title = "";
3339 }
3340
3341 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3342 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3343
3344 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003345 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003346
3347 AlertDialog.Builder alertDialogBuilder =
3348 new AlertDialog.Builder(this)
3349 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3350 .setView(pageInfoView)
3351 .setPositiveButton(
3352 R.string.ok,
3353 new DialogInterface.OnClickListener() {
3354 public void onClick(DialogInterface dialog,
3355 int whichButton) {
3356 mPageInfoDialog = null;
3357 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003358
3359 // if we came here from the SSL error dialog
3360 if (fromShowSSLCertificateOnError) {
3361 // go back to the SSL error dialog
3362 showSSLCertificateOnError(
3363 mSSLCertificateOnErrorView,
3364 mSSLCertificateOnErrorHandler,
3365 mSSLCertificateOnErrorError);
3366 }
3367 }
3368 })
3369 .setOnCancelListener(
3370 new DialogInterface.OnCancelListener() {
3371 public void onCancel(DialogInterface dialog) {
3372 mPageInfoDialog = null;
3373 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003374
3375 // if we came here from the SSL error dialog
3376 if (fromShowSSLCertificateOnError) {
3377 // go back to the SSL error dialog
3378 showSSLCertificateOnError(
3379 mSSLCertificateOnErrorView,
3380 mSSLCertificateOnErrorHandler,
3381 mSSLCertificateOnErrorError);
3382 }
3383 }
3384 });
3385
3386 // if we have a main top-level page SSL certificate set or a certificate
3387 // error
3388 if (fromShowSSLCertificateOnError ||
3389 (view != null && view.getCertificate() != null)) {
3390 // add a 'View Certificate' button
3391 alertDialogBuilder.setNeutralButton(
3392 R.string.view_certificate,
3393 new DialogInterface.OnClickListener() {
3394 public void onClick(DialogInterface dialog,
3395 int whichButton) {
3396 mPageInfoDialog = null;
3397 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003398
3399 // if we came here from the SSL error dialog
3400 if (fromShowSSLCertificateOnError) {
3401 // go back to the SSL error dialog
3402 showSSLCertificateOnError(
3403 mSSLCertificateOnErrorView,
3404 mSSLCertificateOnErrorHandler,
3405 mSSLCertificateOnErrorError);
3406 } else {
3407 // otherwise, display the top-most certificate from
3408 // the chain
3409 if (view.getCertificate() != null) {
3410 showSSLCertificate(tab);
3411 }
3412 }
3413 }
3414 });
3415 }
3416
3417 mPageInfoDialog = alertDialogBuilder.show();
3418 }
3419
3420 /**
3421 * Displays the main top-level page SSL certificate dialog
3422 * (accessible from the Page-Info dialog).
3423 * @param tab The tab to show certificate for.
3424 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003425 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003426 final View certificateView =
3427 inflateCertificateView(tab.getWebView().getCertificate());
3428 if (certificateView == null) {
3429 return;
3430 }
3431
3432 LayoutInflater factory = LayoutInflater.from(this);
3433
3434 final LinearLayout placeholder =
3435 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3436
3437 LinearLayout ll = (LinearLayout) factory.inflate(
3438 R.layout.ssl_success, placeholder);
3439 ((TextView)ll.findViewById(R.id.success))
3440 .setText(R.string.ssl_certificate_is_valid);
3441
3442 mSSLCertificateView = tab;
3443 mSSLCertificateDialog =
3444 new AlertDialog.Builder(this)
3445 .setTitle(R.string.ssl_certificate).setIcon(
3446 R.drawable.ic_dialog_browser_certificate_secure)
3447 .setView(certificateView)
3448 .setPositiveButton(R.string.ok,
3449 new DialogInterface.OnClickListener() {
3450 public void onClick(DialogInterface dialog,
3451 int whichButton) {
3452 mSSLCertificateDialog = null;
3453 mSSLCertificateView = null;
3454
3455 showPageInfo(tab, false);
3456 }
3457 })
3458 .setOnCancelListener(
3459 new DialogInterface.OnCancelListener() {
3460 public void onCancel(DialogInterface dialog) {
3461 mSSLCertificateDialog = null;
3462 mSSLCertificateView = null;
3463
3464 showPageInfo(tab, false);
3465 }
3466 })
3467 .show();
3468 }
3469
3470 /**
3471 * Displays the SSL error certificate dialog.
3472 * @param view The target web-view.
3473 * @param handler The SSL error handler responsible for cancelling the
3474 * connection that resulted in an SSL error or proceeding per user request.
3475 * @param error The SSL error object.
3476 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003477 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003478 final WebView view, final SslErrorHandler handler, final SslError error) {
3479
3480 final View certificateView =
3481 inflateCertificateView(error.getCertificate());
3482 if (certificateView == null) {
3483 return;
3484 }
3485
3486 LayoutInflater factory = LayoutInflater.from(this);
3487
3488 final LinearLayout placeholder =
3489 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3490
3491 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3492 LinearLayout ll = (LinearLayout)factory
3493 .inflate(R.layout.ssl_warning, placeholder);
3494 ((TextView)ll.findViewById(R.id.warning))
3495 .setText(R.string.ssl_untrusted);
3496 }
3497
3498 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3499 LinearLayout ll = (LinearLayout)factory
3500 .inflate(R.layout.ssl_warning, placeholder);
3501 ((TextView)ll.findViewById(R.id.warning))
3502 .setText(R.string.ssl_mismatch);
3503 }
3504
3505 if (error.hasError(SslError.SSL_EXPIRED)) {
3506 LinearLayout ll = (LinearLayout)factory
3507 .inflate(R.layout.ssl_warning, placeholder);
3508 ((TextView)ll.findViewById(R.id.warning))
3509 .setText(R.string.ssl_expired);
3510 }
3511
3512 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3513 LinearLayout ll = (LinearLayout)factory
3514 .inflate(R.layout.ssl_warning, placeholder);
3515 ((TextView)ll.findViewById(R.id.warning))
3516 .setText(R.string.ssl_not_yet_valid);
3517 }
3518
3519 mSSLCertificateOnErrorHandler = handler;
3520 mSSLCertificateOnErrorView = view;
3521 mSSLCertificateOnErrorError = error;
3522 mSSLCertificateOnErrorDialog =
3523 new AlertDialog.Builder(this)
3524 .setTitle(R.string.ssl_certificate).setIcon(
3525 R.drawable.ic_dialog_browser_certificate_partially_secure)
3526 .setView(certificateView)
3527 .setPositiveButton(R.string.ok,
3528 new DialogInterface.OnClickListener() {
3529 public void onClick(DialogInterface dialog,
3530 int whichButton) {
3531 mSSLCertificateOnErrorDialog = null;
3532 mSSLCertificateOnErrorView = null;
3533 mSSLCertificateOnErrorHandler = null;
3534 mSSLCertificateOnErrorError = null;
3535
Grace Kloba22ac16e2009-10-07 18:00:23 -07003536 view.getWebViewClient().onReceivedSslError(
3537 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003538 }
3539 })
3540 .setNeutralButton(R.string.page_info_view,
3541 new DialogInterface.OnClickListener() {
3542 public void onClick(DialogInterface dialog,
3543 int whichButton) {
3544 mSSLCertificateOnErrorDialog = null;
3545
3546 // do not clear the dialog state: we will
3547 // need to show the dialog again once the
3548 // user is done exploring the page-info details
3549
3550 showPageInfo(mTabControl.getTabFromView(view),
3551 true);
3552 }
3553 })
3554 .setOnCancelListener(
3555 new DialogInterface.OnCancelListener() {
3556 public void onCancel(DialogInterface dialog) {
3557 mSSLCertificateOnErrorDialog = null;
3558 mSSLCertificateOnErrorView = null;
3559 mSSLCertificateOnErrorHandler = null;
3560 mSSLCertificateOnErrorError = null;
3561
Grace Kloba22ac16e2009-10-07 18:00:23 -07003562 view.getWebViewClient().onReceivedSslError(
3563 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003564 }
3565 })
3566 .show();
3567 }
3568
3569 /**
3570 * Inflates the SSL certificate view (helper method).
3571 * @param certificate The SSL certificate.
3572 * @return The resultant certificate view with issued-to, issued-by,
3573 * issued-on, expires-on, and possibly other fields set.
3574 * If the input certificate is null, returns null.
3575 */
3576 private View inflateCertificateView(SslCertificate certificate) {
3577 if (certificate == null) {
3578 return null;
3579 }
3580
3581 LayoutInflater factory = LayoutInflater.from(this);
3582
3583 View certificateView = factory.inflate(
3584 R.layout.ssl_certificate, null);
3585
3586 // issued to:
3587 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3588 if (issuedTo != null) {
3589 ((TextView) certificateView.findViewById(R.id.to_common))
3590 .setText(issuedTo.getCName());
3591 ((TextView) certificateView.findViewById(R.id.to_org))
3592 .setText(issuedTo.getOName());
3593 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3594 .setText(issuedTo.getUName());
3595 }
3596
3597 // issued by:
3598 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3599 if (issuedBy != null) {
3600 ((TextView) certificateView.findViewById(R.id.by_common))
3601 .setText(issuedBy.getCName());
3602 ((TextView) certificateView.findViewById(R.id.by_org))
3603 .setText(issuedBy.getOName());
3604 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3605 .setText(issuedBy.getUName());
3606 }
3607
3608 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003609 String issuedOn = formatCertificateDate(
3610 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003611 ((TextView) certificateView.findViewById(R.id.issued_on))
3612 .setText(issuedOn);
3613
3614 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003615 String expiresOn = formatCertificateDate(
3616 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003617 ((TextView) certificateView.findViewById(R.id.expires_on))
3618 .setText(expiresOn);
3619
3620 return certificateView;
3621 }
3622
3623 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003624 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003625 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003626 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003627 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003628 private String formatCertificateDate(Date certificateDate) {
3629 if (certificateDate == null) {
3630 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003631 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003632 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3633 if (formattedDate == null) {
3634 return "";
3635 }
3636 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003637 }
3638
3639 /**
3640 * Displays an http-authentication dialog.
3641 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003642 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003643 final String host, final String realm, final String title,
3644 final String name, final String password, int focusId) {
3645 LayoutInflater factory = LayoutInflater.from(this);
3646 final View v = factory
3647 .inflate(R.layout.http_authentication, null);
3648 if (name != null) {
3649 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3650 }
3651 if (password != null) {
3652 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3653 }
3654
3655 String titleText = title;
3656 if (titleText == null) {
3657 titleText = getText(R.string.sign_in_to).toString().replace(
3658 "%s1", host).replace("%s2", realm);
3659 }
3660
3661 mHttpAuthHandler = handler;
3662 AlertDialog dialog = new AlertDialog.Builder(this)
3663 .setTitle(titleText)
3664 .setIcon(android.R.drawable.ic_dialog_alert)
3665 .setView(v)
3666 .setPositiveButton(R.string.action,
3667 new DialogInterface.OnClickListener() {
3668 public void onClick(DialogInterface dialog,
3669 int whichButton) {
3670 String nm = ((EditText) v
3671 .findViewById(R.id.username_edit))
3672 .getText().toString();
3673 String pw = ((EditText) v
3674 .findViewById(R.id.password_edit))
3675 .getText().toString();
3676 BrowserActivity.this.setHttpAuthUsernamePassword
3677 (host, realm, nm, pw);
3678 handler.proceed(nm, pw);
3679 mHttpAuthenticationDialog = null;
3680 mHttpAuthHandler = null;
3681 }})
3682 .setNegativeButton(R.string.cancel,
3683 new DialogInterface.OnClickListener() {
3684 public void onClick(DialogInterface dialog,
3685 int whichButton) {
3686 handler.cancel();
3687 BrowserActivity.this.resetTitleAndRevertLockIcon();
3688 mHttpAuthenticationDialog = null;
3689 mHttpAuthHandler = null;
3690 }})
3691 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3692 public void onCancel(DialogInterface dialog) {
3693 handler.cancel();
3694 BrowserActivity.this.resetTitleAndRevertLockIcon();
3695 mHttpAuthenticationDialog = null;
3696 mHttpAuthHandler = null;
3697 }})
3698 .create();
3699 // Make the IME appear when the dialog is displayed if applicable.
3700 dialog.getWindow().setSoftInputMode(
3701 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3702 dialog.show();
3703 if (focusId != 0) {
3704 dialog.findViewById(focusId).requestFocus();
3705 } else {
3706 v.findViewById(R.id.username_edit).requestFocus();
3707 }
3708 mHttpAuthenticationDialog = dialog;
3709 }
3710
3711 public int getProgress() {
3712 WebView w = mTabControl.getCurrentWebView();
3713 if (w != null) {
3714 return w.getProgress();
3715 } else {
3716 return 100;
3717 }
3718 }
3719
3720 /**
3721 * Set HTTP authentication password.
3722 *
3723 * @param host The host for the password
3724 * @param realm The realm for the password
3725 * @param username The username for the password. If it is null, it means
3726 * password can't be saved.
3727 * @param password The password
3728 */
3729 public void setHttpAuthUsernamePassword(String host, String realm,
3730 String username,
3731 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003732 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003733 if (w != null) {
3734 w.setHttpAuthUsernamePassword(host, realm, username, password);
3735 }
3736 }
3737
3738 /**
3739 * connectivity manager says net has come or gone... inform the user
3740 * @param up true if net has come up, false if net has gone down
3741 */
3742 public void onNetworkToggle(boolean up) {
3743 if (up == mIsNetworkUp) {
3744 return;
3745 } else if (up) {
3746 mIsNetworkUp = true;
3747 if (mAlertDialog != null) {
3748 mAlertDialog.cancel();
3749 mAlertDialog = null;
3750 }
3751 } else {
3752 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003753 if (mInLoad) {
3754 createAndShowNetworkDialog();
3755 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003756 }
3757 WebView w = mTabControl.getCurrentWebView();
3758 if (w != null) {
3759 w.setNetworkAvailable(up);
3760 }
3761 }
3762
Grace Kloba22ac16e2009-10-07 18:00:23 -07003763 boolean isNetworkUp() {
3764 return mIsNetworkUp;
3765 }
3766
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003767 // This method shows the network dialog alerting the user that the net is
3768 // down. It will only show the dialog if mAlertDialog is null.
3769 private void createAndShowNetworkDialog() {
3770 if (mAlertDialog == null) {
3771 mAlertDialog = new AlertDialog.Builder(this)
3772 .setTitle(R.string.loadSuspendedTitle)
3773 .setMessage(R.string.loadSuspended)
3774 .setPositiveButton(R.string.ok, null)
3775 .show();
3776 }
3777 }
3778
The Android Open Source Project0c908882009-03-03 19:32:16 -08003779 @Override
3780 protected void onActivityResult(int requestCode, int resultCode,
3781 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003782 if (getTopWindow() == null) return;
3783
The Android Open Source Project0c908882009-03-03 19:32:16 -08003784 switch (requestCode) {
3785 case COMBO_PAGE:
3786 if (resultCode == RESULT_OK && intent != null) {
3787 String data = intent.getAction();
3788 Bundle extras = intent.getExtras();
Michael Kolb300b7f02010-08-25 13:47:24 -07003789 if (extras != null &&
3790 extras.getBoolean(
3791 CombinedBookmarkHistoryActivity.EXTRA_OPEN_NEW_WINDOW,
3792 false)) {
Michael Kolb68792c82010-08-09 16:39:18 -07003793 openTab(data, false);
3794 } else if ((extras != null) &&
3795 extras.getBoolean(CombinedBookmarkHistoryActivity.NEWTAB_MODE)) {
3796 openTab(data, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003797 } else {
Michael Kolb68792c82010-08-09 16:39:18 -07003798 final Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003799 dismissSubWindow(currentTab);
3800 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003801 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003802 }
3803 }
Michael Kolb3f65c382010-08-20 15:31:16 -07003804 } else if (resultCode == RESULT_CANCELED) {
3805 if (intent != null) {
3806 float evtx = intent.getFloatExtra(CombinedBookmarkHistoryActivity.EVT_X, -1);
3807 float evty = intent.getFloatExtra(CombinedBookmarkHistoryActivity.EVT_Y, -1);
3808 long now = System.currentTimeMillis();
3809 MotionEvent evt = MotionEvent.obtain(now, now,
3810 MotionEvent.ACTION_DOWN, evtx, evty, 0);
3811 dispatchTouchEvent(evt);
3812 MotionEvent up = MotionEvent.obtain(evt);
3813 up.setAction(MotionEvent.ACTION_UP);
3814 dispatchTouchEvent(up);
3815 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003816 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003817 // Deliberately fall through to PREFERENCES_PAGE, since the
3818 // same extra may be attached to the COMBO_PAGE
3819 case PREFERENCES_PAGE:
3820 if (resultCode == RESULT_OK && intent != null) {
3821 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3822 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3823 mTabControl.removeParentChildRelationShips();
3824 }
3825 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003826 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003827 // Choose a file from the file picker.
3828 case FILE_SELECTED:
3829 if (null == mUploadMessage) break;
3830 Uri result = intent == null || resultCode != RESULT_OK ? null
3831 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003832
3833 // As we ask the camera to save the result of the user taking
3834 // a picture, the camera application does not return anything other
3835 // than RESULT_OK. So we need to check whether the file we expected
3836 // was written to disk in the in the case that we
3837 // did not get an intent returned but did get a RESULT_OK. If it was,
3838 // we assume that this result has came back from the camera.
3839 if (result == null && intent == null && resultCode == RESULT_OK) {
3840 File cameraFile = new File(mCameraFilePath);
3841 if (cameraFile.exists()) {
3842 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003843 // Broadcast to the media scanner that we have a new photo
3844 // so it will be added into the gallery for the user.
3845 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003846 }
3847 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003848 mUploadMessage.onReceiveValue(result);
3849 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003850 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003851 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003852 default:
3853 break;
3854 }
Leon Scroggins30444232009-09-04 18:36:20 -04003855 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003856 }
3857
3858 /*
3859 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003860 * menu to see the download window. It shows the download window on top of
3861 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003862 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003863 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003864 Intent intent = new Intent(this,
3865 BrowserDownloadPage.class);
3866 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003867 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003868
3869 }
3870
Ben Murdocheecb4e62010-07-06 16:30:38 +01003871 /* package*/ void promptAddOrInstallBookmark() {
3872 final Tab current = mTabControl.getCurrentTab();
3873 Resources resources = getResources();
3874 CharSequence[] choices = {
3875 resources.getString(R.string.save_to_bookmarks),
3876 resources.getString(R.string.create_shortcut_bookmark)
3877 };
3878
3879 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3880 builder.setTitle(R.string.add_new_bookmark);
3881 builder.setItems(choices, new DialogInterface.OnClickListener() {
3882 public void onClick(DialogInterface dialog, int item) {
3883 if (item == 0) {
3884 bookmarkCurrentPage();
3885 } else if (item == 1) {
3886 current.populatePickerData();
3887 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3888 if (touchIconUrl != null) {
3889 // Download the touch icon for this site then save it to the
3890 // homescreen.
3891 Bundle b = new Bundle();
3892 b.putString("url", current.getUrl());
3893 b.putString("title", current.getTitle());
3894 b.putParcelable("favicon", current.getFavicon());
3895 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3896 msg.setData(b);
Ben Murdochccb5de02010-07-19 18:38:17 +01003897 new DownloadTouchIcon(BrowserActivity.this, msg,
Ben Murdocheecb4e62010-07-06 16:30:38 +01003898 mTabControl.getCurrentWebView().getSettings()
3899 .getUserAgentString()).execute(touchIconUrl);
3900 } else {
3901 // add to homescreen, can do it immediately as there is no touch
3902 // icon.
3903 showSaveToHomescreenDialog(current.getUrl(), current.getTitle(),
3904 null, current.getFavicon());
3905 }
3906 }
3907 }
3908 });
3909 builder.create().show();
3910 }
3911
Leon Scroggins160a7e72009-08-14 18:28:01 -04003912 /**
3913 * Open the Go page.
3914 * @param startWithHistory If true, open starting on the history tab.
3915 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003916 */
Michael Kolb68792c82010-08-09 16:39:18 -07003917 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory, boolean newTabMode) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003918 WebView current = mTabControl.getCurrentWebView();
3919 if (current == null) {
3920 return;
3921 }
3922 Intent intent = new Intent(this,
3923 CombinedBookmarkHistoryActivity.class);
3924 String title = current.getTitle();
3925 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003926 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3927 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003928
The Android Open Source Project0c908882009-03-03 19:32:16 -08003929 // Just in case the user opens bookmarks before a page finishes loading
3930 // so the current history item, and therefore the page, is null.
3931 if (null == url) {
3932 url = mLastEnteredUrl;
3933 // This can happen.
3934 if (null == url) {
3935 url = mSettings.getHomePage();
3936 }
3937 }
3938 // In case the web page has not yet received its associated title.
3939 if (title == null) {
3940 title = url;
3941 }
3942 intent.putExtra("title", title);
3943 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003944 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003945 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003946 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003947 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003948 if (startWithHistory) {
Jeff Hamilton64144e42010-08-18 16:31:59 -05003949 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_FRAGMENT,
3950 CombinedBookmarkHistoryActivity.FRAGMENT_ID_HISTORY);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003951 }
Michael Kolb300b7f02010-08-25 13:47:24 -07003952 intent.putExtra(CombinedBookmarkHistoryActivity.NEWTAB_MODE, newTabMode);
Michael Kolb0998b0a2010-08-23 17:45:35 -07003953 int top = -1;
3954 int height = -1;
Michael Kolb3f65c382010-08-20 15:31:16 -07003955 if (mXLargeScreenSize) {
3956 showFakeTitleBar();
3957 int titleBarHeight = ((TitleBarXLarge)mFakeTitleBar).getHeightWithoutProgress();
Michael Kolb0998b0a2010-08-23 17:45:35 -07003958 top = mTabBar.getBottom() + titleBarHeight;
3959 height = getTopWindow().getHeight() - titleBarHeight;
Michael Kolb68792c82010-08-09 16:39:18 -07003960 }
Michael Kolb0998b0a2010-08-23 17:45:35 -07003961 intent.putExtra(CombinedBookmarkHistoryActivity.EXTRA_TOP, top);
3962 intent.putExtra(CombinedBookmarkHistoryActivity.EXTRA_HEIGHT, height);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003963 startActivityForResult(intent, COMBO_PAGE);
3964 }
3965
Ben Murdocheecb4e62010-07-06 16:30:38 +01003966 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
3967 Bitmap favicon) {
3968 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
3969
3970 // Just in case the user tries to save before a page finishes loading
3971 // so the current history item, and therefore the page, is null.
3972 if (null == url) {
3973 url = mLastEnteredUrl;
3974 // This can happen.
3975 if (null == url) {
3976 url = mSettings.getHomePage();
3977 }
3978 }
3979
3980 // In case the web page has not yet received its associated title.
3981 if (title == null) {
3982 title = url;
3983 }
3984
3985 intent.putExtra("title", title);
3986 intent.putExtra("url", url);
3987 intent.putExtra("favicon", favicon);
3988 intent.putExtra("touchIcon", touchIcon);
3989 startActivity(intent);
3990 }
3991
3992
The Android Open Source Project0c908882009-03-03 19:32:16 -08003993 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003994 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003995 // In case the user enters nothing.
3996 if (url != null && url.length() != 0 && view != null) {
3997 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003998 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003999 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004000 }
4001 }
4002 }
4003
Leon Scroggins92472e82010-02-17 16:32:28 -05004004 /**
4005 * Load the URL into the given WebView and update the title bar
4006 * to reflect the new load. Call this instead of WebView.loadUrl
4007 * directly.
4008 * @param view The WebView used to load url.
4009 * @param url The URL to load.
4010 */
4011 private void loadUrl(WebView view, String url) {
4012 updateTitleBarForNewLoad(view, url);
4013 view.loadUrl(url);
4014 }
4015
4016 /**
4017 * Load UrlData into a Tab and update the title bar to reflect the new
4018 * load. Call this instead of UrlData.loadIn directly.
4019 * @param t The Tab used to load.
4020 * @param data The UrlData being loaded.
4021 */
4022 private void loadUrlDataIn(Tab t, UrlData data) {
4023 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
4024 data.loadIn(t);
4025 }
4026
4027 /**
4028 * If the WebView is the top window, update the title bar to reflect
4029 * loading the new URL. i.e. set its text, clear the favicon (which
4030 * will be set once the page begins loading), and set the progress to
4031 * INITIAL_PROGRESS to show that the page has begun to load. Called
4032 * by loadUrl and loadUrlDataIn.
4033 * @param view The WebView that is starting a load.
4034 * @param url The URL that is being loaded.
4035 */
4036 private void updateTitleBarForNewLoad(WebView view, String url) {
4037 if (view == getTopWindow()) {
4038 setUrlTitle(url, null);
4039 setFavicon(null);
4040 onProgressChanged(view, INITIAL_PROGRESS);
4041 }
4042 }
4043
The Android Open Source Project0c908882009-03-03 19:32:16 -08004044 private String smartUrlFilter(Uri inUri) {
4045 if (inUri != null) {
4046 return smartUrlFilter(inUri.toString());
4047 }
4048 return null;
4049 }
4050
Feng Qianb34f87a2009-03-24 21:27:26 -07004051 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004052 "(?i)" + // switch on case insensitive matching
4053 "(" + // begin group for schema
4054 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004055 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004056 ")" +
4057 "(.*)" );
4058
4059 /**
4060 * Attempts to determine whether user input is a URL or search
4061 * terms. Anything with a space is passed to search.
4062 *
4063 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4064 * "Http://" converts to "http://"
4065 *
4066 * @return Original or modified URL
4067 *
4068 */
4069 String smartUrlFilter(String url) {
4070
4071 String inUrl = url.trim();
4072 boolean hasSpace = inUrl.indexOf(' ') != -1;
4073
4074 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4075 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004076 // force scheme to lowercase
4077 String scheme = matcher.group(1);
4078 String lcScheme = scheme.toLowerCase();
4079 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004080 inUrl = lcScheme + matcher.group(2);
4081 }
4082 if (hasSpace) {
4083 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004084 }
4085 return inUrl;
4086 }
4087 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004088 // FIXME: Is this the correct place to add to searches?
4089 // what if someone else calls this function?
4090 int shortcut = parseUrlShortcut(inUrl);
4091 if (shortcut != SHORTCUT_INVALID) {
4092 Browser.addSearchUrl(mResolver, inUrl);
4093 String query = inUrl.substring(2);
4094 switch (shortcut) {
4095 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004096 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004097 case SHORTCUT_WIKIPEDIA_SEARCH:
4098 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4099 case SHORTCUT_DICTIONARY_SEARCH:
4100 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4101 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004102 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004103 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004104 }
4105 }
4106 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004107 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004108 return URLUtil.guessUrl(inUrl);
4109 }
4110 }
4111
4112 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004113 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004114 }
4115
Ben Murdochbff2d602009-07-01 20:19:05 +01004116 /* package */ void setShouldShowErrorConsole(boolean flag) {
4117 if (flag == mShouldShowErrorConsole) {
4118 // Nothing to do.
4119 return;
4120 }
4121
4122 mShouldShowErrorConsole = flag;
4123
Grace Kloba22ac16e2009-10-07 18:00:23 -07004124 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
4125 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004126
4127 if (flag) {
4128 // Setting the show state of the console will cause it's the layout to be inflated.
4129 if (errorConsole.numberOfErrors() > 0) {
4130 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4131 } else {
4132 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4133 }
4134
4135 // Now we can add it to the main view.
4136 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004137 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004138 ViewGroup.LayoutParams.WRAP_CONTENT));
4139 } else {
4140 mErrorConsoleContainer.removeView(errorConsole);
4141 }
4142
4143 }
4144
Grace Kloba22ac16e2009-10-07 18:00:23 -07004145 boolean shouldShowErrorConsole() {
4146 return mShouldShowErrorConsole;
4147 }
4148
Andrei Popescu163ab742009-10-20 17:58:23 +01004149 private void setStatusBarVisibility(boolean visible) {
4150 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4151 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4152 }
4153
Andrei Popescu56199cc2010-01-12 22:39:16 +00004154
4155 private void sendNetworkType(String type, String subtype) {
4156 WebView w = mTabControl.getCurrentWebView();
4157 if (w != null) {
4158 w.setNetworkType(type, subtype);
4159 }
4160 }
4161
Grace Klobaeb6eef42009-09-15 17:56:32 -07004162 final static int LOCK_ICON_UNSECURE = 0;
4163 final static int LOCK_ICON_SECURE = 1;
4164 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004165
The Android Open Source Project0c908882009-03-03 19:32:16 -08004166 private BrowserSettings mSettings;
4167 private TabControl mTabControl;
4168 private ContentResolver mResolver;
4169 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004170 private View mCustomView;
4171 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004172 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004173
4174 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4175 // view, we should rewrite this.
4176 private int mCurrentMenuState = 0;
4177 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004178 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004179 private static final int EMPTY_MENU = -1;
4180 private Menu mMenu;
4181
The Android Open Source Project0c908882009-03-03 19:32:16 -08004182 // Used to prevent chording to result in firing two shortcuts immediately
4183 // one after another. Fixes bug 1211714.
4184 boolean mCanChord;
4185
4186 private boolean mInLoad;
4187 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004188 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004189
Cary Clark1f10cbf2010-03-22 11:45:23 -04004190 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004191
4192 private boolean mMenuIsDown;
4193
The Android Open Source Project0c908882009-03-03 19:32:16 -08004194 private static boolean mInTrace;
4195
4196 // Performance probe
4197 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4198 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4199 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4200 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4201 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4202 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4203 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4204 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4205 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4206 };
4207
4208 private long mStart;
4209 private long mProcessStart;
4210 private long mUserStart;
4211 private long mSystemStart;
4212 private long mIdleStart;
4213 private long mIrqStart;
4214
4215 private long mUiStart;
4216
4217 private Drawable mMixLockIcon;
4218 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004219
4220 /* hold a ref so we can auto-cancel if necessary */
4221 private AlertDialog mAlertDialog;
4222
The Android Open Source Project0c908882009-03-03 19:32:16 -08004223 // The up-to-date URL and title (these can be different from those stored
4224 // in WebView, since it takes some time for the information in WebView to
4225 // get updated)
4226 private String mUrl;
4227 private String mTitle;
4228
4229 // As PageInfo has different style for landscape / portrait, we have
4230 // to re-open it when configuration changed
4231 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004232 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004233 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4234 // dialog, we should not just dismiss it, but should get back to the
4235 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004236 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004237
4238 // as SSLCertificateOnError has different style for landscape / portrait,
4239 // we have to re-open it when configuration changed
4240 private AlertDialog mSSLCertificateOnErrorDialog;
4241 private WebView mSSLCertificateOnErrorView;
4242 private SslErrorHandler mSSLCertificateOnErrorHandler;
4243 private SslError mSSLCertificateOnErrorError;
4244
4245 // as SSLCertificate has different style for landscape / portrait, we
4246 // have to re-open it when configuration changed
4247 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004248 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004249
4250 // as HttpAuthentication has different style for landscape / portrait, we
4251 // have to re-open it when configuration changed
4252 private AlertDialog mHttpAuthenticationDialog;
4253 private HttpAuthHandler mHttpAuthHandler;
4254
4255 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4256 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004257 ViewGroup.LayoutParams.MATCH_PARENT,
4258 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004259 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4260 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004261 ViewGroup.LayoutParams.MATCH_PARENT,
4262 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004263 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004264 // Google search
4265 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004266 // Wikipedia search
4267 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4268 // Dictionary search
4269 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4270 // Google Mobile Local search
4271 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4272
4273 final static String QUERY_PLACE_HOLDER = "%s";
4274
4275 // "source" parameter for Google search through search key
4276 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4277 // "source" parameter for Google search through goto menu
4278 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4279 // "source" parameter for Google search through simplily type
4280 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4281 // "source" parameter for Google search suggested by the browser
4282 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4283 // "source" parameter for Google search from unknown source
4284 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4285
4286 private final static String LOGTAG = "browser";
4287
The Android Open Source Project0c908882009-03-03 19:32:16 -08004288 private String mLastEnteredUrl;
4289
4290 private PowerManager.WakeLock mWakeLock;
4291 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4292
4293 private Toast mStopToast;
4294
Leon Scroggins571b3762010-05-26 10:25:01 -04004295 private TitleBarBase mTitleBar;
Michael Kolba2b2ba82010-08-04 17:54:03 -07004296 private TabBar mTabBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004297
Ben Murdochbff2d602009-07-01 20:19:05 +01004298 private LinearLayout mErrorConsoleContainer = null;
4299 private boolean mShouldShowErrorConsole = false;
4300
The Android Open Source Project0c908882009-03-03 19:32:16 -08004301 // As the ids are dynamically created, we can't guarantee that they will
4302 // be in sequence, so this static array maps ids to a window number.
4303 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4304 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4305 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4306 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4307
4308 // monitor platform changes
4309 private IntentFilter mNetworkStateChangedFilter;
4310 private BroadcastReceiver mNetworkStateIntentReceiver;
4311
Bjorn Bringerta7611812010-03-24 11:12:02 +00004312 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4313
The Android Open Source Project0c908882009-03-03 19:32:16 -08004314 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004315 final static int COMBO_PAGE = 1;
4316 final static int DOWNLOAD_PAGE = 2;
4317 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004318 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004319
Andrei Popescu540035d2009-09-18 18:59:20 +01004320 // the default <video> poster
4321 private Bitmap mDefaultVideoPoster;
4322 // the video progress view
4323 private View mVideoProgressView;
4324
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004325 /**
4326 * A UrlData class to abstract how the content will be set to WebView.
4327 * This base class uses loadUrl to show the content.
4328 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004329 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004330 final String mUrl;
4331 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004332 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004333
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004334 UrlData(String url) {
4335 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004336 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004337 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004338 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004339
Leon Scroggins58d56c62010-01-28 15:12:40 -05004340 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004341 this.mUrl = url;
4342 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004343 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4344 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004345 this.mVoiceIntent = intent;
4346 } else {
4347 this.mVoiceIntent = null;
4348 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004349 }
4350
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004351 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004352 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004353 }
4354
Leon Scroggins92472e82010-02-17 16:32:28 -05004355 /**
4356 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4357 * the title bar as well.
4358 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004359 public void loadIn(Tab t) {
4360 if (mVoiceIntent != null) {
4361 t.activateVoiceSearchMode(mVoiceIntent);
4362 } else {
4363 t.getWebView().loadUrl(mUrl, mHeaders);
4364 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004365 }
4366 };
4367
Leon Scroggins1f005d32009-08-10 17:36:42 -04004368 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004369}