blob: b7cdcd4489dffa4608834ccff182e79b6ae1977f [file] [log] [blame]
Michael Kolb8233fac2010-10-26 16:08:53 -07001/*
2 * Copyright (C) 2010 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 Kolb8233fac2010-10-26 16:08:53 -070019import android.app.Activity;
20import android.app.DownloadManager;
21import android.app.SearchManager;
22import android.content.ClipboardManager;
23import android.content.ContentProvider;
24import android.content.ContentProviderClient;
25import android.content.ContentResolver;
John Reckd8c74522011-06-14 08:45:00 -070026import android.content.ContentUris;
Michael Kolb8233fac2010-10-26 16:08:53 -070027import android.content.ContentValues;
28import android.content.Context;
29import android.content.Intent;
30import android.content.pm.PackageManager;
31import android.content.pm.ResolveInfo;
32import android.content.res.Configuration;
John Reck30b065e2011-07-19 10:58:05 -070033import android.content.res.TypedArray;
Leon Scroggins1961ed22010-12-07 15:22:21 -050034import android.database.ContentObserver;
Michael Kolb8233fac2010-10-26 16:08:53 -070035import android.database.Cursor;
36import android.database.sqlite.SQLiteDatabase;
Michael Kolb8233fac2010-10-26 16:08:53 -070037import android.graphics.Bitmap;
38import android.graphics.Canvas;
39import android.graphics.Picture;
40import android.net.Uri;
41import android.net.http.SslError;
42import android.os.AsyncTask;
43import android.os.Bundle;
44import android.os.Handler;
45import android.os.Message;
46import android.os.PowerManager;
47import android.os.PowerManager.WakeLock;
Ben Murdoch8029a772010-11-16 11:58:21 +000048import android.preference.PreferenceActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -070049import android.provider.Browser;
50import android.provider.BrowserContract;
Michael Kolb8233fac2010-10-26 16:08:53 -070051import android.provider.BrowserContract.Images;
52import android.provider.ContactsContract;
53import android.provider.ContactsContract.Intents.Insert;
Michael Kolbcfa3af52010-12-14 10:36:11 -080054import android.speech.RecognizerIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070055import android.text.TextUtils;
56import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080057import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070058import android.view.ActionMode;
59import android.view.ContextMenu;
60import android.view.ContextMenu.ContextMenuInfo;
61import android.view.Gravity;
62import android.view.KeyEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070063import android.view.Menu;
64import android.view.MenuInflater;
65import android.view.MenuItem;
66import android.view.MenuItem.OnMenuItemClickListener;
Michael Kolbc3af0672011-08-09 10:24:41 -070067import android.view.MotionEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070068import android.view.View;
69import android.webkit.CookieManager;
70import android.webkit.CookieSyncManager;
71import android.webkit.HttpAuthHandler;
72import android.webkit.SslErrorHandler;
73import android.webkit.ValueCallback;
74import android.webkit.WebChromeClient;
75import android.webkit.WebIconDatabase;
76import android.webkit.WebSettings;
77import android.webkit.WebView;
Leon Scrogginsac993842011-02-02 12:54:07 -050078import android.widget.Toast;
Michael Kolb8233fac2010-10-26 16:08:53 -070079
Michael Kolb4bd767d2011-05-27 11:33:55 -070080import com.android.browser.IntentHandler.UrlData;
John Reck2bc80422011-06-30 15:11:49 -070081import com.android.browser.UI.ComboViews;
Michael Kolb4bd767d2011-05-27 11:33:55 -070082import com.android.browser.UI.DropdownChangeListener;
83import com.android.browser.provider.BrowserProvider;
John Reck1cf4b792011-07-26 10:22:22 -070084import com.android.browser.provider.BrowserProvider2.Thumbnails;
John Reck8cc92352011-07-06 17:41:52 -070085import com.android.browser.provider.SnapshotProvider.Snapshots;
Michael Kolb4bd767d2011-05-27 11:33:55 -070086import com.android.browser.search.SearchEngine;
87import com.android.common.Search;
88
Michael Kolb8233fac2010-10-26 16:08:53 -070089import java.io.ByteArrayOutputStream;
Michael Kolb8233fac2010-10-26 16:08:53 -070090import java.net.URLEncoder;
John Reck1cf4b792011-07-26 10:22:22 -070091import java.util.ArrayList;
Michael Kolb8233fac2010-10-26 16:08:53 -070092import java.util.Calendar;
93import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -080094import java.util.List;
John Reck26b18322011-06-21 13:08:58 -070095import java.util.Map;
Michael Kolb8233fac2010-10-26 16:08:53 -070096
97/**
98 * Controller for browser
99 */
100public class Controller
101 implements WebViewController, UiController {
102
103 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800104 private static final String SEND_APP_ID_EXTRA =
105 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
Michael Kolba4261fd2011-05-05 11:27:37 -0700106 private static final String INCOGNITO_URI = "browser:incognito";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800107
Michael Kolb8233fac2010-10-26 16:08:53 -0700108
109 // public message ids
110 public final static int LOAD_URL = 1001;
111 public final static int STOP_LOAD = 1002;
112
113 // Message Ids
114 private static final int FOCUS_NODE_HREF = 102;
115 private static final int RELEASE_WAKELOCK = 107;
116
117 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
118
119 private static final int OPEN_BOOKMARKS = 201;
120
121 private static final int EMPTY_MENU = -1;
122
Michael Kolb8233fac2010-10-26 16:08:53 -0700123 // activity requestCode
John Reckd3e4d5b2011-07-13 15:48:43 -0700124 final static int COMBO_VIEW = 1;
Michael Kolb8233fac2010-10-26 16:08:53 -0700125 final static int PREFERENCES_PAGE = 3;
126 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000127 final static int AUTOFILL_SETUP = 5;
128
Michael Kolb8233fac2010-10-26 16:08:53 -0700129 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
130
131 // As the ids are dynamically created, we can't guarantee that they will
132 // be in sequence, so this static array maps ids to a window number.
133 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
134 { R.id.window_one_menu_id, R.id.window_two_menu_id,
135 R.id.window_three_menu_id, R.id.window_four_menu_id,
136 R.id.window_five_menu_id, R.id.window_six_menu_id,
137 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
138
139 // "source" parameter for Google search through search key
140 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
141 // "source" parameter for Google search through simplily type
142 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
143
Guang Zhu9e78f512011-05-04 11:45:11 -0700144 // "no-crash-recovery" parameter in intetnt to suppress crash recovery
145 final static String NO_CRASH_RECOVERY = "no-crash-recovery";
146
Michael Kolb8233fac2010-10-26 16:08:53 -0700147 private Activity mActivity;
148 private UI mUi;
149 private TabControl mTabControl;
150 private BrowserSettings mSettings;
151 private WebViewFactory mFactory;
152
153 private WakeLock mWakeLock;
154
155 private UrlHandler mUrlHandler;
156 private UploadHandler mUploadHandler;
157 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700158 private PageDialogsHandler mPageDialogsHandler;
159 private NetworkStateHandler mNetworkHandler;
160
Ben Murdoch8029a772010-11-16 11:58:21 +0000161 private Message mAutoFillSetupMessage;
162
Michael Kolb8233fac2010-10-26 16:08:53 -0700163 private boolean mShouldShowErrorConsole;
164
165 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
166
167 // FIXME, temp address onPrepareMenu performance problem.
168 // When we move everything out of view, we should rewrite this.
169 private int mCurrentMenuState = 0;
170 private int mMenuState = R.id.MAIN_MENU;
171 private int mOldMenuState = EMPTY_MENU;
172 private Menu mCachedMenu;
173
Michael Kolb8233fac2010-10-26 16:08:53 -0700174 private boolean mMenuIsDown;
175
176 // For select and find, we keep track of the ActionMode so that
177 // finish() can be called as desired.
178 private ActionMode mActionMode;
179
180 /**
181 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
182 * of whether the configuration has changed. The first onMenuOpened call
183 * after a configuration change is simply a reopening of the same menu
184 * (i.e. mIconView did not change).
185 */
186 private boolean mConfigChanged;
187
188 /**
189 * Keeps track of whether the options menu is open. This is important in
190 * determining whether to show or hide the title bar overlay
191 */
192 private boolean mOptionsMenuOpen;
193
194 /**
195 * Whether or not the options menu is in its bigger, popup menu form. When
196 * true, we want the title bar overlay to be gone. When false, we do not.
197 * Only meaningful if mOptionsMenuOpen is true.
198 */
199 private boolean mExtendedMenuOpen;
200
201 private boolean mInLoad;
202
203 private boolean mActivityPaused = true;
204 private boolean mLoadStopped;
205
206 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500207 // Checks to see when the bookmarks database has changed, and updates the
208 // Tabs' notion of whether they represent bookmarked sites.
209 private ContentObserver mBookmarksObserver;
John Reck847b5322011-04-14 17:02:18 -0700210 private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700211
John Reck30b065e2011-07-19 10:58:05 -0700212 private boolean mSimulateActionBarOverlayMode;
213
Michael Kolbc3af0672011-08-09 10:24:41 -0700214 private boolean mBlockEvents;
215
John Reckbc490d22011-07-22 15:04:59 -0700216 public Controller(Activity browser, boolean preloadCrashState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700217 mActivity = browser;
218 mSettings = BrowserSettings.getInstance();
219 mTabControl = new TabControl(this);
220 mSettings.setController(this);
John Reck378a4102011-06-09 16:23:01 -0700221 mCrashRecoveryHandler = CrashRecoveryHandler.initialize(this);
John Reckbc490d22011-07-22 15:04:59 -0700222 if (preloadCrashState) {
223 mCrashRecoveryHandler.preloadCrashState();
224 }
Michael Kolb14612442011-06-24 13:06:29 -0700225 mFactory = new BrowserWebViewFactory(browser);
Michael Kolb8233fac2010-10-26 16:08:53 -0700226
227 mUrlHandler = new UrlHandler(this);
228 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700229 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
230
Michael Kolb8233fac2010-10-26 16:08:53 -0700231 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500232 mBookmarksObserver = new ContentObserver(mHandler) {
233 @Override
234 public void onChange(boolean selfChange) {
235 int size = mTabControl.getTabCount();
236 for (int i = 0; i < size; i++) {
237 mTabControl.getTab(i).updateBookmarkedStatus();
238 }
239 }
240
241 };
242 browser.getContentResolver().registerContentObserver(
243 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700244
245 mNetworkHandler = new NetworkStateHandler(mActivity, this);
246 // Start watching the default geolocation permissions
247 mSystemAllowGeolocationOrigins =
248 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
249 mSystemAllowGeolocationOrigins.start();
250
John Reckaf262e72011-07-25 13:55:44 -0700251 openIconDatabase();
John Reck30b065e2011-07-19 10:58:05 -0700252 mSimulateActionBarOverlayMode = !BrowserActivity.isTablet(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700253 }
254
Patrick Scott7d50a932011-02-04 09:27:26 -0500255 void start(final Bundle icicle, final Intent intent) {
Guang Zhu9e78f512011-05-04 11:45:11 -0700256 boolean noCrashRecovery = intent.getBooleanExtra(NO_CRASH_RECOVERY, false);
257 if (icicle != null || noCrashRecovery) {
John Reck847b5322011-04-14 17:02:18 -0700258 doStart(icicle, intent);
259 } else {
260 mCrashRecoveryHandler.startRecovery(intent);
261 }
262 }
263
264 void doStart(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700265 // Unless the last browser usage was within 24 hours, destroy any
266 // remaining incognito tabs.
267
268 Calendar lastActiveDate = icicle != null ?
269 (Calendar) icicle.getSerializable("lastActiveDate") : null;
270 Calendar today = Calendar.getInstance();
271 Calendar yesterday = Calendar.getInstance();
272 yesterday.add(Calendar.DATE, -1);
273
Patrick Scott7d50a932011-02-04 09:27:26 -0500274 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700275 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800276 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700277
Patrick Scott7d50a932011-02-04 09:27:26 -0500278 // Find out if we will restore any state and remember the tab.
Michael Kolbc831b632011-05-11 09:30:34 -0700279 final long currentTabId =
Patrick Scott7d50a932011-02-04 09:27:26 -0500280 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000281
Michael Kolbc831b632011-05-11 09:30:34 -0700282 if (currentTabId == -1) {
Patrick Scott7d50a932011-02-04 09:27:26 -0500283 // Not able to restore so we go ahead and clear session cookies. We
284 // must do this before trying to login the user as we don't want to
285 // clear any session cookies set during login.
286 CookieManager.getInstance().removeSessionCookie();
287 }
288
Patrick Scottd43e75a2011-03-14 14:47:23 -0400289 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500290 new Runnable() {
291 @Override public void run() {
Michael Kolbc831b632011-05-11 09:30:34 -0700292 onPreloginFinished(icicle, intent, currentTabId, restoreIncognitoTabs);
Patrick Scott7d50a932011-02-04 09:27:26 -0500293 }
294 });
295 }
296
Michael Kolbc831b632011-05-11 09:30:34 -0700297 private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId,
Patrick Scott7d50a932011-02-04 09:27:26 -0500298 boolean restoreIncognitoTabs) {
Michael Kolbc831b632011-05-11 09:30:34 -0700299 if (currentTabId == -1) {
John Reck1cf4b792011-07-26 10:22:22 -0700300 BackgroundHandler.execute(new PruneThumbnails(mActivity, null));
Michael Kolb8233fac2010-10-26 16:08:53 -0700301 final Bundle extra = intent.getExtras();
302 // Create an initial tab.
303 // If the intent is ACTION_VIEW and data is not null, the Browser is
304 // invoked to view the content by another application. In this case,
305 // the tab will be close when exit.
Michael Kolb14612442011-06-24 13:06:29 -0700306 UrlData urlData = IntentHandler.getUrlDataFromIntent(intent);
Michael Kolb7bcafde2011-05-09 13:55:59 -0700307 Tab t = null;
308 if (urlData.isEmpty()) {
309 t = openTabToHomePage();
310 } else {
311 t = openTab(urlData);
312 }
313 if (t != null) {
314 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
315 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700316 WebView webView = t.getWebView();
317 if (extra != null) {
318 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
319 if (scale > 0 && scale <= 1000) {
320 webView.setInitialScale(scale);
321 }
322 }
John Reckd8c74522011-06-14 08:45:00 -0700323 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700324 } else {
Michael Kolbc831b632011-05-11 09:30:34 -0700325 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
Patrick Scott7d50a932011-02-04 09:27:26 -0500326 mUi.needsRestoreAllTabs());
John Reck1cf4b792011-07-26 10:22:22 -0700327 List<Tab> tabs = mTabControl.getTabs();
328 ArrayList<Long> restoredTabs = new ArrayList<Long>(tabs.size());
329 for (Tab t : tabs) {
330 restoredTabs.add(t.getId());
331 }
332 BackgroundHandler.execute(new PruneThumbnails(mActivity, restoredTabs));
John Reck52be4782011-08-26 15:37:29 -0700333 if (tabs.size() == 0) {
334 openTabToHomePage();
335 }
John Reck1cf4b792011-07-26 10:22:22 -0700336 mUi.updateTabs(tabs);
Michael Kolb8233fac2010-10-26 16:08:53 -0700337 // TabControl.restoreState() will create a new tab even if
338 // restoring the state fails.
339 setActiveTab(mTabControl.getCurrentTab());
John Reckdb22ec42011-06-29 11:31:24 -0700340 // Handle the intent
341 mIntentHandler.onNewIntent(intent);
Michael Kolb8233fac2010-10-26 16:08:53 -0700342 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700343 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700344 String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb8233fac2010-10-26 16:08:53 -0700345 if (jsFlags.trim().length() != 0) {
346 getCurrentWebView().setJsFlags(jsFlags);
347 }
John Reck439c9a52010-12-14 10:04:39 -0800348 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
349 bookmarksOrHistoryPicker(false);
350 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700351 }
352
John Reck1cf4b792011-07-26 10:22:22 -0700353 private static class PruneThumbnails implements Runnable {
354 private Context mContext;
355 private List<Long> mIds;
356
357 PruneThumbnails(Context context, List<Long> preserveIds) {
358 mContext = context.getApplicationContext();
359 mIds = preserveIds;
360 }
361
362 @Override
363 public void run() {
364 ContentResolver cr = mContext.getContentResolver();
365 if (mIds == null || mIds.size() == 0) {
366 cr.delete(Thumbnails.CONTENT_URI, null, null);
367 } else {
368 int length = mIds.size();
369 StringBuilder where = new StringBuilder();
370 where.append(Thumbnails._ID);
371 where.append(" not in (");
372 for (int i = 0; i < length; i++) {
373 where.append(mIds.get(i));
374 if (i < (length - 1)) {
375 where.append(",");
376 }
377 }
378 where.append(")");
379 cr.delete(Thumbnails.CONTENT_URI, where.toString(), null);
380 }
381 }
382
383 }
384
Michael Kolb1514bb72010-11-22 09:11:48 -0800385 @Override
386 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700387 return mFactory;
388 }
389
390 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800391 public void onSetWebView(Tab tab, WebView view) {
392 mUi.onSetWebView(tab, view);
393 }
394
395 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800396 public void createSubWindow(Tab tab) {
397 endActionMode();
398 WebView mainView = tab.getWebView();
399 WebView subView = mFactory.createWebView((mainView == null)
400 ? false
401 : mainView.isPrivateBrowsingEnabled());
402 mUi.createSubWindow(tab, subView);
403 }
404
405 @Override
Michael Kolb14612442011-06-24 13:06:29 -0700406 public Context getContext() {
407 return mActivity;
408 }
409
410 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700411 public Activity getActivity() {
412 return mActivity;
413 }
414
415 void setUi(UI ui) {
416 mUi = ui;
417 }
418
419 BrowserSettings getSettings() {
420 return mSettings;
421 }
422
423 IntentHandler getIntentHandler() {
424 return mIntentHandler;
425 }
426
427 @Override
428 public UI getUi() {
429 return mUi;
430 }
431
432 int getMaxTabs() {
433 return mActivity.getResources().getInteger(R.integer.max_tabs);
434 }
435
436 @Override
437 public TabControl getTabControl() {
438 return mTabControl;
439 }
440
Michael Kolb1bf23132010-11-19 12:55:12 -0800441 @Override
442 public List<Tab> getTabs() {
443 return mTabControl.getTabs();
444 }
445
John Reckaf262e72011-07-25 13:55:44 -0700446 // Open the icon database.
447 private void openIconDatabase() {
448 // We have to call getInstance on the UI thread
449 final WebIconDatabase instance = WebIconDatabase.getInstance();
450 BackgroundHandler.execute(new Runnable() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000451
John Reckaf262e72011-07-25 13:55:44 -0700452 @Override
453 public void run() {
454 instance.open(mActivity.getDir("icons", 0).getPath());
Michael Kolb8233fac2010-10-26 16:08:53 -0700455 }
John Reckaf262e72011-07-25 13:55:44 -0700456 });
Michael Kolb8233fac2010-10-26 16:08:53 -0700457 }
458
459 private void startHandler() {
460 mHandler = new Handler() {
461
462 @Override
463 public void handleMessage(Message msg) {
464 switch (msg.what) {
465 case OPEN_BOOKMARKS:
466 bookmarksOrHistoryPicker(false);
467 break;
468 case FOCUS_NODE_HREF:
469 {
470 String url = (String) msg.getData().get("url");
471 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500472 String src = (String) msg.getData().get("src");
473 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700474 if (TextUtils.isEmpty(url)) {
475 break;
476 }
477 HashMap focusNodeMap = (HashMap) msg.obj;
478 WebView view = (WebView) focusNodeMap.get("webview");
479 // Only apply the action if the top window did not change.
480 if (getCurrentTopWebView() != view) {
481 break;
482 }
483 switch (msg.arg1) {
484 case R.id.open_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700485 loadUrlFromContext(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700486 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500487 case R.id.view_image_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700488 loadUrlFromContext(src);
Cary Clark043c2d62010-12-15 11:19:39 -0500489 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500490 case R.id.open_newtab_context_menu_id:
491 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -0700492 openTab(url, parent,
493 !mSettings.openInBackground(), true);
Leon Scroggins026f2542010-11-22 13:26:12 -0500494 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700495 case R.id.copy_link_context_menu_id:
496 copy(url);
497 break;
498 case R.id.save_link_context_menu_id:
499 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500500 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000501 mActivity, url, null, null, null,
502 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700503 break;
504 }
505 break;
506 }
507
508 case LOAD_URL:
John Reck26b18322011-06-21 13:08:58 -0700509 loadUrlFromContext((String) msg.obj);
Michael Kolb8233fac2010-10-26 16:08:53 -0700510 break;
511
512 case STOP_LOAD:
513 stopLoading();
514 break;
515
516 case RELEASE_WAKELOCK:
John Reckf57c0292011-07-21 18:15:39 -0700517 if (mWakeLock != null && mWakeLock.isHeld()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700518 mWakeLock.release();
519 // if we reach here, Browser should be still in the
520 // background loading after WAKELOCK_TIMEOUT (5-min).
521 // To avoid burning the battery, stop loading.
522 mTabControl.stopAllLoading();
523 }
524 break;
525
526 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800527 Tab tab = (Tab) msg.obj;
528 if (tab != null) {
529 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700530 }
531 break;
532 }
533 }
534 };
535
536 }
537
John Reckef654f12011-07-12 16:42:08 -0700538 @Override
Martijn Coenenb2f93552011-06-14 10:48:35 +0200539 public Tab getCurrentTab() {
540 return mTabControl.getCurrentTab();
541 }
542
Michael Kolbba99c5d2010-11-29 14:57:41 -0800543 @Override
544 public void shareCurrentPage() {
545 shareCurrentPage(mTabControl.getCurrentTab());
546 }
547
548 private void shareCurrentPage(Tab tab) {
549 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800550 sharePage(mActivity, tab.getTitle(),
551 tab.getUrl(), tab.getFavicon(),
552 createScreenshot(tab.getWebView(),
553 getDesiredThumbnailWidth(mActivity),
554 getDesiredThumbnailHeight(mActivity)));
555 }
556 }
557
Michael Kolb8233fac2010-10-26 16:08:53 -0700558 /**
559 * Share a page, providing the title, url, favicon, and a screenshot. Uses
560 * an {@link Intent} to launch the Activity chooser.
561 * @param c Context used to launch a new Activity.
562 * @param title Title of the page. Stored in the Intent with
563 * {@link Intent#EXTRA_SUBJECT}
564 * @param url URL of the page. Stored in the Intent with
565 * {@link Intent#EXTRA_TEXT}
566 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
567 * with {@link Browser#EXTRA_SHARE_FAVICON}
568 * @param screenshot Bitmap of a screenshot of the page. Stored in the
569 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
570 */
571 static final void sharePage(Context c, String title, String url,
572 Bitmap favicon, Bitmap screenshot) {
573 Intent send = new Intent(Intent.ACTION_SEND);
574 send.setType("text/plain");
575 send.putExtra(Intent.EXTRA_TEXT, url);
576 send.putExtra(Intent.EXTRA_SUBJECT, title);
577 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
578 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
579 try {
580 c.startActivity(Intent.createChooser(send, c.getString(
581 R.string.choosertitle_sharevia)));
582 } catch(android.content.ActivityNotFoundException ex) {
583 // if no app handles it, do nothing
584 }
585 }
586
587 private void copy(CharSequence text) {
588 ClipboardManager cm = (ClipboardManager) mActivity
589 .getSystemService(Context.CLIPBOARD_SERVICE);
590 cm.setText(text);
591 }
592
593 // lifecycle
594
595 protected void onConfgurationChanged(Configuration config) {
596 mConfigChanged = true;
597 if (mPageDialogsHandler != null) {
598 mPageDialogsHandler.onConfigurationChanged(config);
599 }
600 mUi.onConfigurationChanged(config);
601 }
602
603 @Override
604 public void handleNewIntent(Intent intent) {
Michael Kolb59e232c2011-08-18 17:19:53 -0700605 if (!mUi.isWebShowing()) {
606 mUi.showWeb(false);
607 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700608 mIntentHandler.onNewIntent(intent);
609 }
610
611 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800612 if (mUi.isCustomViewShowing()) {
613 hideCustomView();
614 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700615 if (mActivityPaused) {
616 Log.e(LOGTAG, "BrowserActivity is already paused.");
617 return;
618 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700619 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800620 Tab tab = mTabControl.getCurrentTab();
621 if (tab != null) {
622 tab.pause();
623 if (!pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700624 if (mWakeLock == null) {
625 PowerManager pm = (PowerManager) mActivity
626 .getSystemService(Context.POWER_SERVICE);
627 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
628 }
Michael Kolb70976932010-11-30 11:34:01 -0800629 mWakeLock.acquire();
630 mHandler.sendMessageDelayed(mHandler
631 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
632 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700633 }
634 mUi.onPause();
635 mNetworkHandler.onPause();
636
637 WebView.disablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100638 NfcHandler.unregister(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700639 }
640
John Reck1cf4b792011-07-26 10:22:22 -0700641 void onSaveInstanceState(Bundle outState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700642 // the default implementation requires each view to have an id. As the
643 // browser handles the state itself and it doesn't use id for the views,
644 // don't call the default implementation. Otherwise it will trigger the
645 // warning like this, "couldn't save which view has focus because the
646 // focused view XXX has no id".
647
648 // Save all the tabs
John Reck1cf4b792011-07-26 10:22:22 -0700649 mTabControl.saveState(outState);
John Reck24f18262011-06-17 14:47:20 -0700650 if (!outState.isEmpty()) {
651 // Save time so that we know how old incognito tabs (if any) are.
652 outState.putSerializable("lastActiveDate", Calendar.getInstance());
653 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700654 }
655
656 void onResume() {
657 if (!mActivityPaused) {
658 Log.e(LOGTAG, "BrowserActivity is already resumed.");
659 return;
660 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700661 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800662 Tab current = mTabControl.getCurrentTab();
663 if (current != null) {
664 current.resume();
665 resumeWebViewTimers(current);
666 }
John Reckf57c0292011-07-21 18:15:39 -0700667 releaseWakeLock();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200668
Michael Kolb8233fac2010-10-26 16:08:53 -0700669 mUi.onResume();
670 mNetworkHandler.onResume();
671 WebView.enablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100672 NfcHandler.register(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700673 }
674
John Reckf57c0292011-07-21 18:15:39 -0700675 private void releaseWakeLock() {
676 if (mWakeLock != null && mWakeLock.isHeld()) {
677 mHandler.removeMessages(RELEASE_WAKELOCK);
678 mWakeLock.release();
679 }
680 }
681
Michael Kolb70976932010-11-30 11:34:01 -0800682 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800683 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800684 * @param tab guaranteed non-null
685 */
686 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700687 boolean inLoad = tab.inPageLoad();
688 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
689 CookieSyncManager.getInstance().startSync();
690 WebView w = tab.getWebView();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100691 WebViewTimersControl.getInstance().onBrowserActivityResume(w);
Michael Kolb8233fac2010-10-26 16:08:53 -0700692 }
693 }
694
Michael Kolb70976932010-11-30 11:34:01 -0800695 /**
696 * Pause all WebView timers using the WebView of the given tab
697 * @param tab
698 * @return true if the timers are paused or tab is null
699 */
700 private boolean pauseWebViewTimers(Tab tab) {
701 if (tab == null) {
702 return true;
703 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700704 CookieSyncManager.getInstance().stopSync();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100705 WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView());
Michael Kolb8233fac2010-10-26 16:08:53 -0700706 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700707 }
Michael Kolb70976932010-11-30 11:34:01 -0800708 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700709 }
710
711 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800712 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700713 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
714 mUploadHandler = null;
715 }
716 if (mTabControl == null) return;
717 mUi.onDestroy();
718 // Remove the current tab and sub window
719 Tab t = mTabControl.getCurrentTab();
720 if (t != null) {
721 dismissSubWindow(t);
722 removeTab(t);
723 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500724 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700725 // Destroy all the tabs
726 mTabControl.destroy();
727 WebIconDatabase.getInstance().close();
728 // Stop watching the default geolocation permissions
729 mSystemAllowGeolocationOrigins.stop();
730 mSystemAllowGeolocationOrigins = null;
731 }
732
733 protected boolean isActivityPaused() {
734 return mActivityPaused;
735 }
736
737 protected void onLowMemory() {
738 mTabControl.freeMemory();
739 }
740
741 @Override
742 public boolean shouldShowErrorConsole() {
743 return mShouldShowErrorConsole;
744 }
745
746 protected void setShouldShowErrorConsole(boolean show) {
747 if (show == mShouldShowErrorConsole) {
748 // Nothing to do.
749 return;
750 }
751 mShouldShowErrorConsole = show;
752 Tab t = mTabControl.getCurrentTab();
753 if (t == null) {
754 // There is no current tab so we cannot toggle the error console
755 return;
756 }
757 mUi.setShouldShowErrorConsole(t, show);
758 }
759
760 @Override
761 public void stopLoading() {
762 mLoadStopped = true;
763 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700764 WebView w = getCurrentTopWebView();
765 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700766 mUi.onPageStopped(tab);
767 }
768
769 boolean didUserStopLoading() {
770 return mLoadStopped;
771 }
772
773 // WebViewController
774
775 @Override
John Reck324d4402011-01-11 16:56:42 -0800776 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700777
778 // We've started to load a new page. If there was a pending message
779 // to save a screenshot then we will now take the new page and save
780 // an incorrect screenshot. Therefore, remove any pending thumbnail
781 // messages from the queue.
782 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800783 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700784
785 // reset sync timer to avoid sync starts during loading a page
786 CookieSyncManager.getInstance().resetSync();
787
788 if (!mNetworkHandler.isNetworkUp()) {
789 view.setNetworkAvailable(false);
790 }
791
792 // when BrowserActivity just starts, onPageStarted may be called before
793 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
794 // to start the timer. As we won't switch tabs while an activity is in
795 // pause state, we can ensure calling resume and pause in pair.
796 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800797 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700798 }
799 mLoadStopped = false;
800 if (!mNetworkHandler.isNetworkUp()) {
801 mNetworkHandler.createAndShowNetworkDialog();
802 }
803 endActionMode();
804
John Reck30c714c2010-12-16 17:30:34 -0800805 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700806
John Reck324d4402011-01-11 16:56:42 -0800807 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700808 // update the bookmark database for favicon
809 maybeUpdateFavicon(tab, null, url, favicon);
810
811 Performance.tracePageStart(url);
812
813 // Performance probe
814 if (false) {
815 Performance.onPageStarted();
816 }
817
818 }
819
820 @Override
John Reck324d4402011-01-11 16:56:42 -0800821 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800822 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800823 if (!tab.isPrivateBrowsingEnabled()
John Reckd8c74522011-06-14 08:45:00 -0700824 && !TextUtils.isEmpty(tab.getUrl())
825 && !tab.isSnapshot()) {
John Recka1696282011-07-08 14:10:37 -0700826 // Only update the bookmark screenshot if the user did not
827 // cancel the load early and there is not already
828 // a pending update for the tab.
Michael Kolb8233fac2010-10-26 16:08:53 -0700829 if (tab.inForeground() && !didUserStopLoading()
830 || !tab.inForeground()) {
John Recka1696282011-07-08 14:10:37 -0700831 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
832 mHandler.sendMessageDelayed(mHandler.obtainMessage(
833 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
834 500);
835 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700836 }
837 }
838 // pause the WebView timer and release the wake lock if it is finished
839 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800840 if (mActivityPaused && pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700841 releaseWakeLock();
Michael Kolb8233fac2010-10-26 16:08:53 -0700842 }
Martijn Coenenb2f93552011-06-14 10:48:35 +0200843
Michael Kolb8233fac2010-10-26 16:08:53 -0700844 // Performance probe
845 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800846 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700847 }
848
849 Performance.tracePageFinished();
850 }
851
852 @Override
John Reck30c714c2010-12-16 17:30:34 -0800853 public void onProgressChanged(Tab tab) {
John Reck6c2e2f32011-08-22 13:41:23 -0700854 mCrashRecoveryHandler.backupState();
John Reck30c714c2010-12-16 17:30:34 -0800855 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700856
857 if (newProgress == 100) {
858 CookieSyncManager.getInstance().sync();
859 // onProgressChanged() may continue to be called after the main
860 // frame has finished loading, as any remaining sub frames continue
861 // to load. We'll only get called once though with newProgress as
862 // 100 when everything is loaded. (onPageFinished is called once
863 // when the main frame completes loading regardless of the state of
864 // any sub frames so calls to onProgressChanges may continue after
865 // onPageFinished has executed)
866 if (mInLoad) {
867 mInLoad = false;
868 updateInLoadMenuItems(mCachedMenu);
869 }
870 } else {
871 if (!mInLoad) {
872 // onPageFinished may have already been called but a subframe is
873 // still loading and updating the progress. Reset mInLoad and
874 // update the menu items.
875 mInLoad = true;
876 updateInLoadMenuItems(mCachedMenu);
877 }
878 }
John Reck30c714c2010-12-16 17:30:34 -0800879 mUi.onProgressChanged(tab);
880 }
881
882 @Override
883 public void onUpdatedLockIcon(Tab tab) {
884 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700885 }
886
887 @Override
888 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800889 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800890 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800891 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700892 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
893 return;
894 }
895 // Update the title in the history database if not in private browsing mode
896 if (!tab.isPrivateBrowsingEnabled()) {
John Reckf57c0292011-07-21 18:15:39 -0700897 DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700898 }
899 }
900
901 @Override
902 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800903 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700904 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
905 }
906
907 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800908 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
909 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700910 }
911
912 @Override
913 public boolean shouldOverrideKeyEvent(KeyEvent event) {
914 if (mMenuIsDown) {
915 // only check shortcut key when MENU is held
916 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
917 event);
918 } else {
919 return false;
920 }
921 }
922
923 @Override
924 public void onUnhandledKeyEvent(KeyEvent event) {
925 if (!isActivityPaused()) {
926 if (event.getAction() == KeyEvent.ACTION_DOWN) {
927 mActivity.onKeyDown(event.getKeyCode(), event);
928 } else {
929 mActivity.onKeyUp(event.getKeyCode(), event);
930 }
931 }
932 }
933
934 @Override
John Reck324d4402011-01-11 16:56:42 -0800935 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700936 // Don't save anything in private browsing mode
937 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800938 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700939
John Reck324d4402011-01-11 16:56:42 -0800940 if (TextUtils.isEmpty(url)
941 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700942 return;
943 }
John Reckf57c0292011-07-21 18:15:39 -0700944 DataController.getInstance(mActivity).updateVisitedHistory(url);
John Reck6c2e2f32011-08-22 13:41:23 -0700945 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -0700946 }
947
948 @Override
949 public void getVisitedHistory(final ValueCallback<String[]> callback) {
950 AsyncTask<Void, Void, String[]> task =
951 new AsyncTask<Void, Void, String[]>() {
952 @Override
953 public String[] doInBackground(Void... unused) {
954 return Browser.getVisitedHistory(mActivity.getContentResolver());
955 }
956 @Override
957 public void onPostExecute(String[] result) {
958 callback.onReceiveValue(result);
959 }
960 };
961 task.execute();
962 }
963
964 @Override
965 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
966 final HttpAuthHandler handler, final String host,
967 final String realm) {
968 String username = null;
969 String password = null;
970
971 boolean reuseHttpAuthUsernamePassword
972 = handler.useHttpAuthUsernamePassword();
973
974 if (reuseHttpAuthUsernamePassword && view != null) {
975 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
976 if (credentials != null && credentials.length == 2) {
977 username = credentials[0];
978 password = credentials[1];
979 }
980 }
981
982 if (username != null && password != null) {
983 handler.proceed(username, password);
984 } else {
Ben Murdochfdd37112011-08-05 15:48:14 +0100985 if (tab.inForeground() && !handler.suppressDialog()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700986 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
987 } else {
988 handler.cancel();
989 }
990 }
991 }
992
993 @Override
994 public void onDownloadStart(Tab tab, String url, String userAgent,
995 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000996 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -0500997 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000998 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
999 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001000 // This Tab was opened for the sole purpose of downloading a
1001 // file. Remove it.
1002 if (tab == mTabControl.getCurrentTab()) {
1003 // In this case, the Tab is still on top.
1004 goBackOnePageOrQuit();
1005 } else {
1006 // In this case, it is not.
1007 closeTab(tab);
1008 }
1009 }
1010 }
1011
1012 @Override
1013 public Bitmap getDefaultVideoPoster() {
1014 return mUi.getDefaultVideoPoster();
1015 }
1016
1017 @Override
1018 public View getVideoLoadingProgressView() {
1019 return mUi.getVideoLoadingProgressView();
1020 }
1021
1022 @Override
1023 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1024 SslError error) {
1025 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1026 }
1027
Patrick Scott92066772011-03-10 08:46:27 -05001028 @Override
1029 public void showAutoLogin(Tab tab) {
1030 assert tab.inForeground();
1031 // Update the title bar to show the auto-login request.
1032 mUi.showAutoLogin(tab);
1033 }
1034
1035 @Override
1036 public void hideAutoLogin(Tab tab) {
1037 assert tab.inForeground();
1038 mUi.hideAutoLogin(tab);
1039 }
1040
Michael Kolb8233fac2010-10-26 16:08:53 -07001041 // helper method
1042
1043 /*
1044 * Update the favorites icon if the private browsing isn't enabled and the
1045 * icon is valid.
1046 */
1047 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1048 final String url, Bitmap favicon) {
1049 if (favicon == null) {
1050 return;
1051 }
1052 if (!tab.isPrivateBrowsingEnabled()) {
1053 Bookmarks.updateFavicon(mActivity
1054 .getContentResolver(), originalUrl, url, favicon);
1055 }
1056 }
1057
Leon Scroggins4cd97792010-12-03 15:31:56 -05001058 @Override
1059 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001060 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001061 mUi.bookmarkedStatusHasChanged(tab);
1062 }
1063
Michael Kolb8233fac2010-10-26 16:08:53 -07001064 // end WebViewController
1065
1066 protected void pageUp() {
1067 getCurrentTopWebView().pageUp(false);
1068 }
1069
1070 protected void pageDown() {
1071 getCurrentTopWebView().pageDown(false);
1072 }
1073
1074 // callback from phone title bar
1075 public void editUrl() {
1076 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001077 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001078 }
1079
Michael Kolbcfa3af52010-12-14 10:36:11 -08001080 public void startVoiceSearch() {
1081 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1082 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1083 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1084 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1085 mActivity.getComponentName().flattenToString());
1086 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001087 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001088 mActivity.startActivity(intent);
1089 }
1090
Michael Kolb11d19782011-03-20 10:17:40 -07001091 @Override
1092 public void activateVoiceSearchMode(String title, List<String> results) {
1093 mUi.showVoiceTitleBar(title, results);
Michael Kolb8233fac2010-10-26 16:08:53 -07001094 }
1095
1096 public void revertVoiceSearchMode(Tab tab) {
1097 mUi.revertVoiceTitleBar(tab);
1098 }
1099
Michael Kolb736990c2011-03-20 10:01:20 -07001100 public boolean supportsVoiceSearch() {
John Reck35e9dd62011-04-25 09:01:54 -07001101 SearchEngine searchEngine = getSettings().getSearchEngine();
Michael Kolb736990c2011-03-20 10:01:20 -07001102 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1103 }
1104
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001105 public void showCustomView(Tab tab, View view, int requestedOrientation,
Michael Kolb8233fac2010-10-26 16:08:53 -07001106 WebChromeClient.CustomViewCallback callback) {
1107 if (tab.inForeground()) {
1108 if (mUi.isCustomViewShowing()) {
1109 callback.onCustomViewHidden();
1110 return;
1111 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001112 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001113 // Save the menu state and set it to empty while the custom
1114 // view is showing.
1115 mOldMenuState = mMenuState;
1116 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001117 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001118 }
1119 }
1120
1121 @Override
1122 public void hideCustomView() {
1123 if (mUi.isCustomViewShowing()) {
1124 mUi.onHideCustomView();
1125 // Reset the old menu state.
1126 mMenuState = mOldMenuState;
1127 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001128 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001129 }
1130 }
1131
1132 protected void onActivityResult(int requestCode, int resultCode,
1133 Intent intent) {
1134 if (getCurrentTopWebView() == null) return;
1135 switch (requestCode) {
1136 case PREFERENCES_PAGE:
1137 if (resultCode == Activity.RESULT_OK && intent != null) {
1138 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001139 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001140 mTabControl.removeParentChildRelationShips();
1141 }
1142 }
1143 break;
1144 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001145 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001146 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001147 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001148 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001149 case AUTOFILL_SETUP:
1150 // Determine whether a profile was actually set up or not
1151 // and if so, send the message back to the WebTextView to
1152 // fill the form with the new profile.
1153 if (getSettings().getAutoFillProfile() != null) {
1154 mAutoFillSetupMessage.sendToTarget();
1155 mAutoFillSetupMessage = null;
1156 }
1157 break;
John Reckd3e4d5b2011-07-13 15:48:43 -07001158 case COMBO_VIEW:
1159 if (intent == null || resultCode != Activity.RESULT_OK) {
1160 break;
1161 }
John Reck3ba45532011-08-11 16:26:53 -07001162 mUi.showWeb(false);
John Reckd3e4d5b2011-07-13 15:48:43 -07001163 if (Intent.ACTION_VIEW.equals(intent.getAction())) {
1164 Tab t = getCurrentTab();
1165 Uri uri = intent.getData();
1166 loadUrl(t, uri.toString());
1167 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
1168 String[] urls = intent.getStringArrayExtra(
1169 ComboViewActivity.EXTRA_OPEN_ALL);
1170 Tab parent = getCurrentTab();
1171 for (String url : urls) {
1172 parent = openTab(url, parent,
1173 !mSettings.openInBackground(), true);
1174 }
1175 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
1176 long id = intent.getLongExtra(
1177 ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
1178 if (id >= 0) {
1179 createNewSnapshotTab(id, true);
1180 }
1181 }
1182 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001183 default:
1184 break;
1185 }
1186 getCurrentTopWebView().requestFocus();
1187 }
1188
1189 /**
1190 * Open the Go page.
1191 * @param startWithHistory If true, open starting on the history tab.
1192 * Otherwise, start with the bookmarks tab.
1193 */
1194 @Override
1195 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1196 if (mTabControl.getCurrentWebView() == null) {
1197 return;
1198 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001199 // clear action mode
1200 if (isInCustomActionMode()) {
1201 endActionMode();
1202 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001203 Bundle extras = new Bundle();
1204 // Disable opening in a new window if we have maxed out the windows
1205 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1206 !mTabControl.canCreateNewTab());
John Reck2bc80422011-06-30 15:11:49 -07001207 mUi.showComboView(startWithHistory
1208 ? ComboViews.History : ComboViews.Bookmarks, extras);
Michael Kolb8233fac2010-10-26 16:08:53 -07001209 }
1210
1211 // combo view callbacks
1212
Michael Kolb8233fac2010-10-26 16:08:53 -07001213 // key handling
1214 protected void onBackKey() {
1215 if (!mUi.onBackKey()) {
1216 WebView subwindow = mTabControl.getCurrentSubWindow();
1217 if (subwindow != null) {
1218 if (subwindow.canGoBack()) {
1219 subwindow.goBack();
1220 } else {
1221 dismissSubWindow(mTabControl.getCurrentTab());
1222 }
1223 } else {
1224 goBackOnePageOrQuit();
1225 }
1226 }
1227 }
1228
Michael Kolb4bd767d2011-05-27 11:33:55 -07001229 protected boolean onMenuKey() {
1230 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001231 }
1232
Michael Kolb8233fac2010-10-26 16:08:53 -07001233 // menu handling and state
1234 // TODO: maybe put into separate handler
1235
1236 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckd73c5a22010-12-22 10:22:50 -08001237 if (mMenuState == EMPTY_MENU) {
1238 return false;
1239 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001240 MenuInflater inflater = mActivity.getMenuInflater();
1241 inflater.inflate(R.menu.browser, menu);
1242 updateInLoadMenuItems(menu);
1243 // hold on to the menu reference here; it is used by the page callbacks
1244 // to update the menu based on loading state
1245 mCachedMenu = menu;
1246 return true;
1247 }
1248
1249 protected void onCreateContextMenu(ContextMenu menu, View v,
1250 ContextMenuInfo menuInfo) {
John Reck0f602f32011-07-07 15:38:43 -07001251 if (v instanceof TitleBar) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001252 return;
1253 }
1254 if (!(v instanceof WebView)) {
1255 return;
1256 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001257 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001258 WebView.HitTestResult result = webview.getHitTestResult();
1259 if (result == null) {
1260 return;
1261 }
1262
1263 int type = result.getType();
1264 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1265 Log.w(LOGTAG,
1266 "We should not show context menu when nothing is touched");
1267 return;
1268 }
1269 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1270 // let TextView handles context menu
1271 return;
1272 }
1273
1274 // Note, http://b/issue?id=1106666 is requesting that
1275 // an inflated menu can be used again. This is not available
1276 // yet, so inflate each time (yuk!)
1277 MenuInflater inflater = mActivity.getMenuInflater();
1278 inflater.inflate(R.menu.browsercontext, menu);
1279
1280 // Show the correct menu group
1281 final String extra = result.getExtra();
1282 menu.setGroupVisible(R.id.PHONE_MENU,
1283 type == WebView.HitTestResult.PHONE_TYPE);
1284 menu.setGroupVisible(R.id.EMAIL_MENU,
1285 type == WebView.HitTestResult.EMAIL_TYPE);
1286 menu.setGroupVisible(R.id.GEO_MENU,
1287 type == WebView.HitTestResult.GEO_TYPE);
1288 menu.setGroupVisible(R.id.IMAGE_MENU,
1289 type == WebView.HitTestResult.IMAGE_TYPE
1290 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1291 menu.setGroupVisible(R.id.ANCHOR_MENU,
1292 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1293 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001294 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1295 || type == WebView.HitTestResult.PHONE_TYPE
1296 || type == WebView.HitTestResult.EMAIL_TYPE
1297 || type == WebView.HitTestResult.GEO_TYPE;
1298 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1299 if (hitText) {
1300 menu.findItem(R.id.select_text_menu_id)
1301 .setOnMenuItemClickListener(new SelectText(webview));
1302 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001303 // Setup custom handling depending on the type
1304 switch (type) {
1305 case WebView.HitTestResult.PHONE_TYPE:
1306 menu.setHeaderTitle(Uri.decode(extra));
1307 menu.findItem(R.id.dial_context_menu_id).setIntent(
1308 new Intent(Intent.ACTION_VIEW, Uri
1309 .parse(WebView.SCHEME_TEL + extra)));
1310 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1311 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1312 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1313 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1314 addIntent);
1315 menu.findItem(R.id.copy_phone_context_menu_id)
1316 .setOnMenuItemClickListener(
1317 new Copy(extra));
1318 break;
1319
1320 case WebView.HitTestResult.EMAIL_TYPE:
1321 menu.setHeaderTitle(extra);
1322 menu.findItem(R.id.email_context_menu_id).setIntent(
1323 new Intent(Intent.ACTION_VIEW, Uri
1324 .parse(WebView.SCHEME_MAILTO + extra)));
1325 menu.findItem(R.id.copy_mail_context_menu_id)
1326 .setOnMenuItemClickListener(
1327 new Copy(extra));
1328 break;
1329
1330 case WebView.HitTestResult.GEO_TYPE:
1331 menu.setHeaderTitle(extra);
1332 menu.findItem(R.id.map_context_menu_id).setIntent(
1333 new Intent(Intent.ACTION_VIEW, Uri
1334 .parse(WebView.SCHEME_GEO
1335 + URLEncoder.encode(extra))));
1336 menu.findItem(R.id.copy_geo_context_menu_id)
1337 .setOnMenuItemClickListener(
1338 new Copy(extra));
1339 break;
1340
1341 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1342 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001343 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001344 // decide whether to show the open link in new tab option
1345 boolean showNewTab = mTabControl.canCreateNewTab();
1346 MenuItem newTabItem
1347 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001348 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001349 ? R.string.contextmenu_openlink_newwindow_background
1350 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001351 newTabItem.setVisible(showNewTab);
1352 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001353 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1354 newTabItem.setOnMenuItemClickListener(
1355 new MenuItem.OnMenuItemClickListener() {
1356 @Override
1357 public boolean onMenuItemClick(MenuItem item) {
1358 final HashMap<String, WebView> hrefMap =
1359 new HashMap<String, WebView>();
1360 hrefMap.put("webview", webview);
1361 final Message msg = mHandler.obtainMessage(
1362 FOCUS_NODE_HREF,
1363 R.id.open_newtab_context_menu_id,
1364 0, hrefMap);
1365 webview.requestFocusNodeHref(msg);
1366 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001367 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001368 });
1369 } else {
1370 newTabItem.setOnMenuItemClickListener(
1371 new MenuItem.OnMenuItemClickListener() {
1372 @Override
1373 public boolean onMenuItemClick(MenuItem item) {
1374 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001375 openTab(extra, parent,
1376 !mSettings.openInBackground(),
1377 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001378 return true;
1379 }
1380 });
1381 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001382 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001383 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1384 break;
1385 }
1386 // otherwise fall through to handle image part
1387 case WebView.HitTestResult.IMAGE_TYPE:
1388 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1389 menu.setHeaderTitle(extra);
1390 }
1391 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1392 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1393 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001394 setOnMenuItemClickListener(
1395 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001396 menu.findItem(R.id.set_wallpaper_context_menu_id).
1397 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1398 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001399 break;
1400
1401 default:
1402 Log.w(LOGTAG, "We should not get here.");
1403 break;
1404 }
1405 //update the ui
1406 mUi.onContextMenuCreated(menu);
1407 }
1408
1409 /**
1410 * As the menu can be open when loading state changes
1411 * we must manually update the state of the stop/reload menu
1412 * item
1413 */
1414 private void updateInLoadMenuItems(Menu menu) {
1415 if (menu == null) {
1416 return;
1417 }
1418 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1419 MenuItem src = mInLoad ?
1420 menu.findItem(R.id.stop_menu_id):
1421 menu.findItem(R.id.reload_menu_id);
1422 if (src != null) {
1423 dest.setIcon(src.getIcon());
1424 dest.setTitle(src.getTitle());
1425 }
1426 }
1427
John Reckb3417f02011-01-14 11:01:05 -08001428 boolean onPrepareOptionsMenu(Menu menu) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001429 // Note: setVisible will decide whether an item is visible; while
1430 // setEnabled() will decide whether an item is enabled, which also means
1431 // whether the matching shortcut key will function.
1432 switch (mMenuState) {
1433 case EMPTY_MENU:
1434 if (mCurrentMenuState != mMenuState) {
1435 menu.setGroupVisible(R.id.MAIN_MENU, false);
1436 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1437 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1438 }
1439 break;
1440 default:
1441 if (mCurrentMenuState != mMenuState) {
1442 menu.setGroupVisible(R.id.MAIN_MENU, true);
1443 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1444 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1445 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001446 updateMenuState(getCurrentTab(), menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001447 break;
1448 }
1449 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001450 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001451 }
1452
Michael Kolb4bf79712011-07-14 14:18:12 -07001453 @Override
1454 public void updateMenuState(Tab tab, Menu menu) {
1455 boolean canGoBack = false;
1456 boolean canGoForward = false;
1457 boolean isHome = false;
John Reck42229bc2011-08-19 13:26:43 -07001458 boolean isDesktopUa = false;
Michael Kolb4bf79712011-07-14 14:18:12 -07001459 if (tab != null) {
1460 canGoBack = tab.canGoBack();
1461 canGoForward = tab.canGoForward();
1462 isHome = mSettings.getHomePage().equals(tab.getUrl());
John Reck42229bc2011-08-19 13:26:43 -07001463 isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
Michael Kolb4bf79712011-07-14 14:18:12 -07001464 }
1465 final MenuItem back = menu.findItem(R.id.back_menu_id);
1466 back.setEnabled(canGoBack);
1467
1468 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1469 home.setEnabled(!isHome);
1470
1471 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1472 forward.setEnabled(canGoForward);
1473
1474 final MenuItem source = menu.findItem(mInLoad ? R.id.stop_menu_id : R.id.reload_menu_id);
1475 final MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolb7ab75ee2011-07-14 16:36:38 -07001476 if (source != null && dest != null) {
1477 dest.setTitle(source.getTitle());
1478 dest.setIcon(source.getIcon());
1479 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001480
1481 // decide whether to show the share link option
1482 PackageManager pm = mActivity.getPackageManager();
1483 Intent send = new Intent(Intent.ACTION_SEND);
1484 send.setType("text/plain");
1485 ResolveInfo ri = pm.resolveActivity(send,
1486 PackageManager.MATCH_DEFAULT_ONLY);
1487 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1488
1489 boolean isNavDump = mSettings.enableNavDump();
1490 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1491 nav.setVisible(isNavDump);
1492 nav.setEnabled(isNavDump);
1493
1494 boolean showDebugSettings = mSettings.isDebugEnabled();
1495 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1496 counter.setVisible(showDebugSettings);
1497 counter.setEnabled(showDebugSettings);
John Reck42229bc2011-08-19 13:26:43 -07001498 final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
1499 uaSwitcher.setChecked(isDesktopUa);
Michael Kolb4bf79712011-07-14 14:18:12 -07001500
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001501 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001502 }
1503
Michael Kolb8233fac2010-10-26 16:08:53 -07001504 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001505 if (null == getCurrentTopWebView()) {
1506 return false;
1507 }
1508 if (mMenuIsDown) {
1509 // The shortcut action consumes the MENU. Even if it is still down,
1510 // it won't trigger the next shortcut action. In the case of the
1511 // shortcut action triggering a new activity, like Bookmarks, we
1512 // won't get onKeyUp for MENU. So it is important to reset it here.
1513 mMenuIsDown = false;
1514 }
Michael Kolb3ca12752011-07-20 13:52:25 -07001515 if (mUi.onOptionsItemSelected(item)) {
1516 // ui callback handled it
1517 return true;
1518 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001519 switch (item.getItemId()) {
1520 // -- Main menu
1521 case R.id.new_tab_menu_id:
1522 openTabToHomePage();
1523 break;
1524
1525 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001526 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001527 break;
1528
1529 case R.id.goto_menu_id:
1530 editUrl();
1531 break;
1532
1533 case R.id.bookmarks_menu_id:
1534 bookmarksOrHistoryPicker(false);
1535 break;
1536
Michael Kolb8233fac2010-10-26 16:08:53 -07001537 case R.id.add_bookmark_menu_id:
John Recka60fffa2011-09-06 16:30:29 -07001538 Intent bookmarkIntent = createBookmarkCurrentPageIntent(false);
1539 if (bookmarkIntent != null) {
1540 mActivity.startActivity(bookmarkIntent);
1541 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001542 break;
1543
1544 case R.id.stop_reload_menu_id:
1545 if (mInLoad) {
1546 stopLoading();
1547 } else {
1548 getCurrentTopWebView().reload();
1549 }
1550 break;
1551
1552 case R.id.back_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001553 getCurrentTab().goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07001554 break;
1555
1556 case R.id.forward_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001557 getCurrentTab().goForward();
Michael Kolb8233fac2010-10-26 16:08:53 -07001558 break;
1559
1560 case R.id.close_menu_id:
1561 // Close the subwindow if it exists.
1562 if (mTabControl.getCurrentSubWindow() != null) {
1563 dismissSubWindow(mTabControl.getCurrentTab());
1564 break;
1565 }
1566 closeCurrentTab();
1567 break;
1568
1569 case R.id.homepage_menu_id:
1570 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07001571 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07001572 break;
1573
1574 case R.id.preferences_menu_id:
1575 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1576 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1577 getCurrentTopWebView().getUrl());
1578 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1579 break;
1580
1581 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001582 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001583 break;
1584
John Reck2bc80422011-06-30 15:11:49 -07001585 case R.id.save_snapshot_menu_id:
1586 final Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07001587 if (source == null) break;
John Reckd8c74522011-06-14 08:45:00 -07001588 final ContentResolver cr = mActivity.getContentResolver();
1589 final ContentValues values = source.createSnapshotValues();
John Reck2bc80422011-06-30 15:11:49 -07001590 if (values != null) {
1591 new AsyncTask<Tab, Void, Long>() {
John Reckd8c74522011-06-14 08:45:00 -07001592
John Reck2bc80422011-06-30 15:11:49 -07001593 @Override
1594 protected Long doInBackground(Tab... params) {
1595 Uri result = cr.insert(Snapshots.CONTENT_URI, values);
1596 long id = ContentUris.parseId(result);
1597 return id;
John Reckd8c74522011-06-14 08:45:00 -07001598 }
John Reckf33b1632011-06-04 20:00:23 -07001599
John Reck2bc80422011-06-30 15:11:49 -07001600 @Override
1601 protected void onPostExecute(Long id) {
1602 Bundle b = new Bundle();
1603 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
1604 mUi.showComboView(ComboViews.Snapshots, b);
1605 };
1606 }.execute(source);
1607 } else {
1608 Toast.makeText(mActivity, R.string.snapshot_failed,
Leon Scrogginsac993842011-02-02 12:54:07 -05001609 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001610 }
Leon Scrogginsac993842011-02-02 12:54:07 -05001611 break;
1612
Michael Kolb8233fac2010-10-26 16:08:53 -07001613 case R.id.page_info_menu_id:
Huahui Wuae0c0412011-06-28 10:17:05 -07001614 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001615 break;
1616
1617 case R.id.classic_history_menu_id:
1618 bookmarksOrHistoryPicker(true);
1619 break;
1620
Michael Kolb8233fac2010-10-26 16:08:53 -07001621 case R.id.share_page_menu_id:
1622 Tab currentTab = mTabControl.getCurrentTab();
1623 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001624 return false;
1625 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001626 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001627 break;
1628
1629 case R.id.dump_nav_menu_id:
1630 getCurrentTopWebView().debugDump();
1631 break;
1632
1633 case R.id.dump_counters_menu_id:
1634 getCurrentTopWebView().dumpV8Counters();
1635 break;
1636
1637 case R.id.zoom_in_menu_id:
1638 getCurrentTopWebView().zoomIn();
1639 break;
1640
1641 case R.id.zoom_out_menu_id:
1642 getCurrentTopWebView().zoomOut();
1643 break;
1644
1645 case R.id.view_downloads_menu_id:
1646 viewDownloads();
1647 break;
1648
John Reck42229bc2011-08-19 13:26:43 -07001649 case R.id.ua_desktop_menu_id:
1650 WebView web = getCurrentWebView();
1651 mSettings.toggleDesktopUseragent(web);
1652 web.loadUrl(web.getOriginalUrl());
1653 break;
1654
Michael Kolb8233fac2010-10-26 16:08:53 -07001655 case R.id.window_one_menu_id:
1656 case R.id.window_two_menu_id:
1657 case R.id.window_three_menu_id:
1658 case R.id.window_four_menu_id:
1659 case R.id.window_five_menu_id:
1660 case R.id.window_six_menu_id:
1661 case R.id.window_seven_menu_id:
1662 case R.id.window_eight_menu_id:
1663 {
1664 int menuid = item.getItemId();
1665 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1666 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1667 Tab desiredTab = mTabControl.getTab(id);
1668 if (desiredTab != null &&
1669 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001670 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001671 }
1672 break;
1673 }
1674 }
1675 }
1676 break;
1677
1678 default:
1679 return false;
1680 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001681 return true;
1682 }
1683
1684 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001685 // Let the History and Bookmark fragments handle menus they created.
1686 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1687 return false;
1688 }
1689
Michael Kolb8233fac2010-10-26 16:08:53 -07001690 int id = item.getItemId();
1691 boolean result = true;
1692 switch (id) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001693 // -- Browser context menu
1694 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001695 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001696 case R.id.copy_link_context_menu_id:
1697 final WebView webView = getCurrentTopWebView();
1698 if (null == webView) {
1699 result = false;
1700 break;
1701 }
1702 final HashMap<String, WebView> hrefMap =
1703 new HashMap<String, WebView>();
1704 hrefMap.put("webview", webView);
1705 final Message msg = mHandler.obtainMessage(
1706 FOCUS_NODE_HREF, id, 0, hrefMap);
1707 webView.requestFocusNodeHref(msg);
1708 break;
1709
1710 default:
1711 // For other context menus
1712 result = onOptionsItemSelected(item);
1713 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001714 return result;
1715 }
1716
1717 /**
1718 * support programmatically opening the context menu
1719 */
1720 public void openContextMenu(View view) {
1721 mActivity.openContextMenu(view);
1722 }
1723
1724 /**
1725 * programmatically open the options menu
1726 */
1727 public void openOptionsMenu() {
1728 mActivity.openOptionsMenu();
1729 }
1730
1731 public boolean onMenuOpened(int featureId, Menu menu) {
1732 if (mOptionsMenuOpen) {
1733 if (mConfigChanged) {
1734 // We do not need to make any changes to the state of the
1735 // title bar, since the only thing that happened was a
1736 // change in orientation
1737 mConfigChanged = false;
1738 } else {
1739 if (!mExtendedMenuOpen) {
1740 mExtendedMenuOpen = true;
1741 mUi.onExtendedMenuOpened();
1742 } else {
1743 // Switching the menu back to icon view, so show the
1744 // title bar once again.
1745 mExtendedMenuOpen = false;
1746 mUi.onExtendedMenuClosed(mInLoad);
Michael Kolb8233fac2010-10-26 16:08:53 -07001747 }
1748 }
1749 } else {
1750 // The options menu is closed, so open it, and show the title
1751 mOptionsMenuOpen = true;
1752 mConfigChanged = false;
1753 mExtendedMenuOpen = false;
1754 mUi.onOptionsMenuOpened();
1755 }
1756 return true;
1757 }
1758
1759 public void onOptionsMenuClosed(Menu menu) {
1760 mOptionsMenuOpen = false;
1761 mUi.onOptionsMenuClosed(mInLoad);
1762 }
1763
1764 public void onContextMenuClosed(Menu menu) {
1765 mUi.onContextMenuClosed(menu, mInLoad);
1766 }
1767
1768 // Helper method for getting the top window.
1769 @Override
1770 public WebView getCurrentTopWebView() {
1771 return mTabControl.getCurrentTopWebView();
1772 }
1773
1774 @Override
1775 public WebView getCurrentWebView() {
1776 return mTabControl.getCurrentWebView();
1777 }
1778
1779 /*
1780 * This method is called as a result of the user selecting the options
1781 * menu to see the download window. It shows the download window on top of
1782 * the current window.
1783 */
1784 void viewDownloads() {
1785 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1786 mActivity.startActivity(intent);
1787 }
1788
John Reck30b065e2011-07-19 10:58:05 -07001789 int getActionModeHeight() {
1790 TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
1791 new int[] { android.R.attr.actionBarSize });
1792 int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
1793 actionBarSizeTypedArray.recycle();
1794 return size;
1795 }
1796
Michael Kolb8233fac2010-10-26 16:08:53 -07001797 // action mode
1798
1799 void onActionModeStarted(ActionMode mode) {
1800 mUi.onActionModeStarted(mode);
1801 mActionMode = mode;
Michael Kolb42c0c062011-08-02 12:56:06 -07001802 if (mSimulateActionBarOverlayMode && !mUi.isEditingUrl()) {
John Reck30b065e2011-07-19 10:58:05 -07001803 WebView web = getCurrentWebView();
1804 // Simulate overlay mode by scrolling the webview the amount it will be
1805 // pushed down. Actual overlay mode doesn't work for us as otherwise
1806 // the CAB will, well, overlay the content, which breaks things like
1807 // find on page.
1808 int scrollBy = getActionModeHeight();
1809 web.scrollBy(0, scrollBy);
1810 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001811 }
1812
1813 /*
1814 * True if a custom ActionMode (i.e. find or select) is in use.
1815 */
1816 @Override
1817 public boolean isInCustomActionMode() {
1818 return mActionMode != null;
1819 }
1820
1821 /*
1822 * End the current ActionMode.
1823 */
1824 @Override
1825 public void endActionMode() {
1826 if (mActionMode != null) {
1827 mActionMode.finish();
1828 }
1829 }
1830
1831 /*
1832 * Called by find and select when they are finished. Replace title bars
1833 * as necessary.
1834 */
1835 public void onActionModeFinished(ActionMode mode) {
1836 if (!isInCustomActionMode()) return;
1837 mUi.onActionModeFinished(mInLoad);
1838 mActionMode = null;
John Reck30b065e2011-07-19 10:58:05 -07001839 if (mSimulateActionBarOverlayMode) {
1840 WebView web = getCurrentWebView();
1841 int scrollBy = getActionModeHeight();
1842 web.scrollBy(0, -scrollBy);
1843 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001844 }
1845
1846 boolean isInLoad() {
1847 return mInLoad;
1848 }
1849
1850 // bookmark handling
1851
1852 /**
1853 * add the current page as a bookmark to the given folder id
1854 * @param folderId use -1 for the default folder
John Reckd3e4d5b2011-07-13 15:48:43 -07001855 * @param editExisting If true, check to see whether the site is already
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001856 * bookmarked, and if it is, edit that bookmark. If false, and
1857 * the site is already bookmarked, do not attempt to edit the
1858 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001859 */
1860 @Override
John Reckd3e4d5b2011-07-13 15:48:43 -07001861 public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
John Recka60fffa2011-09-06 16:30:29 -07001862 WebView w = getCurrentTopWebView();
1863 if (w == null) {
1864 return null;
1865 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001866 Intent i = new Intent(mActivity,
1867 AddBookmarkPage.class);
Michael Kolb8233fac2010-10-26 16:08:53 -07001868 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1869 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1870 String touchIconUrl = w.getTouchIconUrl();
1871 if (touchIconUrl != null) {
1872 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1873 WebSettings settings = w.getSettings();
1874 if (settings != null) {
1875 i.putExtra(AddBookmarkPage.USER_AGENT,
1876 settings.getUserAgentString());
1877 }
1878 }
1879 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1880 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1881 getDesiredThumbnailHeight(mActivity)));
1882 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07001883 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001884 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1885 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001886 // Put the dialog at the upper right of the screen, covering the
1887 // star on the title bar.
1888 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07001889 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07001890 }
1891
1892 // file chooser
1893 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1894 mUploadHandler = new UploadHandler(this);
1895 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1896 }
1897
1898 // thumbnails
1899
1900 /**
1901 * Return the desired width for thumbnail screenshots, which are stored in
1902 * the database, and used on the bookmarks screen.
1903 * @param context Context for finding out the density of the screen.
1904 * @return desired width for thumbnail screenshot.
1905 */
1906 static int getDesiredThumbnailWidth(Context context) {
1907 return context.getResources().getDimensionPixelOffset(
1908 R.dimen.bookmarkThumbnailWidth);
1909 }
1910
1911 /**
1912 * Return the desired height for thumbnail screenshots, which are stored in
1913 * the database, and used on the bookmarks screen.
1914 * @param context Context for finding out the density of the screen.
1915 * @return desired height for thumbnail screenshot.
1916 */
1917 static int getDesiredThumbnailHeight(Context context) {
1918 return context.getResources().getDimensionPixelOffset(
1919 R.dimen.bookmarkThumbnailHeight);
1920 }
1921
John Reck8cc92352011-07-06 17:41:52 -07001922 static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001923 // We render to a bitmap 2x the desired size so that we can then
1924 // re-scale it with filtering since canvas.scale doesn't filter
1925 // This helps reduce aliasing at the cost of being slightly blurry
1926 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001927 Picture thumbnail = view.capturePicture();
1928 if (thumbnail == null) {
1929 return null;
1930 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001931 width *= filter_scale;
1932 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001933 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1934 Canvas canvas = new Canvas(bm);
1935 // May need to tweak these values to determine what is the
1936 // best scale factor
1937 int thumbnailWidth = thumbnail.getWidth();
1938 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001939 float scaleFactor = 1.0f;
Michael Kolbeb95db42011-03-03 10:38:40 -08001940 if (thumbnailWidth > 0 && thumbnailHeight > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001941 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001942 } else {
1943 return null;
1944 }
John Reckfe49ab42010-11-16 17:09:37 -08001945
Michael Kolbeb95db42011-03-03 10:38:40 -08001946 float scaleFactorY = (float) height / (float)thumbnailHeight;
1947 if (scaleFactorY > scaleFactor) {
1948 // The picture is narrower than the requested AR
1949 // Center the thumnail and crop the sides
1950 scaleFactor = scaleFactorY;
John Reckfe49ab42010-11-16 17:09:37 -08001951 float wx = (thumbnailWidth * scaleFactor) - width;
1952 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001953 }
1954
John Reckfe49ab42010-11-16 17:09:37 -08001955 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001956
1957 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001958 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
1959 height / filter_scale, true);
Dianne Hackborn43cfe8a2011-08-02 16:59:35 -07001960 canvas.setBitmap(null);
John Reck5c6ac2f2011-01-05 10:18:03 -08001961 bm.recycle();
1962 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001963 }
1964
John Reck34ef2672011-02-10 11:30:55 -08001965 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001966 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07001967 // FIXME: Would like to make sure there is actually something to
1968 // draw, but the API for that (WebViewCore.pictureReady()) is not
1969 // currently accessible here.
1970
John Reck34ef2672011-02-10 11:30:55 -08001971 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08001972 if (view == null) {
1973 // Tab was destroyed
1974 return;
1975 }
John Reck34ef2672011-02-10 11:30:55 -08001976 final String url = tab.getUrl();
1977 final String originalUrl = view.getOriginalUrl();
1978
1979 if (TextUtils.isEmpty(url)) {
1980 return;
1981 }
1982
1983 // Only update thumbnails for web urls (http(s)://), not for
1984 // about:, javascript:, data:, etc...
1985 // Unless it is a bookmarked site, then always update
1986 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
1987 return;
1988 }
1989
Michael Kolb8233fac2010-10-26 16:08:53 -07001990 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1991 getDesiredThumbnailHeight(mActivity));
1992 if (bm == null) {
1993 return;
1994 }
1995
1996 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08001997 new AsyncTask<Void, Void, Void>() {
1998 @Override
1999 protected Void doInBackground(Void... unused) {
2000 Cursor cursor = null;
2001 try {
2002 // TODO: Clean this up
2003 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2004 if (cursor != null && cursor.moveToFirst()) {
2005 final ByteArrayOutputStream os =
2006 new ByteArrayOutputStream();
2007 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002008
John Reck34ef2672011-02-10 11:30:55 -08002009 ContentValues values = new ContentValues();
2010 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002011
John Reck34ef2672011-02-10 11:30:55 -08002012 do {
John Reck617fd832011-02-16 14:35:59 -08002013 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002014 cr.update(Images.CONTENT_URI, values, null, null);
2015 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002016 }
John Reck34ef2672011-02-10 11:30:55 -08002017 } catch (IllegalStateException e) {
2018 // Ignore
2019 } finally {
2020 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002021 }
John Reck34ef2672011-02-10 11:30:55 -08002022 return null;
2023 }
2024 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002025 }
2026
2027 private class Copy implements OnMenuItemClickListener {
2028 private CharSequence mText;
2029
2030 public boolean onMenuItemClick(MenuItem item) {
2031 copy(mText);
2032 return true;
2033 }
2034
2035 public Copy(CharSequence toCopy) {
2036 mText = toCopy;
2037 }
2038 }
2039
Leon Scroggins63c02662010-11-18 15:16:27 -05002040 private static class Download implements OnMenuItemClickListener {
2041 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002042 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002043 private boolean mPrivateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002044
2045 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002046 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002047 null, null, mPrivateBrowsing);
Michael Kolb8233fac2010-10-26 16:08:53 -07002048 return true;
2049 }
2050
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002051 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002052 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002053 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002054 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002055 }
2056 }
2057
Cary Clark8974d282010-11-22 10:46:05 -05002058 private static class SelectText implements OnMenuItemClickListener {
2059 private WebView mWebView;
2060
2061 public boolean onMenuItemClick(MenuItem item) {
2062 if (mWebView != null) {
2063 return mWebView.selectText();
2064 }
2065 return false;
2066 }
2067
2068 public SelectText(WebView webView) {
2069 mWebView = webView;
2070 }
2071
2072 }
2073
Michael Kolb8233fac2010-10-26 16:08:53 -07002074 /********************** TODO: UI stuff *****************************/
2075
2076 // these methods have been copied, they still need to be cleaned up
2077
2078 /****************** tabs ***************************************************/
2079
2080 // basic tab interactions:
2081
2082 // it is assumed that tabcontrol already knows about the tab
2083 protected void addTab(Tab tab) {
2084 mUi.addTab(tab);
2085 }
2086
2087 protected void removeTab(Tab tab) {
2088 mUi.removeTab(tab);
2089 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002090 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002091 }
2092
Michael Kolbf2055602011-04-09 17:20:03 -07002093 @Override
2094 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002095 // monkey protection against delayed start
2096 if (tab != null) {
2097 mTabControl.setCurrentTab(tab);
2098 // the tab is guaranteed to have a webview after setCurrentTab
2099 mUi.setActiveTab(tab);
2100 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002101 }
2102
John Reck8bcafc12011-08-29 16:43:02 -07002103 protected void closeEmptyTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002104 Tab current = mTabControl.getCurrentTab();
2105 if (current != null
2106 && current.getWebView().copyBackForwardList().getSize() == 0) {
John Reck8bcafc12011-08-29 16:43:02 -07002107 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002108 }
2109 }
2110
John Reck26b18322011-06-21 13:08:58 -07002111 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002112 // Dismiss the subwindow if applicable.
2113 dismissSubWindow(appTab);
2114 // Since we might kill the WebView, remove it from the
2115 // content view first.
2116 mUi.detachTab(appTab);
2117 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002118 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002119 // TODO: analyze why the remove and add are necessary
2120 mUi.attachTab(appTab);
2121 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002122 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002123 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002124 } else {
2125 // If the tab was the current tab, we have to attach
2126 // it to the view system again.
2127 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002128 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002129 }
2130 }
2131
2132 // Remove the sub window if it exists. Also called by TabControl when the
2133 // user clicks the 'X' to dismiss a sub window.
2134 public void dismissSubWindow(Tab tab) {
2135 removeSubWindow(tab);
2136 // dismiss the subwindow. This will destroy the WebView.
2137 tab.dismissSubWindow();
2138 getCurrentTopWebView().requestFocus();
2139 }
2140
2141 @Override
2142 public void removeSubWindow(Tab t) {
2143 if (t.getSubWebView() != null) {
2144 mUi.removeSubWindow(t.getSubViewContainer());
2145 }
2146 }
2147
2148 @Override
2149 public void attachSubWindow(Tab tab) {
2150 if (tab.getSubWebView() != null) {
2151 mUi.attachSubWindow(tab.getSubViewContainer());
2152 getCurrentTopWebView().requestFocus();
2153 }
2154 }
2155
Mathew Inwood29721c22011-06-29 17:55:24 +01002156 private Tab showPreloadedTab(final UrlData urlData) {
2157 if (!urlData.isPreloaded()) {
2158 return null;
2159 }
2160 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2161 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2162 if (sbQuery != null) {
2163 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
2164 // Could not submit query. Fallback to regular tab creation
2165 tabControl.destroy();
2166 return null;
2167 }
2168 }
Michael Kolbff6a7482011-07-26 16:37:15 -07002169 // check tab count and make room for new tab
2170 if (!mTabControl.canCreateNewTab()) {
2171 Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
2172 if (leastUsed != null) {
2173 closeTab(leastUsed);
2174 }
2175 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002176 Tab t = tabControl.getTab();
Mathew Inwoode09305e2011-09-02 12:03:26 +01002177 t.refreshIdAfterPreload();
Mathew Inwood29721c22011-06-29 17:55:24 +01002178 mTabControl.addPreloadedTab(t);
2179 addTab(t);
2180 setActiveTab(t);
2181 return t;
2182 }
2183
Michael Kolb7bcafde2011-05-09 13:55:59 -07002184 // open a non inconito tab with the given url data
2185 // and set as active tab
2186 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002187 Tab tab = showPreloadedTab(urlData);
2188 if (tab == null) {
2189 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002190 if ((tab != null) && !urlData.isEmpty()) {
2191 loadUrlDataIn(tab, urlData);
2192 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002193 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002194 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002195 }
2196
Michael Kolb843510f2010-12-09 10:51:49 -08002197 @Override
2198 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002199 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002200 }
2201
Michael Kolb8233fac2010-10-26 16:08:53 -07002202 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002203 public Tab openIncognitoTab() {
2204 return openTab(INCOGNITO_URI, true, true, false);
2205 }
2206
2207 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002208 public Tab openTab(String url, boolean incognito, boolean setActive,
2209 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002210 return openTab(url, incognito, setActive, useCurrent, null);
2211 }
2212
2213 @Override
2214 public Tab openTab(String url, Tab parent, boolean setActive,
2215 boolean useCurrent) {
2216 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2217 setActive, useCurrent, parent);
2218 }
2219
2220 public Tab openTab(String url, boolean incognito, boolean setActive,
2221 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002222 Tab tab = createNewTab(incognito, setActive, useCurrent);
2223 if (tab != null) {
John Reck5949c662011-05-27 09:52:29 -07002224 if (parent != null && parent != tab) {
2225 parent.addChildTab(tab);
2226 }
Michael Kolb519d2282011-05-09 17:03:19 -07002227 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002228 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002229 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002230 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002231 return tab;
2232 }
2233
2234 // this method will attempt to create a new tab
2235 // incognito: private browsing tab
2236 // setActive: ste tab as current tab
2237 // useCurrent: if no new tab can be created, return current tab
2238 private Tab createNewTab(boolean incognito, boolean setActive,
2239 boolean useCurrent) {
2240 Tab tab = null;
2241 if (mTabControl.canCreateNewTab()) {
2242 tab = mTabControl.createNewTab(incognito);
2243 addTab(tab);
2244 if (setActive) {
2245 setActiveTab(tab);
2246 }
2247 } else {
2248 if (useCurrent) {
2249 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002250 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002251 } else {
2252 mUi.showMaxTabsWarning();
2253 }
2254 }
2255 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002256 }
2257
John Reck2bc80422011-06-30 15:11:49 -07002258 @Override
2259 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2260 SnapshotTab tab = null;
2261 if (mTabControl.canCreateNewTab()) {
2262 tab = mTabControl.createSnapshotTab(snapshotId);
2263 addTab(tab);
2264 if (setActive) {
2265 setActiveTab(tab);
2266 }
2267 } else {
2268 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07002269 }
2270 return tab;
2271 }
2272
Michael Kolb8233fac2010-10-26 16:08:53 -07002273 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002274 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002275 * @return boolean True if we successfully switched to a different tab. If
2276 * the indexth tab is null, or if that tab is the same as
2277 * the current one, return false.
2278 */
2279 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002280 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002281 Tab currentTab = mTabControl.getCurrentTab();
2282 if (tab == null || tab == currentTab) {
2283 return false;
2284 }
2285 setActiveTab(tab);
2286 return true;
2287 }
2288
2289 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002290 public void closeCurrentTab() {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002291 closeCurrentTab(false);
2292 }
2293
2294 protected void closeCurrentTab(boolean andQuit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002295 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07002296 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07002297 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08002298 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002299 return;
2300 }
Michael Kolbc831b632011-05-11 09:30:34 -07002301 final Tab current = mTabControl.getCurrentTab();
2302 final int pos = mTabControl.getCurrentPosition();
2303 Tab newTab = current.getParent();
2304 if (newTab == null) {
2305 newTab = mTabControl.getTab(pos + 1);
2306 if (newTab == null) {
2307 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002308 }
2309 }
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002310 if (andQuit) {
2311 mTabControl.setCurrentTab(newTab);
2312 closeTab(current);
2313 } else if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002314 // Close window
2315 closeTab(current);
2316 }
2317 }
2318
2319 /**
2320 * Close the tab, remove its associated title bar, and adjust mTabControl's
2321 * current tab to a valid value.
2322 */
2323 @Override
2324 public void closeTab(Tab tab) {
Michael Kolb2d59c322011-01-25 13:18:55 -08002325 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002326 }
2327
Michael Kolb8233fac2010-10-26 16:08:53 -07002328 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07002329 protected void loadUrlFromContext(String url) {
2330 Tab tab = getCurrentTab();
2331 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002332 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07002333 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002334 url = UrlUtils.smartUrlFilter(url);
2335 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07002336 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07002337 }
2338 }
2339 }
2340
2341 /**
2342 * Load the URL into the given WebView and update the title bar
2343 * to reflect the new load. Call this instead of WebView.loadUrl
2344 * directly.
2345 * @param view The WebView used to load url.
2346 * @param url The URL to load.
2347 */
John Reck71e51422011-07-01 16:49:28 -07002348 @Override
2349 public void loadUrl(Tab tab, String url) {
John Reck26b18322011-06-21 13:08:58 -07002350 loadUrl(tab, url, null);
2351 }
2352
2353 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
2354 if (tab != null) {
2355 dismissSubWindow(tab);
2356 tab.loadUrl(url, headers);
2357 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002358 }
2359
2360 /**
2361 * Load UrlData into a Tab and update the title bar to reflect the new
2362 * load. Call this instead of UrlData.loadIn directly.
2363 * @param t The Tab used to load.
2364 * @param data The UrlData being loaded.
2365 */
2366 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07002367 if (data != null) {
2368 if (data.mVoiceIntent != null) {
2369 t.activateVoiceSearchMode(data.mVoiceIntent);
Michael Kolb14612442011-06-24 13:06:29 -07002370 } else if (data.isPreloaded()) {
2371 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07002372 } else {
2373 loadUrl(t, data.mUrl, data.mHeaders);
2374 }
2375 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002376 }
2377
John Reck30c714c2010-12-16 17:30:34 -08002378 @Override
2379 public void onUserCanceledSsl(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08002380 // TODO: Figure out the "right" behavior
John Reckef654f12011-07-12 16:42:08 -07002381 if (tab.canGoBack()) {
2382 tab.goBack();
John Reck30c714c2010-12-16 17:30:34 -08002383 } else {
John Reckef654f12011-07-12 16:42:08 -07002384 tab.loadUrl(mSettings.getHomePage(), null);
John Reck30c714c2010-12-16 17:30:34 -08002385 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002386 }
2387
2388 void goBackOnePageOrQuit() {
2389 Tab current = mTabControl.getCurrentTab();
2390 if (current == null) {
2391 /*
2392 * Instead of finishing the activity, simply push this to the back
2393 * of the stack and let ActivityManager to choose the foreground
2394 * activity. As BrowserActivity is singleTask, it will be always the
2395 * root of the task. So we can use either true or false for
2396 * moveTaskToBack().
2397 */
2398 mActivity.moveTaskToBack(true);
2399 return;
2400 }
John Reckef654f12011-07-12 16:42:08 -07002401 if (current.canGoBack()) {
2402 current.goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07002403 } else {
2404 // Check to see if we are closing a window that was created by
2405 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002406 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002407 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002408 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002409 // Now we close the other tab
2410 closeTab(current);
2411 } else {
Michael Kolbe28b3472011-08-04 16:54:31 -07002412 if ((current.getAppId() != null) || current.closeOnBack()) {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002413 closeCurrentTab(true);
Michael Kolbe28b3472011-08-04 16:54:31 -07002414 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002415 /*
2416 * Instead of finishing the activity, simply push this to the back
2417 * of the stack and let ActivityManager to choose the foreground
2418 * activity. As BrowserActivity is singleTask, it will be always the
2419 * root of the task. So we can use either true or false for
2420 * moveTaskToBack().
2421 */
2422 mActivity.moveTaskToBack(true);
2423 }
2424 }
2425 }
2426
2427 /**
2428 * Feed the previously stored results strings to the BrowserProvider so that
2429 * the SearchDialog will show them instead of the standard searches.
2430 * @param result String to show on the editable line of the SearchDialog.
2431 */
2432 @Override
2433 public void showVoiceSearchResults(String result) {
2434 ContentProviderClient client = mActivity.getContentResolver()
2435 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2436 ContentProvider prov = client.getLocalContentProvider();
2437 BrowserProvider bp = (BrowserProvider) prov;
2438 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2439 client.release();
2440
2441 Bundle bundle = createGoogleSearchSourceBundle(
2442 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2443 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2444 startSearch(result, false, bundle, false);
2445 }
2446
2447 private void startSearch(String initialQuery, boolean selectInitialQuery,
2448 Bundle appSearchData, boolean globalSearch) {
2449 if (appSearchData == null) {
2450 appSearchData = createGoogleSearchSourceBundle(
2451 GOOGLE_SEARCH_SOURCE_TYPE);
2452 }
2453
2454 SearchEngine searchEngine = mSettings.getSearchEngine();
2455 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2456 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2457 }
2458 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2459 globalSearch);
2460 }
2461
2462 private Bundle createGoogleSearchSourceBundle(String source) {
2463 Bundle bundle = new Bundle();
2464 bundle.putString(Search.SOURCE, source);
2465 return bundle;
2466 }
2467
2468 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002469 * helper method for key handler
2470 * returns the current tab if it can't advance
2471 */
Michael Kolbc831b632011-05-11 09:30:34 -07002472 private Tab getNextTab() {
2473 return mTabControl.getTab(Math.min(mTabControl.getTabCount() - 1,
2474 mTabControl.getCurrentPosition() + 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002475 }
2476
2477 /**
2478 * helper method for key handler
2479 * returns the current tab if it can't advance
2480 */
Michael Kolbc831b632011-05-11 09:30:34 -07002481 private Tab getPrevTab() {
2482 return mTabControl.getTab(Math.max(0,
2483 mTabControl.getCurrentPosition() - 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002484 }
2485
2486 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002487 * handle key events in browser
2488 *
2489 * @param keyCode
2490 * @param event
2491 * @return true if handled, false to pass to super
2492 */
2493 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002494 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002495 // Even if MENU is already held down, we need to call to super to open
2496 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002497 if (!noModifiers
2498 && ((KeyEvent.KEYCODE_MENU == keyCode)
2499 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2500 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002501 mMenuIsDown = true;
2502 return false;
2503 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002504
Cary Clark8ff8c662010-12-29 15:03:05 -05002505 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07002506 Tab tab = getCurrentTab();
2507 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05002508
Cary Clark160bbb92011-01-10 11:17:07 -05002509 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2510 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002511
Michael Kolb8233fac2010-10-26 16:08:53 -07002512 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002513 case KeyEvent.KEYCODE_TAB:
2514 if (event.isCtrlPressed()) {
2515 if (event.isShiftPressed()) {
2516 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002517 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002518 } else {
2519 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002520 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002521 }
2522 return true;
2523 }
2524 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002525 case KeyEvent.KEYCODE_SPACE:
2526 // WebView/WebTextView handle the keys in the KeyDown. As
2527 // the Activity's shortcut keys are only handled when WebView
2528 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002529 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002530 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002531 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002532 pageDown();
2533 }
2534 return true;
2535 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002536 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002537 event.startTracking();
2538 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07002539 case KeyEvent.KEYCODE_FORWARD:
2540 if (!noModifiers) break;
2541 tab.goForward();
2542 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002543 case KeyEvent.KEYCODE_DPAD_LEFT:
2544 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002545 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05002546 return true;
2547 }
2548 break;
2549 case KeyEvent.KEYCODE_DPAD_RIGHT:
2550 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002551 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05002552 return true;
2553 }
2554 break;
2555 case KeyEvent.KEYCODE_A:
2556 if (ctrl) {
2557 webView.selectAll();
2558 return true;
2559 }
2560 break;
Michael Kolba4183062011-01-16 10:43:21 -08002561// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002562 case KeyEvent.KEYCODE_C:
2563 if (ctrl) {
2564 webView.copySelection();
2565 return true;
2566 }
2567 break;
Michael Kolba4183062011-01-16 10:43:21 -08002568// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002569// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002570// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002571// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002572// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002573// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002574// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002575// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002576// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002577// case KeyEvent.KEYCODE_M: // unused
2578// case KeyEvent.KEYCODE_N: // in Chrome: new window
2579// case KeyEvent.KEYCODE_O: // in Chrome: open file
2580// case KeyEvent.KEYCODE_P: // in Chrome: print page
2581// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002582// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002583// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2584 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002585 // we can't use the ctrl/shift flags, they check for
2586 // exclusive use of a modifier
2587 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002588 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002589 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002590 } else {
2591 openTabToHomePage();
2592 }
2593 return true;
2594 }
2595 break;
2596// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2597// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb5ae15bd2011-08-16 17:09:27 -07002598// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002599// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2600// case KeyEvent.KEYCODE_Y: // unused
2601// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002602 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002603 // it is a regular key and webview is not null
2604 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002605 }
2606
John Recke6bf4ab2011-02-24 15:48:05 -08002607 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2608 switch(keyCode) {
2609 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07002610 if (mUi.isWebShowing()) {
John Recke6bf4ab2011-02-24 15:48:05 -08002611 bookmarksOrHistoryPicker(true);
2612 return true;
2613 }
2614 break;
2615 }
2616 return false;
2617 }
2618
Michael Kolb8233fac2010-10-26 16:08:53 -07002619 boolean onKeyUp(int keyCode, KeyEvent event) {
Michael Kolb2814a362011-05-19 15:49:41 -07002620 if (KeyEvent.KEYCODE_MENU == keyCode) {
2621 mMenuIsDown = false;
2622 if (event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002623 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002624 }
2625 }
Cary Clark160bbb92011-01-10 11:17:07 -05002626 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002627 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002628 case KeyEvent.KEYCODE_BACK:
2629 if (event.isTracking() && !event.isCanceled()) {
2630 onBackKey();
2631 return true;
2632 }
2633 break;
2634 }
2635 return false;
2636 }
2637
2638 public boolean isMenuDown() {
2639 return mMenuIsDown;
2640 }
2641
Ben Murdoch8029a772010-11-16 11:58:21 +00002642 public void setupAutoFill(Message message) {
2643 // Open the settings activity at the AutoFill profile fragment so that
2644 // the user can create a new profile. When they return, we will dispatch
2645 // the message so that we can autofill the form using their new profile.
2646 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2647 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2648 AutoFillSettingsFragment.class.getName());
2649 mAutoFillSetupMessage = message;
2650 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2651 }
John Reckb3417f02011-01-14 11:01:05 -08002652
2653 @Override
Narayan Kamath5119edd2011-02-23 15:49:17 +00002654 public void registerDropdownChangeListener(DropdownChangeListener d) {
2655 mUi.registerDropdownChangeListener(d);
2656 }
Michael Kolbfbc579a2011-07-07 15:59:33 -07002657
2658 public boolean onSearchRequested() {
2659 mUi.editUrl(false);
2660 return true;
2661 }
2662
John Reck1cf4b792011-07-26 10:22:22 -07002663 @Override
2664 public boolean shouldCaptureThumbnails() {
2665 return mUi.shouldCaptureThumbnails();
2666 }
2667
Michael Kolbc3af0672011-08-09 10:24:41 -07002668 @Override
2669 public void setBlockEvents(boolean block) {
2670 mBlockEvents = block;
2671 }
2672
2673 public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002674 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002675 }
2676
2677 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002678 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002679 }
2680
2681 public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002682 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002683 }
2684
2685 public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002686 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002687 }
2688
2689 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002690 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002691 }
2692
Michael Kolb8233fac2010-10-26 16:08:53 -07002693}