blob: 551be38ed591bc66f87a801f0c54045ce2e6ade6 [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;
Martijn Coenenb2f93552011-06-14 10:48:35 +0200160 private NfcHandler mNfcHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700161
Ben Murdoch8029a772010-11-16 11:58:21 +0000162 private Message mAutoFillSetupMessage;
163
Michael Kolb8233fac2010-10-26 16:08:53 -0700164 private boolean mShouldShowErrorConsole;
165
166 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
167
168 // FIXME, temp address onPrepareMenu performance problem.
169 // When we move everything out of view, we should rewrite this.
170 private int mCurrentMenuState = 0;
171 private int mMenuState = R.id.MAIN_MENU;
172 private int mOldMenuState = EMPTY_MENU;
173 private Menu mCachedMenu;
174
Michael Kolb8233fac2010-10-26 16:08:53 -0700175 private boolean mMenuIsDown;
176
177 // For select and find, we keep track of the ActionMode so that
178 // finish() can be called as desired.
179 private ActionMode mActionMode;
180
181 /**
182 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
183 * of whether the configuration has changed. The first onMenuOpened call
184 * after a configuration change is simply a reopening of the same menu
185 * (i.e. mIconView did not change).
186 */
187 private boolean mConfigChanged;
188
189 /**
190 * Keeps track of whether the options menu is open. This is important in
191 * determining whether to show or hide the title bar overlay
192 */
193 private boolean mOptionsMenuOpen;
194
195 /**
196 * Whether or not the options menu is in its bigger, popup menu form. When
197 * true, we want the title bar overlay to be gone. When false, we do not.
198 * Only meaningful if mOptionsMenuOpen is true.
199 */
200 private boolean mExtendedMenuOpen;
201
202 private boolean mInLoad;
203
204 private boolean mActivityPaused = true;
205 private boolean mLoadStopped;
206
207 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500208 // Checks to see when the bookmarks database has changed, and updates the
209 // Tabs' notion of whether they represent bookmarked sites.
210 private ContentObserver mBookmarksObserver;
John Reck847b5322011-04-14 17:02:18 -0700211 private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700212
John Reck30b065e2011-07-19 10:58:05 -0700213 private boolean mSimulateActionBarOverlayMode;
214
Michael Kolbc3af0672011-08-09 10:24:41 -0700215 private boolean mBlockEvents;
216
John Reckbc490d22011-07-22 15:04:59 -0700217 public Controller(Activity browser, boolean preloadCrashState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700218 mActivity = browser;
219 mSettings = BrowserSettings.getInstance();
220 mTabControl = new TabControl(this);
221 mSettings.setController(this);
John Reck378a4102011-06-09 16:23:01 -0700222 mCrashRecoveryHandler = CrashRecoveryHandler.initialize(this);
John Reckbc490d22011-07-22 15:04:59 -0700223 if (preloadCrashState) {
224 mCrashRecoveryHandler.preloadCrashState();
225 }
Michael Kolb14612442011-06-24 13:06:29 -0700226 mFactory = new BrowserWebViewFactory(browser);
Michael Kolb8233fac2010-10-26 16:08:53 -0700227
228 mUrlHandler = new UrlHandler(this);
229 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700230 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
Martijn Coenenb2f93552011-06-14 10:48:35 +0200231 mNfcHandler = new NfcHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700232
Michael Kolb8233fac2010-10-26 16:08:53 -0700233 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500234 mBookmarksObserver = new ContentObserver(mHandler) {
235 @Override
236 public void onChange(boolean selfChange) {
237 int size = mTabControl.getTabCount();
238 for (int i = 0; i < size; i++) {
239 mTabControl.getTab(i).updateBookmarkedStatus();
240 }
241 }
242
243 };
244 browser.getContentResolver().registerContentObserver(
245 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700246
247 mNetworkHandler = new NetworkStateHandler(mActivity, this);
248 // Start watching the default geolocation permissions
249 mSystemAllowGeolocationOrigins =
250 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
251 mSystemAllowGeolocationOrigins.start();
252
John Reckaf262e72011-07-25 13:55:44 -0700253 openIconDatabase();
John Reck30b065e2011-07-19 10:58:05 -0700254 mSimulateActionBarOverlayMode = !BrowserActivity.isTablet(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700255 }
256
Patrick Scott7d50a932011-02-04 09:27:26 -0500257 void start(final Bundle icicle, final Intent intent) {
Guang Zhu9e78f512011-05-04 11:45:11 -0700258 boolean noCrashRecovery = intent.getBooleanExtra(NO_CRASH_RECOVERY, false);
259 if (icicle != null || noCrashRecovery) {
John Reck847b5322011-04-14 17:02:18 -0700260 doStart(icicle, intent);
261 } else {
262 mCrashRecoveryHandler.startRecovery(intent);
263 }
264 }
265
266 void doStart(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700267 // Unless the last browser usage was within 24 hours, destroy any
268 // remaining incognito tabs.
269
270 Calendar lastActiveDate = icicle != null ?
271 (Calendar) icicle.getSerializable("lastActiveDate") : null;
272 Calendar today = Calendar.getInstance();
273 Calendar yesterday = Calendar.getInstance();
274 yesterday.add(Calendar.DATE, -1);
275
Patrick Scott7d50a932011-02-04 09:27:26 -0500276 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700277 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800278 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700279
Patrick Scott7d50a932011-02-04 09:27:26 -0500280 // Find out if we will restore any state and remember the tab.
Michael Kolbc831b632011-05-11 09:30:34 -0700281 final long currentTabId =
Patrick Scott7d50a932011-02-04 09:27:26 -0500282 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000283
Michael Kolbc831b632011-05-11 09:30:34 -0700284 if (currentTabId == -1) {
Patrick Scott7d50a932011-02-04 09:27:26 -0500285 // Not able to restore so we go ahead and clear session cookies. We
286 // must do this before trying to login the user as we don't want to
287 // clear any session cookies set during login.
288 CookieManager.getInstance().removeSessionCookie();
289 }
290
Patrick Scottd43e75a2011-03-14 14:47:23 -0400291 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500292 new Runnable() {
293 @Override public void run() {
Michael Kolbc831b632011-05-11 09:30:34 -0700294 onPreloginFinished(icicle, intent, currentTabId, restoreIncognitoTabs);
Patrick Scott7d50a932011-02-04 09:27:26 -0500295 }
296 });
297 }
298
Michael Kolbc831b632011-05-11 09:30:34 -0700299 private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId,
Patrick Scott7d50a932011-02-04 09:27:26 -0500300 boolean restoreIncognitoTabs) {
Michael Kolbc831b632011-05-11 09:30:34 -0700301 if (currentTabId == -1) {
John Reck1cf4b792011-07-26 10:22:22 -0700302 BackgroundHandler.execute(new PruneThumbnails(mActivity, null));
Michael Kolb8233fac2010-10-26 16:08:53 -0700303 final Bundle extra = intent.getExtras();
304 // Create an initial tab.
305 // If the intent is ACTION_VIEW and data is not null, the Browser is
306 // invoked to view the content by another application. In this case,
307 // the tab will be close when exit.
Michael Kolb14612442011-06-24 13:06:29 -0700308 UrlData urlData = IntentHandler.getUrlDataFromIntent(intent);
Michael Kolb7bcafde2011-05-09 13:55:59 -0700309 Tab t = null;
310 if (urlData.isEmpty()) {
311 t = openTabToHomePage();
312 } else {
313 t = openTab(urlData);
314 }
315 if (t != null) {
316 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
317 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700318 WebView webView = t.getWebView();
319 if (extra != null) {
320 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
321 if (scale > 0 && scale <= 1000) {
322 webView.setInitialScale(scale);
323 }
324 }
John Reckd8c74522011-06-14 08:45:00 -0700325 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700326 } else {
Michael Kolbc831b632011-05-11 09:30:34 -0700327 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
Patrick Scott7d50a932011-02-04 09:27:26 -0500328 mUi.needsRestoreAllTabs());
John Reck1cf4b792011-07-26 10:22:22 -0700329 List<Tab> tabs = mTabControl.getTabs();
330 ArrayList<Long> restoredTabs = new ArrayList<Long>(tabs.size());
331 for (Tab t : tabs) {
332 restoredTabs.add(t.getId());
333 }
334 BackgroundHandler.execute(new PruneThumbnails(mActivity, restoredTabs));
335 mUi.updateTabs(tabs);
Michael Kolb8233fac2010-10-26 16:08:53 -0700336 // TabControl.restoreState() will create a new tab even if
337 // restoring the state fails.
338 setActiveTab(mTabControl.getCurrentTab());
John Reckdb22ec42011-06-29 11:31:24 -0700339 // Handle the intent
340 mIntentHandler.onNewIntent(intent);
Michael Kolb8233fac2010-10-26 16:08:53 -0700341 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700342 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700343 String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb8233fac2010-10-26 16:08:53 -0700344 if (jsFlags.trim().length() != 0) {
345 getCurrentWebView().setJsFlags(jsFlags);
346 }
John Reck439c9a52010-12-14 10:04:39 -0800347 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
348 bookmarksOrHistoryPicker(false);
349 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700350 }
351
John Reck1cf4b792011-07-26 10:22:22 -0700352 private static class PruneThumbnails implements Runnable {
353 private Context mContext;
354 private List<Long> mIds;
355
356 PruneThumbnails(Context context, List<Long> preserveIds) {
357 mContext = context.getApplicationContext();
358 mIds = preserveIds;
359 }
360
361 @Override
362 public void run() {
363 ContentResolver cr = mContext.getContentResolver();
364 if (mIds == null || mIds.size() == 0) {
365 cr.delete(Thumbnails.CONTENT_URI, null, null);
366 } else {
367 int length = mIds.size();
368 StringBuilder where = new StringBuilder();
369 where.append(Thumbnails._ID);
370 where.append(" not in (");
371 for (int i = 0; i < length; i++) {
372 where.append(mIds.get(i));
373 if (i < (length - 1)) {
374 where.append(",");
375 }
376 }
377 where.append(")");
378 cr.delete(Thumbnails.CONTENT_URI, where.toString(), null);
379 }
380 }
381
382 }
383
Michael Kolb1514bb72010-11-22 09:11:48 -0800384 @Override
385 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700386 return mFactory;
387 }
388
389 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800390 public void onSetWebView(Tab tab, WebView view) {
391 mUi.onSetWebView(tab, view);
392 }
393
394 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800395 public void createSubWindow(Tab tab) {
396 endActionMode();
397 WebView mainView = tab.getWebView();
398 WebView subView = mFactory.createWebView((mainView == null)
399 ? false
400 : mainView.isPrivateBrowsingEnabled());
401 mUi.createSubWindow(tab, subView);
402 }
403
404 @Override
Michael Kolb14612442011-06-24 13:06:29 -0700405 public Context getContext() {
406 return mActivity;
407 }
408
409 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700410 public Activity getActivity() {
411 return mActivity;
412 }
413
414 void setUi(UI ui) {
415 mUi = ui;
416 }
417
418 BrowserSettings getSettings() {
419 return mSettings;
420 }
421
422 IntentHandler getIntentHandler() {
423 return mIntentHandler;
424 }
425
426 @Override
427 public UI getUi() {
428 return mUi;
429 }
430
431 int getMaxTabs() {
432 return mActivity.getResources().getInteger(R.integer.max_tabs);
433 }
434
435 @Override
436 public TabControl getTabControl() {
437 return mTabControl;
438 }
439
Michael Kolb1bf23132010-11-19 12:55:12 -0800440 @Override
441 public List<Tab> getTabs() {
442 return mTabControl.getTabs();
443 }
444
John Reckaf262e72011-07-25 13:55:44 -0700445 // Open the icon database.
446 private void openIconDatabase() {
447 // We have to call getInstance on the UI thread
448 final WebIconDatabase instance = WebIconDatabase.getInstance();
449 BackgroundHandler.execute(new Runnable() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000450
John Reckaf262e72011-07-25 13:55:44 -0700451 @Override
452 public void run() {
453 instance.open(mActivity.getDir("icons", 0).getPath());
Michael Kolb8233fac2010-10-26 16:08:53 -0700454 }
John Reckaf262e72011-07-25 13:55:44 -0700455 });
Michael Kolb8233fac2010-10-26 16:08:53 -0700456 }
457
458 private void startHandler() {
459 mHandler = new Handler() {
460
461 @Override
462 public void handleMessage(Message msg) {
463 switch (msg.what) {
464 case OPEN_BOOKMARKS:
465 bookmarksOrHistoryPicker(false);
466 break;
467 case FOCUS_NODE_HREF:
468 {
469 String url = (String) msg.getData().get("url");
470 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500471 String src = (String) msg.getData().get("src");
472 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700473 if (TextUtils.isEmpty(url)) {
474 break;
475 }
476 HashMap focusNodeMap = (HashMap) msg.obj;
477 WebView view = (WebView) focusNodeMap.get("webview");
478 // Only apply the action if the top window did not change.
479 if (getCurrentTopWebView() != view) {
480 break;
481 }
482 switch (msg.arg1) {
483 case R.id.open_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700484 loadUrlFromContext(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700485 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500486 case R.id.view_image_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700487 loadUrlFromContext(src);
Cary Clark043c2d62010-12-15 11:19:39 -0500488 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500489 case R.id.open_newtab_context_menu_id:
490 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -0700491 openTab(url, parent,
492 !mSettings.openInBackground(), true);
Leon Scroggins026f2542010-11-22 13:26:12 -0500493 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700494 case R.id.copy_link_context_menu_id:
495 copy(url);
496 break;
497 case R.id.save_link_context_menu_id:
498 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500499 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000500 mActivity, url, null, null, null,
501 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700502 break;
503 }
504 break;
505 }
506
507 case LOAD_URL:
John Reck26b18322011-06-21 13:08:58 -0700508 loadUrlFromContext((String) msg.obj);
Michael Kolb8233fac2010-10-26 16:08:53 -0700509 break;
510
511 case STOP_LOAD:
512 stopLoading();
513 break;
514
515 case RELEASE_WAKELOCK:
John Reckf57c0292011-07-21 18:15:39 -0700516 if (mWakeLock != null && mWakeLock.isHeld()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700517 mWakeLock.release();
518 // if we reach here, Browser should be still in the
519 // background loading after WAKELOCK_TIMEOUT (5-min).
520 // To avoid burning the battery, stop loading.
521 mTabControl.stopAllLoading();
522 }
523 break;
524
525 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800526 Tab tab = (Tab) msg.obj;
527 if (tab != null) {
528 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700529 }
530 break;
531 }
532 }
533 };
534
535 }
536
John Reckef654f12011-07-12 16:42:08 -0700537 @Override
Martijn Coenenb2f93552011-06-14 10:48:35 +0200538 public Tab getCurrentTab() {
539 return mTabControl.getCurrentTab();
540 }
541
Michael Kolbba99c5d2010-11-29 14:57:41 -0800542 @Override
543 public void shareCurrentPage() {
544 shareCurrentPage(mTabControl.getCurrentTab());
545 }
546
547 private void shareCurrentPage(Tab tab) {
548 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800549 sharePage(mActivity, tab.getTitle(),
550 tab.getUrl(), tab.getFavicon(),
551 createScreenshot(tab.getWebView(),
552 getDesiredThumbnailWidth(mActivity),
553 getDesiredThumbnailHeight(mActivity)));
554 }
555 }
556
Michael Kolb8233fac2010-10-26 16:08:53 -0700557 /**
558 * Share a page, providing the title, url, favicon, and a screenshot. Uses
559 * an {@link Intent} to launch the Activity chooser.
560 * @param c Context used to launch a new Activity.
561 * @param title Title of the page. Stored in the Intent with
562 * {@link Intent#EXTRA_SUBJECT}
563 * @param url URL of the page. Stored in the Intent with
564 * {@link Intent#EXTRA_TEXT}
565 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
566 * with {@link Browser#EXTRA_SHARE_FAVICON}
567 * @param screenshot Bitmap of a screenshot of the page. Stored in the
568 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
569 */
570 static final void sharePage(Context c, String title, String url,
571 Bitmap favicon, Bitmap screenshot) {
572 Intent send = new Intent(Intent.ACTION_SEND);
573 send.setType("text/plain");
574 send.putExtra(Intent.EXTRA_TEXT, url);
575 send.putExtra(Intent.EXTRA_SUBJECT, title);
576 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
577 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
578 try {
579 c.startActivity(Intent.createChooser(send, c.getString(
580 R.string.choosertitle_sharevia)));
581 } catch(android.content.ActivityNotFoundException ex) {
582 // if no app handles it, do nothing
583 }
584 }
585
586 private void copy(CharSequence text) {
587 ClipboardManager cm = (ClipboardManager) mActivity
588 .getSystemService(Context.CLIPBOARD_SERVICE);
589 cm.setText(text);
590 }
591
592 // lifecycle
593
594 protected void onConfgurationChanged(Configuration config) {
595 mConfigChanged = true;
596 if (mPageDialogsHandler != null) {
597 mPageDialogsHandler.onConfigurationChanged(config);
598 }
599 mUi.onConfigurationChanged(config);
600 }
601
602 @Override
603 public void handleNewIntent(Intent intent) {
604 mIntentHandler.onNewIntent(intent);
605 }
606
607 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800608 if (mUi.isCustomViewShowing()) {
609 hideCustomView();
610 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700611 if (mActivityPaused) {
612 Log.e(LOGTAG, "BrowserActivity is already paused.");
613 return;
614 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700615 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800616 Tab tab = mTabControl.getCurrentTab();
617 if (tab != null) {
618 tab.pause();
619 if (!pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700620 if (mWakeLock == null) {
621 PowerManager pm = (PowerManager) mActivity
622 .getSystemService(Context.POWER_SERVICE);
623 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
624 }
Michael Kolb70976932010-11-30 11:34:01 -0800625 mWakeLock.acquire();
626 mHandler.sendMessageDelayed(mHandler
627 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
628 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700629 }
630 mUi.onPause();
631 mNetworkHandler.onPause();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200632 mNfcHandler.onPause();
Michael Kolb8233fac2010-10-26 16:08:53 -0700633
634 WebView.disablePlatformNotifications();
John Reck378a4102011-06-09 16:23:01 -0700635 mCrashRecoveryHandler.backupState();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200636
Michael Kolb8233fac2010-10-26 16:08:53 -0700637 }
638
John Reck1cf4b792011-07-26 10:22:22 -0700639 void onSaveInstanceState(Bundle outState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700640 // the default implementation requires each view to have an id. As the
641 // browser handles the state itself and it doesn't use id for the views,
642 // don't call the default implementation. Otherwise it will trigger the
643 // warning like this, "couldn't save which view has focus because the
644 // focused view XXX has no id".
645
646 // Save all the tabs
John Reck1cf4b792011-07-26 10:22:22 -0700647 mTabControl.saveState(outState);
John Reck24f18262011-06-17 14:47:20 -0700648 if (!outState.isEmpty()) {
649 // Save time so that we know how old incognito tabs (if any) are.
650 outState.putSerializable("lastActiveDate", Calendar.getInstance());
651 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700652 }
653
654 void onResume() {
655 if (!mActivityPaused) {
656 Log.e(LOGTAG, "BrowserActivity is already resumed.");
657 return;
658 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700659 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800660 Tab current = mTabControl.getCurrentTab();
661 if (current != null) {
662 current.resume();
663 resumeWebViewTimers(current);
664 }
John Reckf57c0292011-07-21 18:15:39 -0700665 releaseWakeLock();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200666
Michael Kolb8233fac2010-10-26 16:08:53 -0700667 mUi.onResume();
668 mNetworkHandler.onResume();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200669 mNfcHandler.onResume();
Michael Kolb8233fac2010-10-26 16:08:53 -0700670 WebView.enablePlatformNotifications();
671 }
672
John Reckf57c0292011-07-21 18:15:39 -0700673 private void releaseWakeLock() {
674 if (mWakeLock != null && mWakeLock.isHeld()) {
675 mHandler.removeMessages(RELEASE_WAKELOCK);
676 mWakeLock.release();
677 }
678 }
679
Michael Kolb70976932010-11-30 11:34:01 -0800680 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800681 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800682 * @param tab guaranteed non-null
683 */
684 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700685 boolean inLoad = tab.inPageLoad();
686 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
687 CookieSyncManager.getInstance().startSync();
688 WebView w = tab.getWebView();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100689 WebViewTimersControl.getInstance().onBrowserActivityResume(w);
Michael Kolb8233fac2010-10-26 16:08:53 -0700690 }
691 }
692
Michael Kolb70976932010-11-30 11:34:01 -0800693 /**
694 * Pause all WebView timers using the WebView of the given tab
695 * @param tab
696 * @return true if the timers are paused or tab is null
697 */
698 private boolean pauseWebViewTimers(Tab tab) {
699 if (tab == null) {
700 return true;
701 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700702 CookieSyncManager.getInstance().stopSync();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100703 WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView());
Michael Kolb8233fac2010-10-26 16:08:53 -0700704 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700705 }
Michael Kolb70976932010-11-30 11:34:01 -0800706 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700707 }
708
709 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800710 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700711 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
712 mUploadHandler = null;
713 }
714 if (mTabControl == null) return;
715 mUi.onDestroy();
716 // Remove the current tab and sub window
717 Tab t = mTabControl.getCurrentTab();
718 if (t != null) {
719 dismissSubWindow(t);
720 removeTab(t);
721 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500722 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700723 // Destroy all the tabs
724 mTabControl.destroy();
725 WebIconDatabase.getInstance().close();
726 // Stop watching the default geolocation permissions
727 mSystemAllowGeolocationOrigins.stop();
728 mSystemAllowGeolocationOrigins = null;
729 }
730
731 protected boolean isActivityPaused() {
732 return mActivityPaused;
733 }
734
735 protected void onLowMemory() {
736 mTabControl.freeMemory();
737 }
738
739 @Override
740 public boolean shouldShowErrorConsole() {
741 return mShouldShowErrorConsole;
742 }
743
744 protected void setShouldShowErrorConsole(boolean show) {
745 if (show == mShouldShowErrorConsole) {
746 // Nothing to do.
747 return;
748 }
749 mShouldShowErrorConsole = show;
750 Tab t = mTabControl.getCurrentTab();
751 if (t == null) {
752 // There is no current tab so we cannot toggle the error console
753 return;
754 }
755 mUi.setShouldShowErrorConsole(t, show);
756 }
757
758 @Override
759 public void stopLoading() {
760 mLoadStopped = true;
761 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700762 WebView w = getCurrentTopWebView();
763 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700764 mUi.onPageStopped(tab);
765 }
766
767 boolean didUserStopLoading() {
768 return mLoadStopped;
769 }
770
771 // WebViewController
772
773 @Override
John Reck324d4402011-01-11 16:56:42 -0800774 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700775
776 // We've started to load a new page. If there was a pending message
777 // to save a screenshot then we will now take the new page and save
778 // an incorrect screenshot. Therefore, remove any pending thumbnail
779 // messages from the queue.
780 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800781 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700782
783 // reset sync timer to avoid sync starts during loading a page
784 CookieSyncManager.getInstance().resetSync();
785
786 if (!mNetworkHandler.isNetworkUp()) {
787 view.setNetworkAvailable(false);
788 }
789
790 // when BrowserActivity just starts, onPageStarted may be called before
791 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
792 // to start the timer. As we won't switch tabs while an activity is in
793 // pause state, we can ensure calling resume and pause in pair.
794 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800795 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700796 }
797 mLoadStopped = false;
798 if (!mNetworkHandler.isNetworkUp()) {
799 mNetworkHandler.createAndShowNetworkDialog();
800 }
801 endActionMode();
802
John Reck30c714c2010-12-16 17:30:34 -0800803 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700804
John Reck324d4402011-01-11 16:56:42 -0800805 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700806 // update the bookmark database for favicon
807 maybeUpdateFavicon(tab, null, url, favicon);
808
809 Performance.tracePageStart(url);
810
811 // Performance probe
812 if (false) {
813 Performance.onPageStarted();
814 }
815
816 }
817
818 @Override
John Reck324d4402011-01-11 16:56:42 -0800819 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800820 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800821 if (!tab.isPrivateBrowsingEnabled()
John Reckd8c74522011-06-14 08:45:00 -0700822 && !TextUtils.isEmpty(tab.getUrl())
823 && !tab.isSnapshot()) {
John Recka1696282011-07-08 14:10:37 -0700824 // Only update the bookmark screenshot if the user did not
825 // cancel the load early and there is not already
826 // a pending update for the tab.
Michael Kolb8233fac2010-10-26 16:08:53 -0700827 if (tab.inForeground() && !didUserStopLoading()
828 || !tab.inForeground()) {
John Recka1696282011-07-08 14:10:37 -0700829 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
830 mHandler.sendMessageDelayed(mHandler.obtainMessage(
831 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
832 500);
833 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700834 }
835 }
836 // pause the WebView timer and release the wake lock if it is finished
837 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800838 if (mActivityPaused && pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700839 releaseWakeLock();
Michael Kolb8233fac2010-10-26 16:08:53 -0700840 }
Martijn Coenenb2f93552011-06-14 10:48:35 +0200841
Michael Kolb8233fac2010-10-26 16:08:53 -0700842 // Performance probe
843 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800844 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700845 }
846
847 Performance.tracePageFinished();
848 }
849
850 @Override
John Reck30c714c2010-12-16 17:30:34 -0800851 public void onProgressChanged(Tab tab) {
852 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700853
854 if (newProgress == 100) {
855 CookieSyncManager.getInstance().sync();
856 // onProgressChanged() may continue to be called after the main
857 // frame has finished loading, as any remaining sub frames continue
858 // to load. We'll only get called once though with newProgress as
859 // 100 when everything is loaded. (onPageFinished is called once
860 // when the main frame completes loading regardless of the state of
861 // any sub frames so calls to onProgressChanges may continue after
862 // onPageFinished has executed)
863 if (mInLoad) {
864 mInLoad = false;
865 updateInLoadMenuItems(mCachedMenu);
866 }
867 } else {
868 if (!mInLoad) {
869 // onPageFinished may have already been called but a subframe is
870 // still loading and updating the progress. Reset mInLoad and
871 // update the menu items.
872 mInLoad = true;
873 updateInLoadMenuItems(mCachedMenu);
874 }
875 }
John Reck30c714c2010-12-16 17:30:34 -0800876 mUi.onProgressChanged(tab);
877 }
878
879 @Override
880 public void onUpdatedLockIcon(Tab tab) {
881 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700882 }
883
884 @Override
885 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800886 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800887 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800888 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700889 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
890 return;
891 }
892 // Update the title in the history database if not in private browsing mode
893 if (!tab.isPrivateBrowsingEnabled()) {
John Reckf57c0292011-07-21 18:15:39 -0700894 DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700895 }
896 }
897
898 @Override
899 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800900 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700901 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
902 }
903
904 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800905 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
906 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700907 }
908
909 @Override
910 public boolean shouldOverrideKeyEvent(KeyEvent event) {
911 if (mMenuIsDown) {
912 // only check shortcut key when MENU is held
913 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
914 event);
915 } else {
916 return false;
917 }
918 }
919
920 @Override
921 public void onUnhandledKeyEvent(KeyEvent event) {
922 if (!isActivityPaused()) {
923 if (event.getAction() == KeyEvent.ACTION_DOWN) {
924 mActivity.onKeyDown(event.getKeyCode(), event);
925 } else {
926 mActivity.onKeyUp(event.getKeyCode(), event);
927 }
928 }
929 }
930
931 @Override
John Reck324d4402011-01-11 16:56:42 -0800932 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700933 // Don't save anything in private browsing mode
934 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800935 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700936
John Reck324d4402011-01-11 16:56:42 -0800937 if (TextUtils.isEmpty(url)
938 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700939 return;
940 }
John Reckf57c0292011-07-21 18:15:39 -0700941 DataController.getInstance(mActivity).updateVisitedHistory(url);
John Reck847b5322011-04-14 17:02:18 -0700942 if (!mActivityPaused) {
943 // Since we clear the state in onPause, don't backup the current
944 // state if we are already paused
945 mCrashRecoveryHandler.backupState();
946 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700947 }
948
949 @Override
950 public void getVisitedHistory(final ValueCallback<String[]> callback) {
951 AsyncTask<Void, Void, String[]> task =
952 new AsyncTask<Void, Void, String[]>() {
953 @Override
954 public String[] doInBackground(Void... unused) {
955 return Browser.getVisitedHistory(mActivity.getContentResolver());
956 }
957 @Override
958 public void onPostExecute(String[] result) {
959 callback.onReceiveValue(result);
960 }
961 };
962 task.execute();
963 }
964
965 @Override
966 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
967 final HttpAuthHandler handler, final String host,
968 final String realm) {
969 String username = null;
970 String password = null;
971
972 boolean reuseHttpAuthUsernamePassword
973 = handler.useHttpAuthUsernamePassword();
974
975 if (reuseHttpAuthUsernamePassword && view != null) {
976 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
977 if (credentials != null && credentials.length == 2) {
978 username = credentials[0];
979 password = credentials[1];
980 }
981 }
982
983 if (username != null && password != null) {
984 handler.proceed(username, password);
985 } else {
Ben Murdochfdd37112011-08-05 15:48:14 +0100986 if (tab.inForeground() && !handler.suppressDialog()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700987 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
988 } else {
989 handler.cancel();
990 }
991 }
992 }
993
994 @Override
995 public void onDownloadStart(Tab tab, String url, String userAgent,
996 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000997 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -0500998 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000999 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
1000 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001001 // This Tab was opened for the sole purpose of downloading a
1002 // file. Remove it.
1003 if (tab == mTabControl.getCurrentTab()) {
1004 // In this case, the Tab is still on top.
1005 goBackOnePageOrQuit();
1006 } else {
1007 // In this case, it is not.
1008 closeTab(tab);
1009 }
1010 }
1011 }
1012
1013 @Override
1014 public Bitmap getDefaultVideoPoster() {
1015 return mUi.getDefaultVideoPoster();
1016 }
1017
1018 @Override
1019 public View getVideoLoadingProgressView() {
1020 return mUi.getVideoLoadingProgressView();
1021 }
1022
1023 @Override
1024 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1025 SslError error) {
1026 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1027 }
1028
Patrick Scott92066772011-03-10 08:46:27 -05001029 @Override
1030 public void showAutoLogin(Tab tab) {
1031 assert tab.inForeground();
1032 // Update the title bar to show the auto-login request.
1033 mUi.showAutoLogin(tab);
1034 }
1035
1036 @Override
1037 public void hideAutoLogin(Tab tab) {
1038 assert tab.inForeground();
1039 mUi.hideAutoLogin(tab);
1040 }
1041
Michael Kolb8233fac2010-10-26 16:08:53 -07001042 // helper method
1043
1044 /*
1045 * Update the favorites icon if the private browsing isn't enabled and the
1046 * icon is valid.
1047 */
1048 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1049 final String url, Bitmap favicon) {
1050 if (favicon == null) {
1051 return;
1052 }
1053 if (!tab.isPrivateBrowsingEnabled()) {
1054 Bookmarks.updateFavicon(mActivity
1055 .getContentResolver(), originalUrl, url, favicon);
1056 }
1057 }
1058
Leon Scroggins4cd97792010-12-03 15:31:56 -05001059 @Override
1060 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001061 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001062 mUi.bookmarkedStatusHasChanged(tab);
1063 }
1064
Michael Kolb8233fac2010-10-26 16:08:53 -07001065 // end WebViewController
1066
1067 protected void pageUp() {
1068 getCurrentTopWebView().pageUp(false);
1069 }
1070
1071 protected void pageDown() {
1072 getCurrentTopWebView().pageDown(false);
1073 }
1074
1075 // callback from phone title bar
1076 public void editUrl() {
1077 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001078 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001079 }
1080
Michael Kolbcfa3af52010-12-14 10:36:11 -08001081 public void startVoiceSearch() {
1082 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1083 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1084 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1085 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1086 mActivity.getComponentName().flattenToString());
1087 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001088 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001089 mActivity.startActivity(intent);
1090 }
1091
Michael Kolb11d19782011-03-20 10:17:40 -07001092 @Override
1093 public void activateVoiceSearchMode(String title, List<String> results) {
1094 mUi.showVoiceTitleBar(title, results);
Michael Kolb8233fac2010-10-26 16:08:53 -07001095 }
1096
1097 public void revertVoiceSearchMode(Tab tab) {
1098 mUi.revertVoiceTitleBar(tab);
1099 }
1100
Michael Kolb736990c2011-03-20 10:01:20 -07001101 public boolean supportsVoiceSearch() {
John Reck35e9dd62011-04-25 09:01:54 -07001102 SearchEngine searchEngine = getSettings().getSearchEngine();
Michael Kolb736990c2011-03-20 10:01:20 -07001103 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1104 }
1105
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001106 public void showCustomView(Tab tab, View view, int requestedOrientation,
Michael Kolb8233fac2010-10-26 16:08:53 -07001107 WebChromeClient.CustomViewCallback callback) {
1108 if (tab.inForeground()) {
1109 if (mUi.isCustomViewShowing()) {
1110 callback.onCustomViewHidden();
1111 return;
1112 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001113 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001114 // Save the menu state and set it to empty while the custom
1115 // view is showing.
1116 mOldMenuState = mMenuState;
1117 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001118 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001119 }
1120 }
1121
1122 @Override
1123 public void hideCustomView() {
1124 if (mUi.isCustomViewShowing()) {
1125 mUi.onHideCustomView();
1126 // Reset the old menu state.
1127 mMenuState = mOldMenuState;
1128 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001129 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001130 }
1131 }
1132
1133 protected void onActivityResult(int requestCode, int resultCode,
1134 Intent intent) {
1135 if (getCurrentTopWebView() == null) return;
1136 switch (requestCode) {
1137 case PREFERENCES_PAGE:
1138 if (resultCode == Activity.RESULT_OK && intent != null) {
1139 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001140 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001141 mTabControl.removeParentChildRelationShips();
1142 }
1143 }
1144 break;
1145 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001146 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001147 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001148 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001149 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001150 case AUTOFILL_SETUP:
1151 // Determine whether a profile was actually set up or not
1152 // and if so, send the message back to the WebTextView to
1153 // fill the form with the new profile.
1154 if (getSettings().getAutoFillProfile() != null) {
1155 mAutoFillSetupMessage.sendToTarget();
1156 mAutoFillSetupMessage = null;
1157 }
1158 break;
John Reckd3e4d5b2011-07-13 15:48:43 -07001159 case COMBO_VIEW:
1160 if (intent == null || resultCode != Activity.RESULT_OK) {
1161 break;
1162 }
John Reck3ba45532011-08-11 16:26:53 -07001163 mUi.showWeb(false);
John Reckd3e4d5b2011-07-13 15:48:43 -07001164 if (Intent.ACTION_VIEW.equals(intent.getAction())) {
1165 Tab t = getCurrentTab();
1166 Uri uri = intent.getData();
1167 loadUrl(t, uri.toString());
1168 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
1169 String[] urls = intent.getStringArrayExtra(
1170 ComboViewActivity.EXTRA_OPEN_ALL);
1171 Tab parent = getCurrentTab();
1172 for (String url : urls) {
1173 parent = openTab(url, parent,
1174 !mSettings.openInBackground(), true);
1175 }
1176 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
1177 long id = intent.getLongExtra(
1178 ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
1179 if (id >= 0) {
1180 createNewSnapshotTab(id, true);
1181 }
1182 }
1183 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001184 default:
1185 break;
1186 }
1187 getCurrentTopWebView().requestFocus();
1188 }
1189
1190 /**
1191 * Open the Go page.
1192 * @param startWithHistory If true, open starting on the history tab.
1193 * Otherwise, start with the bookmarks tab.
1194 */
1195 @Override
1196 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1197 if (mTabControl.getCurrentWebView() == null) {
1198 return;
1199 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001200 // clear action mode
1201 if (isInCustomActionMode()) {
1202 endActionMode();
1203 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001204 Bundle extras = new Bundle();
1205 // Disable opening in a new window if we have maxed out the windows
1206 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1207 !mTabControl.canCreateNewTab());
John Reck2bc80422011-06-30 15:11:49 -07001208 mUi.showComboView(startWithHistory
1209 ? ComboViews.History : ComboViews.Bookmarks, extras);
Michael Kolb8233fac2010-10-26 16:08:53 -07001210 }
1211
1212 // combo view callbacks
1213
1214 /**
1215 * callback from ComboPage when clear history is requested
1216 */
1217 public void onRemoveParentChildRelationships() {
1218 mTabControl.removeParentChildRelationShips();
1219 }
1220
Michael Kolb8233fac2010-10-26 16:08:53 -07001221 // key handling
1222 protected void onBackKey() {
1223 if (!mUi.onBackKey()) {
1224 WebView subwindow = mTabControl.getCurrentSubWindow();
1225 if (subwindow != null) {
1226 if (subwindow.canGoBack()) {
1227 subwindow.goBack();
1228 } else {
1229 dismissSubWindow(mTabControl.getCurrentTab());
1230 }
1231 } else {
1232 goBackOnePageOrQuit();
1233 }
1234 }
1235 }
1236
Michael Kolb4bd767d2011-05-27 11:33:55 -07001237 protected boolean onMenuKey() {
1238 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001239 }
1240
Michael Kolb8233fac2010-10-26 16:08:53 -07001241 // menu handling and state
1242 // TODO: maybe put into separate handler
1243
1244 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckd73c5a22010-12-22 10:22:50 -08001245 if (mMenuState == EMPTY_MENU) {
1246 return false;
1247 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001248 MenuInflater inflater = mActivity.getMenuInflater();
1249 inflater.inflate(R.menu.browser, menu);
1250 updateInLoadMenuItems(menu);
1251 // hold on to the menu reference here; it is used by the page callbacks
1252 // to update the menu based on loading state
1253 mCachedMenu = menu;
1254 return true;
1255 }
1256
1257 protected void onCreateContextMenu(ContextMenu menu, View v,
1258 ContextMenuInfo menuInfo) {
John Reck0f602f32011-07-07 15:38:43 -07001259 if (v instanceof TitleBar) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001260 return;
1261 }
1262 if (!(v instanceof WebView)) {
1263 return;
1264 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001265 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001266 WebView.HitTestResult result = webview.getHitTestResult();
1267 if (result == null) {
1268 return;
1269 }
1270
1271 int type = result.getType();
1272 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1273 Log.w(LOGTAG,
1274 "We should not show context menu when nothing is touched");
1275 return;
1276 }
1277 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1278 // let TextView handles context menu
1279 return;
1280 }
1281
1282 // Note, http://b/issue?id=1106666 is requesting that
1283 // an inflated menu can be used again. This is not available
1284 // yet, so inflate each time (yuk!)
1285 MenuInflater inflater = mActivity.getMenuInflater();
1286 inflater.inflate(R.menu.browsercontext, menu);
1287
1288 // Show the correct menu group
1289 final String extra = result.getExtra();
1290 menu.setGroupVisible(R.id.PHONE_MENU,
1291 type == WebView.HitTestResult.PHONE_TYPE);
1292 menu.setGroupVisible(R.id.EMAIL_MENU,
1293 type == WebView.HitTestResult.EMAIL_TYPE);
1294 menu.setGroupVisible(R.id.GEO_MENU,
1295 type == WebView.HitTestResult.GEO_TYPE);
1296 menu.setGroupVisible(R.id.IMAGE_MENU,
1297 type == WebView.HitTestResult.IMAGE_TYPE
1298 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1299 menu.setGroupVisible(R.id.ANCHOR_MENU,
1300 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1301 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001302 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1303 || type == WebView.HitTestResult.PHONE_TYPE
1304 || type == WebView.HitTestResult.EMAIL_TYPE
1305 || type == WebView.HitTestResult.GEO_TYPE;
1306 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1307 if (hitText) {
1308 menu.findItem(R.id.select_text_menu_id)
1309 .setOnMenuItemClickListener(new SelectText(webview));
1310 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001311 // Setup custom handling depending on the type
1312 switch (type) {
1313 case WebView.HitTestResult.PHONE_TYPE:
1314 menu.setHeaderTitle(Uri.decode(extra));
1315 menu.findItem(R.id.dial_context_menu_id).setIntent(
1316 new Intent(Intent.ACTION_VIEW, Uri
1317 .parse(WebView.SCHEME_TEL + extra)));
1318 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1319 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1320 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1321 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1322 addIntent);
1323 menu.findItem(R.id.copy_phone_context_menu_id)
1324 .setOnMenuItemClickListener(
1325 new Copy(extra));
1326 break;
1327
1328 case WebView.HitTestResult.EMAIL_TYPE:
1329 menu.setHeaderTitle(extra);
1330 menu.findItem(R.id.email_context_menu_id).setIntent(
1331 new Intent(Intent.ACTION_VIEW, Uri
1332 .parse(WebView.SCHEME_MAILTO + extra)));
1333 menu.findItem(R.id.copy_mail_context_menu_id)
1334 .setOnMenuItemClickListener(
1335 new Copy(extra));
1336 break;
1337
1338 case WebView.HitTestResult.GEO_TYPE:
1339 menu.setHeaderTitle(extra);
1340 menu.findItem(R.id.map_context_menu_id).setIntent(
1341 new Intent(Intent.ACTION_VIEW, Uri
1342 .parse(WebView.SCHEME_GEO
1343 + URLEncoder.encode(extra))));
1344 menu.findItem(R.id.copy_geo_context_menu_id)
1345 .setOnMenuItemClickListener(
1346 new Copy(extra));
1347 break;
1348
1349 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1350 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001351 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001352 // decide whether to show the open link in new tab option
1353 boolean showNewTab = mTabControl.canCreateNewTab();
1354 MenuItem newTabItem
1355 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001356 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001357 ? R.string.contextmenu_openlink_newwindow_background
1358 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001359 newTabItem.setVisible(showNewTab);
1360 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001361 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1362 newTabItem.setOnMenuItemClickListener(
1363 new MenuItem.OnMenuItemClickListener() {
1364 @Override
1365 public boolean onMenuItemClick(MenuItem item) {
1366 final HashMap<String, WebView> hrefMap =
1367 new HashMap<String, WebView>();
1368 hrefMap.put("webview", webview);
1369 final Message msg = mHandler.obtainMessage(
1370 FOCUS_NODE_HREF,
1371 R.id.open_newtab_context_menu_id,
1372 0, hrefMap);
1373 webview.requestFocusNodeHref(msg);
1374 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001375 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001376 });
1377 } else {
1378 newTabItem.setOnMenuItemClickListener(
1379 new MenuItem.OnMenuItemClickListener() {
1380 @Override
1381 public boolean onMenuItemClick(MenuItem item) {
1382 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001383 openTab(extra, parent,
1384 !mSettings.openInBackground(),
1385 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001386 return true;
1387 }
1388 });
1389 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001390 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001391 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1392 break;
1393 }
1394 // otherwise fall through to handle image part
1395 case WebView.HitTestResult.IMAGE_TYPE:
1396 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1397 menu.setHeaderTitle(extra);
1398 }
1399 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1400 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1401 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001402 setOnMenuItemClickListener(
1403 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001404 menu.findItem(R.id.set_wallpaper_context_menu_id).
1405 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1406 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001407 break;
1408
1409 default:
1410 Log.w(LOGTAG, "We should not get here.");
1411 break;
1412 }
1413 //update the ui
1414 mUi.onContextMenuCreated(menu);
1415 }
1416
1417 /**
1418 * As the menu can be open when loading state changes
1419 * we must manually update the state of the stop/reload menu
1420 * item
1421 */
1422 private void updateInLoadMenuItems(Menu menu) {
1423 if (menu == null) {
1424 return;
1425 }
1426 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1427 MenuItem src = mInLoad ?
1428 menu.findItem(R.id.stop_menu_id):
1429 menu.findItem(R.id.reload_menu_id);
1430 if (src != null) {
1431 dest.setIcon(src.getIcon());
1432 dest.setTitle(src.getTitle());
1433 }
1434 }
1435
John Reckb3417f02011-01-14 11:01:05 -08001436 boolean onPrepareOptionsMenu(Menu menu) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001437 // Note: setVisible will decide whether an item is visible; while
1438 // setEnabled() will decide whether an item is enabled, which also means
1439 // whether the matching shortcut key will function.
1440 switch (mMenuState) {
1441 case EMPTY_MENU:
1442 if (mCurrentMenuState != mMenuState) {
1443 menu.setGroupVisible(R.id.MAIN_MENU, false);
1444 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1445 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1446 }
1447 break;
1448 default:
1449 if (mCurrentMenuState != mMenuState) {
1450 menu.setGroupVisible(R.id.MAIN_MENU, true);
1451 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1452 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1453 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001454 updateMenuState(getCurrentTab(), menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001455 break;
1456 }
1457 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001458 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001459 }
1460
Michael Kolb4bf79712011-07-14 14:18:12 -07001461 @Override
1462 public void updateMenuState(Tab tab, Menu menu) {
1463 boolean canGoBack = false;
1464 boolean canGoForward = false;
1465 boolean isHome = false;
1466 if (tab != null) {
1467 canGoBack = tab.canGoBack();
1468 canGoForward = tab.canGoForward();
1469 isHome = mSettings.getHomePage().equals(tab.getUrl());
1470 }
1471 final MenuItem back = menu.findItem(R.id.back_menu_id);
1472 back.setEnabled(canGoBack);
1473
1474 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1475 home.setEnabled(!isHome);
1476
1477 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1478 forward.setEnabled(canGoForward);
1479
1480 final MenuItem source = menu.findItem(mInLoad ? R.id.stop_menu_id : R.id.reload_menu_id);
1481 final MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolb7ab75ee2011-07-14 16:36:38 -07001482 if (source != null && dest != null) {
1483 dest.setTitle(source.getTitle());
1484 dest.setIcon(source.getIcon());
1485 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001486
1487 // decide whether to show the share link option
1488 PackageManager pm = mActivity.getPackageManager();
1489 Intent send = new Intent(Intent.ACTION_SEND);
1490 send.setType("text/plain");
1491 ResolveInfo ri = pm.resolveActivity(send,
1492 PackageManager.MATCH_DEFAULT_ONLY);
1493 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1494
1495 boolean isNavDump = mSettings.enableNavDump();
1496 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1497 nav.setVisible(isNavDump);
1498 nav.setEnabled(isNavDump);
1499
1500 boolean showDebugSettings = mSettings.isDebugEnabled();
1501 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1502 counter.setVisible(showDebugSettings);
1503 counter.setEnabled(showDebugSettings);
1504
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001505 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001506 }
1507
Michael Kolb8233fac2010-10-26 16:08:53 -07001508 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001509 if (null == getCurrentTopWebView()) {
1510 return false;
1511 }
1512 if (mMenuIsDown) {
1513 // The shortcut action consumes the MENU. Even if it is still down,
1514 // it won't trigger the next shortcut action. In the case of the
1515 // shortcut action triggering a new activity, like Bookmarks, we
1516 // won't get onKeyUp for MENU. So it is important to reset it here.
1517 mMenuIsDown = false;
1518 }
Michael Kolb3ca12752011-07-20 13:52:25 -07001519 if (mUi.onOptionsItemSelected(item)) {
1520 // ui callback handled it
1521 return true;
1522 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001523 switch (item.getItemId()) {
1524 // -- Main menu
1525 case R.id.new_tab_menu_id:
1526 openTabToHomePage();
1527 break;
1528
1529 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001530 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001531 break;
1532
1533 case R.id.goto_menu_id:
1534 editUrl();
1535 break;
1536
1537 case R.id.bookmarks_menu_id:
1538 bookmarksOrHistoryPicker(false);
1539 break;
1540
Michael Kolb8233fac2010-10-26 16:08:53 -07001541 case R.id.add_bookmark_menu_id:
John Reckd3e4d5b2011-07-13 15:48:43 -07001542 mActivity.startActivity(createBookmarkCurrentPageIntent(false));
Michael Kolb8233fac2010-10-26 16:08:53 -07001543 break;
1544
1545 case R.id.stop_reload_menu_id:
1546 if (mInLoad) {
1547 stopLoading();
1548 } else {
1549 getCurrentTopWebView().reload();
1550 }
1551 break;
1552
1553 case R.id.back_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001554 getCurrentTab().goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07001555 break;
1556
1557 case R.id.forward_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001558 getCurrentTab().goForward();
Michael Kolb8233fac2010-10-26 16:08:53 -07001559 break;
1560
1561 case R.id.close_menu_id:
1562 // Close the subwindow if it exists.
1563 if (mTabControl.getCurrentSubWindow() != null) {
1564 dismissSubWindow(mTabControl.getCurrentTab());
1565 break;
1566 }
1567 closeCurrentTab();
1568 break;
1569
1570 case R.id.homepage_menu_id:
1571 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07001572 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07001573 break;
1574
1575 case R.id.preferences_menu_id:
1576 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1577 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1578 getCurrentTopWebView().getUrl());
1579 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1580 break;
1581
1582 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001583 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001584 break;
1585
John Reck2bc80422011-06-30 15:11:49 -07001586 case R.id.save_snapshot_menu_id:
1587 final Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07001588 if (source == null) break;
John Reckd8c74522011-06-14 08:45:00 -07001589 final ContentResolver cr = mActivity.getContentResolver();
1590 final ContentValues values = source.createSnapshotValues();
John Reck2bc80422011-06-30 15:11:49 -07001591 if (values != null) {
1592 new AsyncTask<Tab, Void, Long>() {
John Reckd8c74522011-06-14 08:45:00 -07001593
John Reck2bc80422011-06-30 15:11:49 -07001594 @Override
1595 protected Long doInBackground(Tab... params) {
1596 Uri result = cr.insert(Snapshots.CONTENT_URI, values);
1597 long id = ContentUris.parseId(result);
1598 return id;
John Reckd8c74522011-06-14 08:45:00 -07001599 }
John Reckf33b1632011-06-04 20:00:23 -07001600
John Reck2bc80422011-06-30 15:11:49 -07001601 @Override
1602 protected void onPostExecute(Long id) {
1603 Bundle b = new Bundle();
1604 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
1605 mUi.showComboView(ComboViews.Snapshots, b);
1606 };
1607 }.execute(source);
1608 } else {
1609 Toast.makeText(mActivity, R.string.snapshot_failed,
Leon Scrogginsac993842011-02-02 12:54:07 -05001610 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001611 }
Leon Scrogginsac993842011-02-02 12:54:07 -05001612 break;
1613
Michael Kolb8233fac2010-10-26 16:08:53 -07001614 case R.id.page_info_menu_id:
Huahui Wuae0c0412011-06-28 10:17:05 -07001615 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001616 break;
1617
1618 case R.id.classic_history_menu_id:
1619 bookmarksOrHistoryPicker(true);
1620 break;
1621
Michael Kolb8233fac2010-10-26 16:08:53 -07001622 case R.id.share_page_menu_id:
1623 Tab currentTab = mTabControl.getCurrentTab();
1624 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001625 return false;
1626 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001627 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001628 break;
1629
1630 case R.id.dump_nav_menu_id:
1631 getCurrentTopWebView().debugDump();
1632 break;
1633
1634 case R.id.dump_counters_menu_id:
1635 getCurrentTopWebView().dumpV8Counters();
1636 break;
1637
1638 case R.id.zoom_in_menu_id:
1639 getCurrentTopWebView().zoomIn();
1640 break;
1641
1642 case R.id.zoom_out_menu_id:
1643 getCurrentTopWebView().zoomOut();
1644 break;
1645
1646 case R.id.view_downloads_menu_id:
1647 viewDownloads();
1648 break;
1649
1650 case R.id.window_one_menu_id:
1651 case R.id.window_two_menu_id:
1652 case R.id.window_three_menu_id:
1653 case R.id.window_four_menu_id:
1654 case R.id.window_five_menu_id:
1655 case R.id.window_six_menu_id:
1656 case R.id.window_seven_menu_id:
1657 case R.id.window_eight_menu_id:
1658 {
1659 int menuid = item.getItemId();
1660 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1661 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1662 Tab desiredTab = mTabControl.getTab(id);
1663 if (desiredTab != null &&
1664 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001665 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001666 }
1667 break;
1668 }
1669 }
1670 }
1671 break;
1672
1673 default:
1674 return false;
1675 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001676 return true;
1677 }
1678
1679 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001680 // Let the History and Bookmark fragments handle menus they created.
1681 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1682 return false;
1683 }
1684
Michael Kolb8233fac2010-10-26 16:08:53 -07001685 int id = item.getItemId();
1686 boolean result = true;
1687 switch (id) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001688 // -- Browser context menu
1689 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001690 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001691 case R.id.copy_link_context_menu_id:
1692 final WebView webView = getCurrentTopWebView();
1693 if (null == webView) {
1694 result = false;
1695 break;
1696 }
1697 final HashMap<String, WebView> hrefMap =
1698 new HashMap<String, WebView>();
1699 hrefMap.put("webview", webView);
1700 final Message msg = mHandler.obtainMessage(
1701 FOCUS_NODE_HREF, id, 0, hrefMap);
1702 webView.requestFocusNodeHref(msg);
1703 break;
1704
1705 default:
1706 // For other context menus
1707 result = onOptionsItemSelected(item);
1708 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001709 return result;
1710 }
1711
1712 /**
1713 * support programmatically opening the context menu
1714 */
1715 public void openContextMenu(View view) {
1716 mActivity.openContextMenu(view);
1717 }
1718
1719 /**
1720 * programmatically open the options menu
1721 */
1722 public void openOptionsMenu() {
1723 mActivity.openOptionsMenu();
1724 }
1725
1726 public boolean onMenuOpened(int featureId, Menu menu) {
1727 if (mOptionsMenuOpen) {
1728 if (mConfigChanged) {
1729 // We do not need to make any changes to the state of the
1730 // title bar, since the only thing that happened was a
1731 // change in orientation
1732 mConfigChanged = false;
1733 } else {
1734 if (!mExtendedMenuOpen) {
1735 mExtendedMenuOpen = true;
1736 mUi.onExtendedMenuOpened();
1737 } else {
1738 // Switching the menu back to icon view, so show the
1739 // title bar once again.
1740 mExtendedMenuOpen = false;
1741 mUi.onExtendedMenuClosed(mInLoad);
Michael Kolb8233fac2010-10-26 16:08:53 -07001742 }
1743 }
1744 } else {
1745 // The options menu is closed, so open it, and show the title
1746 mOptionsMenuOpen = true;
1747 mConfigChanged = false;
1748 mExtendedMenuOpen = false;
1749 mUi.onOptionsMenuOpened();
1750 }
1751 return true;
1752 }
1753
1754 public void onOptionsMenuClosed(Menu menu) {
1755 mOptionsMenuOpen = false;
1756 mUi.onOptionsMenuClosed(mInLoad);
1757 }
1758
1759 public void onContextMenuClosed(Menu menu) {
1760 mUi.onContextMenuClosed(menu, mInLoad);
1761 }
1762
1763 // Helper method for getting the top window.
1764 @Override
1765 public WebView getCurrentTopWebView() {
1766 return mTabControl.getCurrentTopWebView();
1767 }
1768
1769 @Override
1770 public WebView getCurrentWebView() {
1771 return mTabControl.getCurrentWebView();
1772 }
1773
1774 /*
1775 * This method is called as a result of the user selecting the options
1776 * menu to see the download window. It shows the download window on top of
1777 * the current window.
1778 */
1779 void viewDownloads() {
1780 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1781 mActivity.startActivity(intent);
1782 }
1783
John Reck30b065e2011-07-19 10:58:05 -07001784 int getActionModeHeight() {
1785 TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
1786 new int[] { android.R.attr.actionBarSize });
1787 int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
1788 actionBarSizeTypedArray.recycle();
1789 return size;
1790 }
1791
Michael Kolb8233fac2010-10-26 16:08:53 -07001792 // action mode
1793
1794 void onActionModeStarted(ActionMode mode) {
1795 mUi.onActionModeStarted(mode);
1796 mActionMode = mode;
Michael Kolb42c0c062011-08-02 12:56:06 -07001797 if (mSimulateActionBarOverlayMode && !mUi.isEditingUrl()) {
John Reck30b065e2011-07-19 10:58:05 -07001798 WebView web = getCurrentWebView();
1799 // Simulate overlay mode by scrolling the webview the amount it will be
1800 // pushed down. Actual overlay mode doesn't work for us as otherwise
1801 // the CAB will, well, overlay the content, which breaks things like
1802 // find on page.
1803 int scrollBy = getActionModeHeight();
1804 web.scrollBy(0, scrollBy);
1805 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001806 }
1807
1808 /*
1809 * True if a custom ActionMode (i.e. find or select) is in use.
1810 */
1811 @Override
1812 public boolean isInCustomActionMode() {
1813 return mActionMode != null;
1814 }
1815
1816 /*
1817 * End the current ActionMode.
1818 */
1819 @Override
1820 public void endActionMode() {
1821 if (mActionMode != null) {
1822 mActionMode.finish();
1823 }
1824 }
1825
1826 /*
1827 * Called by find and select when they are finished. Replace title bars
1828 * as necessary.
1829 */
1830 public void onActionModeFinished(ActionMode mode) {
1831 if (!isInCustomActionMode()) return;
1832 mUi.onActionModeFinished(mInLoad);
1833 mActionMode = null;
John Reck30b065e2011-07-19 10:58:05 -07001834 if (mSimulateActionBarOverlayMode) {
1835 WebView web = getCurrentWebView();
1836 int scrollBy = getActionModeHeight();
1837 web.scrollBy(0, -scrollBy);
1838 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001839 }
1840
1841 boolean isInLoad() {
1842 return mInLoad;
1843 }
1844
1845 // bookmark handling
1846
1847 /**
1848 * add the current page as a bookmark to the given folder id
1849 * @param folderId use -1 for the default folder
John Reckd3e4d5b2011-07-13 15:48:43 -07001850 * @param editExisting If true, check to see whether the site is already
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001851 * bookmarked, and if it is, edit that bookmark. If false, and
1852 * the site is already bookmarked, do not attempt to edit the
1853 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001854 */
1855 @Override
John Reckd3e4d5b2011-07-13 15:48:43 -07001856 public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001857 Intent i = new Intent(mActivity,
1858 AddBookmarkPage.class);
1859 WebView w = getCurrentTopWebView();
1860 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1861 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1862 String touchIconUrl = w.getTouchIconUrl();
1863 if (touchIconUrl != null) {
1864 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1865 WebSettings settings = w.getSettings();
1866 if (settings != null) {
1867 i.putExtra(AddBookmarkPage.USER_AGENT,
1868 settings.getUserAgentString());
1869 }
1870 }
1871 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1872 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1873 getDesiredThumbnailHeight(mActivity)));
1874 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07001875 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001876 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1877 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001878 // Put the dialog at the upper right of the screen, covering the
1879 // star on the title bar.
1880 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07001881 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07001882 }
1883
1884 // file chooser
1885 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1886 mUploadHandler = new UploadHandler(this);
1887 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1888 }
1889
1890 // thumbnails
1891
1892 /**
1893 * Return the desired width for thumbnail screenshots, which are stored in
1894 * the database, and used on the bookmarks screen.
1895 * @param context Context for finding out the density of the screen.
1896 * @return desired width for thumbnail screenshot.
1897 */
1898 static int getDesiredThumbnailWidth(Context context) {
1899 return context.getResources().getDimensionPixelOffset(
1900 R.dimen.bookmarkThumbnailWidth);
1901 }
1902
1903 /**
1904 * Return the desired height for thumbnail screenshots, which are stored in
1905 * the database, and used on the bookmarks screen.
1906 * @param context Context for finding out the density of the screen.
1907 * @return desired height for thumbnail screenshot.
1908 */
1909 static int getDesiredThumbnailHeight(Context context) {
1910 return context.getResources().getDimensionPixelOffset(
1911 R.dimen.bookmarkThumbnailHeight);
1912 }
1913
John Reck8cc92352011-07-06 17:41:52 -07001914 static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001915 // We render to a bitmap 2x the desired size so that we can then
1916 // re-scale it with filtering since canvas.scale doesn't filter
1917 // This helps reduce aliasing at the cost of being slightly blurry
1918 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001919 Picture thumbnail = view.capturePicture();
1920 if (thumbnail == null) {
1921 return null;
1922 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001923 width *= filter_scale;
1924 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001925 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1926 Canvas canvas = new Canvas(bm);
1927 // May need to tweak these values to determine what is the
1928 // best scale factor
1929 int thumbnailWidth = thumbnail.getWidth();
1930 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001931 float scaleFactor = 1.0f;
Michael Kolbeb95db42011-03-03 10:38:40 -08001932 if (thumbnailWidth > 0 && thumbnailHeight > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001933 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001934 } else {
1935 return null;
1936 }
John Reckfe49ab42010-11-16 17:09:37 -08001937
Michael Kolbeb95db42011-03-03 10:38:40 -08001938 float scaleFactorY = (float) height / (float)thumbnailHeight;
1939 if (scaleFactorY > scaleFactor) {
1940 // The picture is narrower than the requested AR
1941 // Center the thumnail and crop the sides
1942 scaleFactor = scaleFactorY;
John Reckfe49ab42010-11-16 17:09:37 -08001943 float wx = (thumbnailWidth * scaleFactor) - width;
1944 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001945 }
1946
John Reckfe49ab42010-11-16 17:09:37 -08001947 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001948
1949 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001950 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
1951 height / filter_scale, true);
Dianne Hackborn43cfe8a2011-08-02 16:59:35 -07001952 canvas.setBitmap(null);
John Reck5c6ac2f2011-01-05 10:18:03 -08001953 bm.recycle();
1954 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001955 }
1956
John Reck34ef2672011-02-10 11:30:55 -08001957 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001958 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07001959 // FIXME: Would like to make sure there is actually something to
1960 // draw, but the API for that (WebViewCore.pictureReady()) is not
1961 // currently accessible here.
1962
John Reck34ef2672011-02-10 11:30:55 -08001963 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08001964 if (view == null) {
1965 // Tab was destroyed
1966 return;
1967 }
John Reck34ef2672011-02-10 11:30:55 -08001968 final String url = tab.getUrl();
1969 final String originalUrl = view.getOriginalUrl();
1970
1971 if (TextUtils.isEmpty(url)) {
1972 return;
1973 }
1974
1975 // Only update thumbnails for web urls (http(s)://), not for
1976 // about:, javascript:, data:, etc...
1977 // Unless it is a bookmarked site, then always update
1978 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
1979 return;
1980 }
1981
Michael Kolb8233fac2010-10-26 16:08:53 -07001982 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1983 getDesiredThumbnailHeight(mActivity));
1984 if (bm == null) {
1985 return;
1986 }
1987
1988 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08001989 new AsyncTask<Void, Void, Void>() {
1990 @Override
1991 protected Void doInBackground(Void... unused) {
1992 Cursor cursor = null;
1993 try {
1994 // TODO: Clean this up
1995 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
1996 if (cursor != null && cursor.moveToFirst()) {
1997 final ByteArrayOutputStream os =
1998 new ByteArrayOutputStream();
1999 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002000
John Reck34ef2672011-02-10 11:30:55 -08002001 ContentValues values = new ContentValues();
2002 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002003
John Reck34ef2672011-02-10 11:30:55 -08002004 do {
John Reck617fd832011-02-16 14:35:59 -08002005 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002006 cr.update(Images.CONTENT_URI, values, null, null);
2007 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002008 }
John Reck34ef2672011-02-10 11:30:55 -08002009 } catch (IllegalStateException e) {
2010 // Ignore
2011 } finally {
2012 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002013 }
John Reck34ef2672011-02-10 11:30:55 -08002014 return null;
2015 }
2016 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002017 }
2018
2019 private class Copy implements OnMenuItemClickListener {
2020 private CharSequence mText;
2021
2022 public boolean onMenuItemClick(MenuItem item) {
2023 copy(mText);
2024 return true;
2025 }
2026
2027 public Copy(CharSequence toCopy) {
2028 mText = toCopy;
2029 }
2030 }
2031
Leon Scroggins63c02662010-11-18 15:16:27 -05002032 private static class Download implements OnMenuItemClickListener {
2033 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002034 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002035 private boolean mPrivateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002036
2037 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002038 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002039 null, null, mPrivateBrowsing);
Michael Kolb8233fac2010-10-26 16:08:53 -07002040 return true;
2041 }
2042
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002043 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002044 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002045 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002046 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002047 }
2048 }
2049
Cary Clark8974d282010-11-22 10:46:05 -05002050 private static class SelectText implements OnMenuItemClickListener {
2051 private WebView mWebView;
2052
2053 public boolean onMenuItemClick(MenuItem item) {
2054 if (mWebView != null) {
2055 return mWebView.selectText();
2056 }
2057 return false;
2058 }
2059
2060 public SelectText(WebView webView) {
2061 mWebView = webView;
2062 }
2063
2064 }
2065
Michael Kolb8233fac2010-10-26 16:08:53 -07002066 /********************** TODO: UI stuff *****************************/
2067
2068 // these methods have been copied, they still need to be cleaned up
2069
2070 /****************** tabs ***************************************************/
2071
2072 // basic tab interactions:
2073
2074 // it is assumed that tabcontrol already knows about the tab
2075 protected void addTab(Tab tab) {
2076 mUi.addTab(tab);
2077 }
2078
2079 protected void removeTab(Tab tab) {
2080 mUi.removeTab(tab);
2081 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002082 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002083 }
2084
Michael Kolbf2055602011-04-09 17:20:03 -07002085 @Override
2086 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002087 // monkey protection against delayed start
2088 if (tab != null) {
2089 mTabControl.setCurrentTab(tab);
2090 // the tab is guaranteed to have a webview after setCurrentTab
2091 mUi.setActiveTab(tab);
2092 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002093 }
2094
2095 protected void closeEmptyChildTab() {
2096 Tab current = mTabControl.getCurrentTab();
2097 if (current != null
2098 && current.getWebView().copyBackForwardList().getSize() == 0) {
Michael Kolbc831b632011-05-11 09:30:34 -07002099 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002100 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002101 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002102 closeTab(current);
2103 }
2104 }
2105 }
2106
John Reck26b18322011-06-21 13:08:58 -07002107 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002108 // Dismiss the subwindow if applicable.
2109 dismissSubWindow(appTab);
2110 // Since we might kill the WebView, remove it from the
2111 // content view first.
2112 mUi.detachTab(appTab);
2113 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002114 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002115 // TODO: analyze why the remove and add are necessary
2116 mUi.attachTab(appTab);
2117 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002118 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002119 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002120 } else {
2121 // If the tab was the current tab, we have to attach
2122 // it to the view system again.
2123 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002124 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002125 }
2126 }
2127
2128 // Remove the sub window if it exists. Also called by TabControl when the
2129 // user clicks the 'X' to dismiss a sub window.
2130 public void dismissSubWindow(Tab tab) {
2131 removeSubWindow(tab);
2132 // dismiss the subwindow. This will destroy the WebView.
2133 tab.dismissSubWindow();
2134 getCurrentTopWebView().requestFocus();
2135 }
2136
2137 @Override
2138 public void removeSubWindow(Tab t) {
2139 if (t.getSubWebView() != null) {
2140 mUi.removeSubWindow(t.getSubViewContainer());
2141 }
2142 }
2143
2144 @Override
2145 public void attachSubWindow(Tab tab) {
2146 if (tab.getSubWebView() != null) {
2147 mUi.attachSubWindow(tab.getSubViewContainer());
2148 getCurrentTopWebView().requestFocus();
2149 }
2150 }
2151
Mathew Inwood29721c22011-06-29 17:55:24 +01002152 private Tab showPreloadedTab(final UrlData urlData) {
2153 if (!urlData.isPreloaded()) {
2154 return null;
2155 }
2156 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2157 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2158 if (sbQuery != null) {
2159 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
2160 // Could not submit query. Fallback to regular tab creation
2161 tabControl.destroy();
2162 return null;
2163 }
2164 }
Michael Kolbff6a7482011-07-26 16:37:15 -07002165 // check tab count and make room for new tab
2166 if (!mTabControl.canCreateNewTab()) {
2167 Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
2168 if (leastUsed != null) {
2169 closeTab(leastUsed);
2170 }
2171 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002172 Tab t = tabControl.getTab();
2173 mTabControl.addPreloadedTab(t);
2174 addTab(t);
2175 setActiveTab(t);
2176 return t;
2177 }
2178
Michael Kolb7bcafde2011-05-09 13:55:59 -07002179 // open a non inconito tab with the given url data
2180 // and set as active tab
2181 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002182 Tab tab = showPreloadedTab(urlData);
2183 if (tab == null) {
2184 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002185 if ((tab != null) && !urlData.isEmpty()) {
2186 loadUrlDataIn(tab, urlData);
2187 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002188 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002189 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002190 }
2191
Michael Kolb843510f2010-12-09 10:51:49 -08002192 @Override
2193 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002194 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002195 }
2196
Michael Kolb8233fac2010-10-26 16:08:53 -07002197 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002198 public Tab openIncognitoTab() {
2199 return openTab(INCOGNITO_URI, true, true, false);
2200 }
2201
2202 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002203 public Tab openTab(String url, boolean incognito, boolean setActive,
2204 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002205 return openTab(url, incognito, setActive, useCurrent, null);
2206 }
2207
2208 @Override
2209 public Tab openTab(String url, Tab parent, boolean setActive,
2210 boolean useCurrent) {
2211 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2212 setActive, useCurrent, parent);
2213 }
2214
2215 public Tab openTab(String url, boolean incognito, boolean setActive,
2216 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002217 Tab tab = createNewTab(incognito, setActive, useCurrent);
2218 if (tab != null) {
John Reck5949c662011-05-27 09:52:29 -07002219 if (parent != null && parent != tab) {
2220 parent.addChildTab(tab);
2221 }
Michael Kolb519d2282011-05-09 17:03:19 -07002222 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002223 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002224 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002225 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002226 return tab;
2227 }
2228
2229 // this method will attempt to create a new tab
2230 // incognito: private browsing tab
2231 // setActive: ste tab as current tab
2232 // useCurrent: if no new tab can be created, return current tab
2233 private Tab createNewTab(boolean incognito, boolean setActive,
2234 boolean useCurrent) {
2235 Tab tab = null;
2236 if (mTabControl.canCreateNewTab()) {
2237 tab = mTabControl.createNewTab(incognito);
2238 addTab(tab);
2239 if (setActive) {
2240 setActiveTab(tab);
2241 }
2242 } else {
2243 if (useCurrent) {
2244 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002245 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002246 } else {
2247 mUi.showMaxTabsWarning();
2248 }
2249 }
2250 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002251 }
2252
John Reck2bc80422011-06-30 15:11:49 -07002253 @Override
2254 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2255 SnapshotTab tab = null;
2256 if (mTabControl.canCreateNewTab()) {
2257 tab = mTabControl.createSnapshotTab(snapshotId);
2258 addTab(tab);
2259 if (setActive) {
2260 setActiveTab(tab);
2261 }
2262 } else {
2263 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07002264 }
2265 return tab;
2266 }
2267
Michael Kolb8233fac2010-10-26 16:08:53 -07002268 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002269 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002270 * @return boolean True if we successfully switched to a different tab. If
2271 * the indexth tab is null, or if that tab is the same as
2272 * the current one, return false.
2273 */
2274 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002275 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002276 Tab currentTab = mTabControl.getCurrentTab();
2277 if (tab == null || tab == currentTab) {
2278 return false;
2279 }
2280 setActiveTab(tab);
2281 return true;
2282 }
2283
2284 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002285 public void closeCurrentTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002286 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07002287 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07002288 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08002289 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002290 return;
2291 }
Michael Kolbc831b632011-05-11 09:30:34 -07002292 final Tab current = mTabControl.getCurrentTab();
2293 final int pos = mTabControl.getCurrentPosition();
2294 Tab newTab = current.getParent();
2295 if (newTab == null) {
2296 newTab = mTabControl.getTab(pos + 1);
2297 if (newTab == null) {
2298 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002299 }
2300 }
Michael Kolbc831b632011-05-11 09:30:34 -07002301 if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002302 // Close window
2303 closeTab(current);
2304 }
2305 }
2306
2307 /**
2308 * Close the tab, remove its associated title bar, and adjust mTabControl's
2309 * current tab to a valid value.
2310 */
2311 @Override
2312 public void closeTab(Tab tab) {
Michael Kolb2d59c322011-01-25 13:18:55 -08002313 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002314 }
2315
Michael Kolb8233fac2010-10-26 16:08:53 -07002316 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07002317 protected void loadUrlFromContext(String url) {
2318 Tab tab = getCurrentTab();
2319 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002320 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07002321 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002322 url = UrlUtils.smartUrlFilter(url);
2323 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07002324 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07002325 }
2326 }
2327 }
2328
2329 /**
2330 * Load the URL into the given WebView and update the title bar
2331 * to reflect the new load. Call this instead of WebView.loadUrl
2332 * directly.
2333 * @param view The WebView used to load url.
2334 * @param url The URL to load.
2335 */
John Reck71e51422011-07-01 16:49:28 -07002336 @Override
2337 public void loadUrl(Tab tab, String url) {
John Reck26b18322011-06-21 13:08:58 -07002338 loadUrl(tab, url, null);
2339 }
2340
2341 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
2342 if (tab != null) {
2343 dismissSubWindow(tab);
2344 tab.loadUrl(url, headers);
2345 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002346 }
2347
2348 /**
2349 * Load UrlData into a Tab and update the title bar to reflect the new
2350 * load. Call this instead of UrlData.loadIn directly.
2351 * @param t The Tab used to load.
2352 * @param data The UrlData being loaded.
2353 */
2354 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07002355 if (data != null) {
2356 if (data.mVoiceIntent != null) {
2357 t.activateVoiceSearchMode(data.mVoiceIntent);
Michael Kolb14612442011-06-24 13:06:29 -07002358 } else if (data.isPreloaded()) {
2359 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07002360 } else {
2361 loadUrl(t, data.mUrl, data.mHeaders);
2362 }
2363 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002364 }
2365
John Reck30c714c2010-12-16 17:30:34 -08002366 @Override
2367 public void onUserCanceledSsl(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08002368 // TODO: Figure out the "right" behavior
John Reckef654f12011-07-12 16:42:08 -07002369 if (tab.canGoBack()) {
2370 tab.goBack();
John Reck30c714c2010-12-16 17:30:34 -08002371 } else {
John Reckef654f12011-07-12 16:42:08 -07002372 tab.loadUrl(mSettings.getHomePage(), null);
John Reck30c714c2010-12-16 17:30:34 -08002373 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002374 }
2375
2376 void goBackOnePageOrQuit() {
2377 Tab current = mTabControl.getCurrentTab();
2378 if (current == null) {
2379 /*
2380 * Instead of finishing the activity, simply push this to the back
2381 * of the stack and let ActivityManager to choose the foreground
2382 * activity. As BrowserActivity is singleTask, it will be always the
2383 * root of the task. So we can use either true or false for
2384 * moveTaskToBack().
2385 */
2386 mActivity.moveTaskToBack(true);
2387 return;
2388 }
John Reckef654f12011-07-12 16:42:08 -07002389 if (current.canGoBack()) {
2390 current.goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07002391 } else {
2392 // Check to see if we are closing a window that was created by
2393 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002394 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002395 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002396 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002397 // Now we close the other tab
2398 closeTab(current);
2399 } else {
Michael Kolbe28b3472011-08-04 16:54:31 -07002400 if ((current.getAppId() != null) || current.closeOnBack()) {
2401 closeCurrentTab();
2402 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002403 /*
2404 * Instead of finishing the activity, simply push this to the back
2405 * of the stack and let ActivityManager to choose the foreground
2406 * activity. As BrowserActivity is singleTask, it will be always the
2407 * root of the task. So we can use either true or false for
2408 * moveTaskToBack().
2409 */
2410 mActivity.moveTaskToBack(true);
2411 }
2412 }
2413 }
2414
2415 /**
2416 * Feed the previously stored results strings to the BrowserProvider so that
2417 * the SearchDialog will show them instead of the standard searches.
2418 * @param result String to show on the editable line of the SearchDialog.
2419 */
2420 @Override
2421 public void showVoiceSearchResults(String result) {
2422 ContentProviderClient client = mActivity.getContentResolver()
2423 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2424 ContentProvider prov = client.getLocalContentProvider();
2425 BrowserProvider bp = (BrowserProvider) prov;
2426 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2427 client.release();
2428
2429 Bundle bundle = createGoogleSearchSourceBundle(
2430 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2431 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2432 startSearch(result, false, bundle, false);
2433 }
2434
2435 private void startSearch(String initialQuery, boolean selectInitialQuery,
2436 Bundle appSearchData, boolean globalSearch) {
2437 if (appSearchData == null) {
2438 appSearchData = createGoogleSearchSourceBundle(
2439 GOOGLE_SEARCH_SOURCE_TYPE);
2440 }
2441
2442 SearchEngine searchEngine = mSettings.getSearchEngine();
2443 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2444 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2445 }
2446 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2447 globalSearch);
2448 }
2449
2450 private Bundle createGoogleSearchSourceBundle(String source) {
2451 Bundle bundle = new Bundle();
2452 bundle.putString(Search.SOURCE, source);
2453 return bundle;
2454 }
2455
2456 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002457 * helper method for key handler
2458 * returns the current tab if it can't advance
2459 */
Michael Kolbc831b632011-05-11 09:30:34 -07002460 private Tab getNextTab() {
2461 return mTabControl.getTab(Math.min(mTabControl.getTabCount() - 1,
2462 mTabControl.getCurrentPosition() + 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002463 }
2464
2465 /**
2466 * helper method for key handler
2467 * returns the current tab if it can't advance
2468 */
Michael Kolbc831b632011-05-11 09:30:34 -07002469 private Tab getPrevTab() {
2470 return mTabControl.getTab(Math.max(0,
2471 mTabControl.getCurrentPosition() - 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002472 }
2473
2474 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002475 * handle key events in browser
2476 *
2477 * @param keyCode
2478 * @param event
2479 * @return true if handled, false to pass to super
2480 */
2481 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002482 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002483 // Even if MENU is already held down, we need to call to super to open
2484 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002485 if (!noModifiers
2486 && ((KeyEvent.KEYCODE_MENU == keyCode)
2487 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2488 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002489 mMenuIsDown = true;
2490 return false;
2491 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002492
Cary Clark8ff8c662010-12-29 15:03:05 -05002493 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07002494 Tab tab = getCurrentTab();
2495 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05002496
Cary Clark160bbb92011-01-10 11:17:07 -05002497 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2498 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002499
Michael Kolb8233fac2010-10-26 16:08:53 -07002500 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002501 case KeyEvent.KEYCODE_TAB:
2502 if (event.isCtrlPressed()) {
2503 if (event.isShiftPressed()) {
2504 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002505 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002506 } else {
2507 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002508 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002509 }
2510 return true;
2511 }
2512 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002513 case KeyEvent.KEYCODE_SPACE:
2514 // WebView/WebTextView handle the keys in the KeyDown. As
2515 // the Activity's shortcut keys are only handled when WebView
2516 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002517 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002518 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002519 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002520 pageDown();
2521 }
2522 return true;
2523 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002524 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002525 event.startTracking();
2526 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07002527 case KeyEvent.KEYCODE_FORWARD:
2528 if (!noModifiers) break;
2529 tab.goForward();
2530 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002531 case KeyEvent.KEYCODE_DPAD_LEFT:
2532 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002533 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05002534 return true;
2535 }
2536 break;
2537 case KeyEvent.KEYCODE_DPAD_RIGHT:
2538 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002539 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05002540 return true;
2541 }
2542 break;
2543 case KeyEvent.KEYCODE_A:
2544 if (ctrl) {
2545 webView.selectAll();
2546 return true;
2547 }
2548 break;
Michael Kolba4183062011-01-16 10:43:21 -08002549// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002550 case KeyEvent.KEYCODE_C:
2551 if (ctrl) {
2552 webView.copySelection();
2553 return true;
2554 }
2555 break;
Michael Kolba4183062011-01-16 10:43:21 -08002556// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002557// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002558// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002559// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002560// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002561// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002562// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002563// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002564// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002565// case KeyEvent.KEYCODE_M: // unused
2566// case KeyEvent.KEYCODE_N: // in Chrome: new window
2567// case KeyEvent.KEYCODE_O: // in Chrome: open file
2568// case KeyEvent.KEYCODE_P: // in Chrome: print page
2569// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002570// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002571// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2572 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002573 // we can't use the ctrl/shift flags, they check for
2574 // exclusive use of a modifier
2575 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002576 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002577 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002578 } else {
2579 openTabToHomePage();
2580 }
2581 return true;
2582 }
2583 break;
2584// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2585// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb5ae15bd2011-08-16 17:09:27 -07002586// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002587// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2588// case KeyEvent.KEYCODE_Y: // unused
2589// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002590 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002591 // it is a regular key and webview is not null
2592 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002593 }
2594
John Recke6bf4ab2011-02-24 15:48:05 -08002595 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2596 switch(keyCode) {
2597 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07002598 if (mUi.isWebShowing()) {
John Recke6bf4ab2011-02-24 15:48:05 -08002599 bookmarksOrHistoryPicker(true);
2600 return true;
2601 }
2602 break;
2603 }
2604 return false;
2605 }
2606
Michael Kolb8233fac2010-10-26 16:08:53 -07002607 boolean onKeyUp(int keyCode, KeyEvent event) {
Michael Kolb2814a362011-05-19 15:49:41 -07002608 if (KeyEvent.KEYCODE_MENU == keyCode) {
2609 mMenuIsDown = false;
2610 if (event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002611 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002612 }
2613 }
Cary Clark160bbb92011-01-10 11:17:07 -05002614 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002615 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002616 case KeyEvent.KEYCODE_BACK:
2617 if (event.isTracking() && !event.isCanceled()) {
2618 onBackKey();
2619 return true;
2620 }
2621 break;
2622 }
2623 return false;
2624 }
2625
2626 public boolean isMenuDown() {
2627 return mMenuIsDown;
2628 }
2629
Ben Murdoch8029a772010-11-16 11:58:21 +00002630 public void setupAutoFill(Message message) {
2631 // Open the settings activity at the AutoFill profile fragment so that
2632 // the user can create a new profile. When they return, we will dispatch
2633 // the message so that we can autofill the form using their new profile.
2634 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2635 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2636 AutoFillSettingsFragment.class.getName());
2637 mAutoFillSetupMessage = message;
2638 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2639 }
John Reckb3417f02011-01-14 11:01:05 -08002640
2641 @Override
Narayan Kamath5119edd2011-02-23 15:49:17 +00002642 public void registerDropdownChangeListener(DropdownChangeListener d) {
2643 mUi.registerDropdownChangeListener(d);
2644 }
Michael Kolbfbc579a2011-07-07 15:59:33 -07002645
2646 public boolean onSearchRequested() {
2647 mUi.editUrl(false);
2648 return true;
2649 }
2650
John Reck1cf4b792011-07-26 10:22:22 -07002651 @Override
2652 public boolean shouldCaptureThumbnails() {
2653 return mUi.shouldCaptureThumbnails();
2654 }
2655
Michael Kolbc3af0672011-08-09 10:24:41 -07002656 @Override
2657 public void setBlockEvents(boolean block) {
2658 mBlockEvents = block;
2659 }
2660
2661 public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb8a009492011-08-15 15:37:30 -07002662 return mBlockEvents || hasNoActiveTab();
Michael Kolbc3af0672011-08-09 10:24:41 -07002663 }
2664
2665 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb8a009492011-08-15 15:37:30 -07002666 return mBlockEvents || hasNoActiveTab();
Michael Kolbc3af0672011-08-09 10:24:41 -07002667 }
2668
2669 public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb8a009492011-08-15 15:37:30 -07002670 return mBlockEvents || hasNoActiveTab();
Michael Kolbc3af0672011-08-09 10:24:41 -07002671 }
2672
2673 public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb8a009492011-08-15 15:37:30 -07002674 return mBlockEvents || hasNoActiveTab();
Michael Kolbc3af0672011-08-09 10:24:41 -07002675 }
2676
2677 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb8a009492011-08-15 15:37:30 -07002678 return mBlockEvents || hasNoActiveTab();
2679 }
2680
2681 private boolean hasNoActiveTab() {
2682 Tab tab = getCurrentTab();
2683 if (tab == null) {
2684 Log.w(LOGTAG, "Received event with no active tab. Tab count: "
2685 + mTabControl.getTabCount());
2686 }
2687 return tab == null;
Michael Kolbc3af0672011-08-09 10:24:41 -07002688 }
2689
Michael Kolb8233fac2010-10-26 16:08:53 -07002690}