blob: 0a54a89cf7699e43691474d3b310d79fa8bd2553 [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;
Michael Kolb8233fac2010-10-26 16:08:53 -070039import android.net.Uri;
40import android.net.http.SslError;
41import android.os.AsyncTask;
42import android.os.Bundle;
43import android.os.Handler;
44import android.os.Message;
45import android.os.PowerManager;
46import android.os.PowerManager.WakeLock;
Ben Murdoch8029a772010-11-16 11:58:21 +000047import android.preference.PreferenceActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -070048import android.provider.Browser;
49import android.provider.BrowserContract;
Michael Kolb8233fac2010-10-26 16:08:53 -070050import android.provider.BrowserContract.Images;
51import android.provider.ContactsContract;
52import android.provider.ContactsContract.Intents.Insert;
Michael Kolbcfa3af52010-12-14 10:36:11 -080053import android.speech.RecognizerIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070054import android.text.TextUtils;
55import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080056import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070057import android.view.ActionMode;
58import android.view.ContextMenu;
59import android.view.ContextMenu.ContextMenuInfo;
60import android.view.Gravity;
61import android.view.KeyEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070062import android.view.Menu;
63import android.view.MenuInflater;
64import android.view.MenuItem;
65import android.view.MenuItem.OnMenuItemClickListener;
Michael Kolbc3af0672011-08-09 10:24:41 -070066import android.view.MotionEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070067import android.view.View;
68import android.webkit.CookieManager;
69import android.webkit.CookieSyncManager;
70import android.webkit.HttpAuthHandler;
71import android.webkit.SslErrorHandler;
72import android.webkit.ValueCallback;
73import android.webkit.WebChromeClient;
74import android.webkit.WebIconDatabase;
75import android.webkit.WebSettings;
76import android.webkit.WebView;
Leon Scrogginsac993842011-02-02 12:54:07 -050077import android.widget.Toast;
Michael Kolb8233fac2010-10-26 16:08:53 -070078
Michael Kolb4bd767d2011-05-27 11:33:55 -070079import com.android.browser.IntentHandler.UrlData;
John Reck2bc80422011-06-30 15:11:49 -070080import com.android.browser.UI.ComboViews;
Michael Kolb4bd767d2011-05-27 11:33:55 -070081import com.android.browser.UI.DropdownChangeListener;
82import com.android.browser.provider.BrowserProvider;
John Reck1cf4b792011-07-26 10:22:22 -070083import com.android.browser.provider.BrowserProvider2.Thumbnails;
John Reck8cc92352011-07-06 17:41:52 -070084import com.android.browser.provider.SnapshotProvider.Snapshots;
Michael Kolb4bd767d2011-05-27 11:33:55 -070085import com.android.browser.search.SearchEngine;
86import com.android.common.Search;
87
Michael Kolb8233fac2010-10-26 16:08:53 -070088import java.io.ByteArrayOutputStream;
Michael Kolb8233fac2010-10-26 16:08:53 -070089import java.net.URLEncoder;
John Reck1cf4b792011-07-26 10:22:22 -070090import java.util.ArrayList;
Michael Kolb8233fac2010-10-26 16:08:53 -070091import java.util.Calendar;
92import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -080093import java.util.List;
John Reck26b18322011-06-21 13:08:58 -070094import java.util.Map;
Michael Kolb8233fac2010-10-26 16:08:53 -070095
96/**
97 * Controller for browser
98 */
99public class Controller
100 implements WebViewController, UiController {
101
102 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800103 private static final String SEND_APP_ID_EXTRA =
104 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
Michael Kolba4261fd2011-05-05 11:27:37 -0700105 private static final String INCOGNITO_URI = "browser:incognito";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800106
Michael Kolb8233fac2010-10-26 16:08:53 -0700107
108 // public message ids
109 public final static int LOAD_URL = 1001;
110 public final static int STOP_LOAD = 1002;
111
112 // Message Ids
113 private static final int FOCUS_NODE_HREF = 102;
114 private static final int RELEASE_WAKELOCK = 107;
115
116 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
117
118 private static final int OPEN_BOOKMARKS = 201;
119
120 private static final int EMPTY_MENU = -1;
121
Michael Kolb8233fac2010-10-26 16:08:53 -0700122 // activity requestCode
John Reckd3e4d5b2011-07-13 15:48:43 -0700123 final static int COMBO_VIEW = 1;
Michael Kolb8233fac2010-10-26 16:08:53 -0700124 final static int PREFERENCES_PAGE = 3;
125 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000126 final static int AUTOFILL_SETUP = 5;
127
Michael Kolb8233fac2010-10-26 16:08:53 -0700128 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
129
130 // As the ids are dynamically created, we can't guarantee that they will
131 // be in sequence, so this static array maps ids to a window number.
132 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
133 { R.id.window_one_menu_id, R.id.window_two_menu_id,
134 R.id.window_three_menu_id, R.id.window_four_menu_id,
135 R.id.window_five_menu_id, R.id.window_six_menu_id,
136 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
137
138 // "source" parameter for Google search through search key
139 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
140 // "source" parameter for Google search through simplily type
141 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
142
Guang Zhu9e78f512011-05-04 11:45:11 -0700143 // "no-crash-recovery" parameter in intetnt to suppress crash recovery
144 final static String NO_CRASH_RECOVERY = "no-crash-recovery";
145
John Reckd7dd9b22011-08-30 09:18:29 -0700146 // A bitmap that is re-used in createScreenshot as scratch space
147 private static Bitmap sThumbnailBitmap;
148
Michael Kolb8233fac2010-10-26 16:08:53 -0700149 private Activity mActivity;
150 private UI mUi;
151 private TabControl mTabControl;
152 private BrowserSettings mSettings;
153 private WebViewFactory mFactory;
154
155 private WakeLock mWakeLock;
156
157 private UrlHandler mUrlHandler;
158 private UploadHandler mUploadHandler;
159 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700160 private PageDialogsHandler mPageDialogsHandler;
161 private NetworkStateHandler mNetworkHandler;
162
Ben Murdoch8029a772010-11-16 11:58:21 +0000163 private Message mAutoFillSetupMessage;
164
Michael Kolb8233fac2010-10-26 16:08:53 -0700165 private boolean mShouldShowErrorConsole;
166
167 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
168
169 // FIXME, temp address onPrepareMenu performance problem.
170 // When we move everything out of view, we should rewrite this.
171 private int mCurrentMenuState = 0;
172 private int mMenuState = R.id.MAIN_MENU;
173 private int mOldMenuState = EMPTY_MENU;
174 private Menu mCachedMenu;
175
Michael Kolb8233fac2010-10-26 16:08:53 -0700176 private boolean mMenuIsDown;
177
178 // For select and find, we keep track of the ActionMode so that
179 // finish() can be called as desired.
180 private ActionMode mActionMode;
181
182 /**
183 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
184 * of whether the configuration has changed. The first onMenuOpened call
185 * after a configuration change is simply a reopening of the same menu
186 * (i.e. mIconView did not change).
187 */
188 private boolean mConfigChanged;
189
190 /**
191 * Keeps track of whether the options menu is open. This is important in
192 * determining whether to show or hide the title bar overlay
193 */
194 private boolean mOptionsMenuOpen;
195
196 /**
197 * Whether or not the options menu is in its bigger, popup menu form. When
198 * true, we want the title bar overlay to be gone. When false, we do not.
199 * Only meaningful if mOptionsMenuOpen is true.
200 */
201 private boolean mExtendedMenuOpen;
202
203 private boolean mInLoad;
204
205 private boolean mActivityPaused = true;
206 private boolean mLoadStopped;
207
208 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500209 // Checks to see when the bookmarks database has changed, and updates the
210 // Tabs' notion of whether they represent bookmarked sites.
211 private ContentObserver mBookmarksObserver;
John Reck847b5322011-04-14 17:02:18 -0700212 private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700213
John Reck30b065e2011-07-19 10:58:05 -0700214 private boolean mSimulateActionBarOverlayMode;
215
Michael Kolbc3af0672011-08-09 10:24:41 -0700216 private boolean mBlockEvents;
217
John Reckbc490d22011-07-22 15:04:59 -0700218 public Controller(Activity browser, boolean preloadCrashState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700219 mActivity = browser;
220 mSettings = BrowserSettings.getInstance();
221 mTabControl = new TabControl(this);
222 mSettings.setController(this);
John Reck378a4102011-06-09 16:23:01 -0700223 mCrashRecoveryHandler = CrashRecoveryHandler.initialize(this);
John Reckbc490d22011-07-22 15:04:59 -0700224 if (preloadCrashState) {
225 mCrashRecoveryHandler.preloadCrashState();
226 }
Michael Kolb14612442011-06-24 13:06:29 -0700227 mFactory = new BrowserWebViewFactory(browser);
Michael Kolb8233fac2010-10-26 16:08:53 -0700228
229 mUrlHandler = new UrlHandler(this);
230 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700231 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
232
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));
John Reck52be4782011-08-26 15:37:29 -0700335 if (tabs.size() == 0) {
336 openTabToHomePage();
337 }
John Reck1cf4b792011-07-26 10:22:22 -0700338 mUi.updateTabs(tabs);
Michael Kolb8233fac2010-10-26 16:08:53 -0700339 // TabControl.restoreState() will create a new tab even if
340 // restoring the state fails.
341 setActiveTab(mTabControl.getCurrentTab());
John Reckdb22ec42011-06-29 11:31:24 -0700342 // Handle the intent
343 mIntentHandler.onNewIntent(intent);
Michael Kolb8233fac2010-10-26 16:08:53 -0700344 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700345 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700346 String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb8233fac2010-10-26 16:08:53 -0700347 if (jsFlags.trim().length() != 0) {
348 getCurrentWebView().setJsFlags(jsFlags);
349 }
John Reck439c9a52010-12-14 10:04:39 -0800350 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
351 bookmarksOrHistoryPicker(false);
352 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700353 }
354
John Reck1cf4b792011-07-26 10:22:22 -0700355 private static class PruneThumbnails implements Runnable {
356 private Context mContext;
357 private List<Long> mIds;
358
359 PruneThumbnails(Context context, List<Long> preserveIds) {
360 mContext = context.getApplicationContext();
361 mIds = preserveIds;
362 }
363
364 @Override
365 public void run() {
366 ContentResolver cr = mContext.getContentResolver();
367 if (mIds == null || mIds.size() == 0) {
368 cr.delete(Thumbnails.CONTENT_URI, null, null);
369 } else {
370 int length = mIds.size();
371 StringBuilder where = new StringBuilder();
372 where.append(Thumbnails._ID);
373 where.append(" not in (");
374 for (int i = 0; i < length; i++) {
375 where.append(mIds.get(i));
376 if (i < (length - 1)) {
377 where.append(",");
378 }
379 }
380 where.append(")");
381 cr.delete(Thumbnails.CONTENT_URI, where.toString(), null);
382 }
383 }
384
385 }
386
Michael Kolb1514bb72010-11-22 09:11:48 -0800387 @Override
388 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700389 return mFactory;
390 }
391
392 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800393 public void onSetWebView(Tab tab, WebView view) {
394 mUi.onSetWebView(tab, view);
395 }
396
397 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800398 public void createSubWindow(Tab tab) {
399 endActionMode();
400 WebView mainView = tab.getWebView();
401 WebView subView = mFactory.createWebView((mainView == null)
402 ? false
403 : mainView.isPrivateBrowsingEnabled());
404 mUi.createSubWindow(tab, subView);
405 }
406
407 @Override
Michael Kolb14612442011-06-24 13:06:29 -0700408 public Context getContext() {
409 return mActivity;
410 }
411
412 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700413 public Activity getActivity() {
414 return mActivity;
415 }
416
417 void setUi(UI ui) {
418 mUi = ui;
419 }
420
421 BrowserSettings getSettings() {
422 return mSettings;
423 }
424
425 IntentHandler getIntentHandler() {
426 return mIntentHandler;
427 }
428
429 @Override
430 public UI getUi() {
431 return mUi;
432 }
433
434 int getMaxTabs() {
435 return mActivity.getResources().getInteger(R.integer.max_tabs);
436 }
437
438 @Override
439 public TabControl getTabControl() {
440 return mTabControl;
441 }
442
Michael Kolb1bf23132010-11-19 12:55:12 -0800443 @Override
444 public List<Tab> getTabs() {
445 return mTabControl.getTabs();
446 }
447
John Reckaf262e72011-07-25 13:55:44 -0700448 // Open the icon database.
449 private void openIconDatabase() {
450 // We have to call getInstance on the UI thread
451 final WebIconDatabase instance = WebIconDatabase.getInstance();
452 BackgroundHandler.execute(new Runnable() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000453
John Reckaf262e72011-07-25 13:55:44 -0700454 @Override
455 public void run() {
456 instance.open(mActivity.getDir("icons", 0).getPath());
Michael Kolb8233fac2010-10-26 16:08:53 -0700457 }
John Reckaf262e72011-07-25 13:55:44 -0700458 });
Michael Kolb8233fac2010-10-26 16:08:53 -0700459 }
460
461 private void startHandler() {
462 mHandler = new Handler() {
463
464 @Override
465 public void handleMessage(Message msg) {
466 switch (msg.what) {
467 case OPEN_BOOKMARKS:
468 bookmarksOrHistoryPicker(false);
469 break;
470 case FOCUS_NODE_HREF:
471 {
472 String url = (String) msg.getData().get("url");
473 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500474 String src = (String) msg.getData().get("src");
475 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700476 if (TextUtils.isEmpty(url)) {
477 break;
478 }
479 HashMap focusNodeMap = (HashMap) msg.obj;
480 WebView view = (WebView) focusNodeMap.get("webview");
481 // Only apply the action if the top window did not change.
482 if (getCurrentTopWebView() != view) {
483 break;
484 }
485 switch (msg.arg1) {
486 case R.id.open_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700487 loadUrlFromContext(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700488 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500489 case R.id.view_image_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700490 loadUrlFromContext(src);
Cary Clark043c2d62010-12-15 11:19:39 -0500491 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500492 case R.id.open_newtab_context_menu_id:
493 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -0700494 openTab(url, parent,
495 !mSettings.openInBackground(), true);
Leon Scroggins026f2542010-11-22 13:26:12 -0500496 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700497 case R.id.copy_link_context_menu_id:
498 copy(url);
499 break;
500 case R.id.save_link_context_menu_id:
501 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500502 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000503 mActivity, url, null, null, null,
504 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700505 break;
506 }
507 break;
508 }
509
510 case LOAD_URL:
John Reck26b18322011-06-21 13:08:58 -0700511 loadUrlFromContext((String) msg.obj);
Michael Kolb8233fac2010-10-26 16:08:53 -0700512 break;
513
514 case STOP_LOAD:
515 stopLoading();
516 break;
517
518 case RELEASE_WAKELOCK:
John Reckf57c0292011-07-21 18:15:39 -0700519 if (mWakeLock != null && mWakeLock.isHeld()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700520 mWakeLock.release();
521 // if we reach here, Browser should be still in the
522 // background loading after WAKELOCK_TIMEOUT (5-min).
523 // To avoid burning the battery, stop loading.
524 mTabControl.stopAllLoading();
525 }
526 break;
527
528 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800529 Tab tab = (Tab) msg.obj;
530 if (tab != null) {
531 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700532 }
533 break;
534 }
535 }
536 };
537
538 }
539
John Reckef654f12011-07-12 16:42:08 -0700540 @Override
Martijn Coenenb2f93552011-06-14 10:48:35 +0200541 public Tab getCurrentTab() {
542 return mTabControl.getCurrentTab();
543 }
544
Michael Kolbba99c5d2010-11-29 14:57:41 -0800545 @Override
546 public void shareCurrentPage() {
547 shareCurrentPage(mTabControl.getCurrentTab());
548 }
549
550 private void shareCurrentPage(Tab tab) {
551 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800552 sharePage(mActivity, tab.getTitle(),
553 tab.getUrl(), tab.getFavicon(),
554 createScreenshot(tab.getWebView(),
555 getDesiredThumbnailWidth(mActivity),
556 getDesiredThumbnailHeight(mActivity)));
557 }
558 }
559
Michael Kolb8233fac2010-10-26 16:08:53 -0700560 /**
561 * Share a page, providing the title, url, favicon, and a screenshot. Uses
562 * an {@link Intent} to launch the Activity chooser.
563 * @param c Context used to launch a new Activity.
564 * @param title Title of the page. Stored in the Intent with
565 * {@link Intent#EXTRA_SUBJECT}
566 * @param url URL of the page. Stored in the Intent with
567 * {@link Intent#EXTRA_TEXT}
568 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
569 * with {@link Browser#EXTRA_SHARE_FAVICON}
570 * @param screenshot Bitmap of a screenshot of the page. Stored in the
571 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
572 */
573 static final void sharePage(Context c, String title, String url,
574 Bitmap favicon, Bitmap screenshot) {
575 Intent send = new Intent(Intent.ACTION_SEND);
576 send.setType("text/plain");
577 send.putExtra(Intent.EXTRA_TEXT, url);
578 send.putExtra(Intent.EXTRA_SUBJECT, title);
579 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
580 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
581 try {
582 c.startActivity(Intent.createChooser(send, c.getString(
583 R.string.choosertitle_sharevia)));
584 } catch(android.content.ActivityNotFoundException ex) {
585 // if no app handles it, do nothing
586 }
587 }
588
589 private void copy(CharSequence text) {
590 ClipboardManager cm = (ClipboardManager) mActivity
591 .getSystemService(Context.CLIPBOARD_SERVICE);
592 cm.setText(text);
593 }
594
595 // lifecycle
596
597 protected void onConfgurationChanged(Configuration config) {
598 mConfigChanged = true;
599 if (mPageDialogsHandler != null) {
600 mPageDialogsHandler.onConfigurationChanged(config);
601 }
602 mUi.onConfigurationChanged(config);
603 }
604
605 @Override
606 public void handleNewIntent(Intent intent) {
Michael Kolb59e232c2011-08-18 17:19:53 -0700607 if (!mUi.isWebShowing()) {
608 mUi.showWeb(false);
609 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700610 mIntentHandler.onNewIntent(intent);
611 }
612
613 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800614 if (mUi.isCustomViewShowing()) {
615 hideCustomView();
616 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700617 if (mActivityPaused) {
618 Log.e(LOGTAG, "BrowserActivity is already paused.");
619 return;
620 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700621 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800622 Tab tab = mTabControl.getCurrentTab();
623 if (tab != null) {
624 tab.pause();
625 if (!pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700626 if (mWakeLock == null) {
627 PowerManager pm = (PowerManager) mActivity
628 .getSystemService(Context.POWER_SERVICE);
629 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
630 }
Michael Kolb70976932010-11-30 11:34:01 -0800631 mWakeLock.acquire();
632 mHandler.sendMessageDelayed(mHandler
633 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
634 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700635 }
636 mUi.onPause();
637 mNetworkHandler.onPause();
638
639 WebView.disablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100640 NfcHandler.unregister(mActivity);
John Reckd7dd9b22011-08-30 09:18:29 -0700641 if (sThumbnailBitmap != null) {
642 sThumbnailBitmap.recycle();
643 sThumbnailBitmap = null;
644 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700645 }
646
John Reck1cf4b792011-07-26 10:22:22 -0700647 void onSaveInstanceState(Bundle outState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700648 // the default implementation requires each view to have an id. As the
649 // browser handles the state itself and it doesn't use id for the views,
650 // don't call the default implementation. Otherwise it will trigger the
651 // warning like this, "couldn't save which view has focus because the
652 // focused view XXX has no id".
653
654 // Save all the tabs
John Reck1cf4b792011-07-26 10:22:22 -0700655 mTabControl.saveState(outState);
John Reck24f18262011-06-17 14:47:20 -0700656 if (!outState.isEmpty()) {
657 // Save time so that we know how old incognito tabs (if any) are.
658 outState.putSerializable("lastActiveDate", Calendar.getInstance());
659 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700660 }
661
662 void onResume() {
663 if (!mActivityPaused) {
664 Log.e(LOGTAG, "BrowserActivity is already resumed.");
665 return;
666 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700667 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800668 Tab current = mTabControl.getCurrentTab();
669 if (current != null) {
670 current.resume();
671 resumeWebViewTimers(current);
672 }
John Reckf57c0292011-07-21 18:15:39 -0700673 releaseWakeLock();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200674
Michael Kolb8233fac2010-10-26 16:08:53 -0700675 mUi.onResume();
676 mNetworkHandler.onResume();
677 WebView.enablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100678 NfcHandler.register(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700679 }
680
John Reckf57c0292011-07-21 18:15:39 -0700681 private void releaseWakeLock() {
682 if (mWakeLock != null && mWakeLock.isHeld()) {
683 mHandler.removeMessages(RELEASE_WAKELOCK);
684 mWakeLock.release();
685 }
686 }
687
Michael Kolb70976932010-11-30 11:34:01 -0800688 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800689 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800690 * @param tab guaranteed non-null
691 */
692 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700693 boolean inLoad = tab.inPageLoad();
694 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
695 CookieSyncManager.getInstance().startSync();
696 WebView w = tab.getWebView();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100697 WebViewTimersControl.getInstance().onBrowserActivityResume(w);
Michael Kolb8233fac2010-10-26 16:08:53 -0700698 }
699 }
700
Michael Kolb70976932010-11-30 11:34:01 -0800701 /**
702 * Pause all WebView timers using the WebView of the given tab
703 * @param tab
704 * @return true if the timers are paused or tab is null
705 */
706 private boolean pauseWebViewTimers(Tab tab) {
707 if (tab == null) {
708 return true;
709 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700710 CookieSyncManager.getInstance().stopSync();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100711 WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView());
Michael Kolb8233fac2010-10-26 16:08:53 -0700712 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700713 }
Michael Kolb70976932010-11-30 11:34:01 -0800714 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700715 }
716
717 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800718 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700719 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
720 mUploadHandler = null;
721 }
722 if (mTabControl == null) return;
723 mUi.onDestroy();
724 // Remove the current tab and sub window
725 Tab t = mTabControl.getCurrentTab();
726 if (t != null) {
727 dismissSubWindow(t);
728 removeTab(t);
729 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500730 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700731 // Destroy all the tabs
732 mTabControl.destroy();
733 WebIconDatabase.getInstance().close();
734 // Stop watching the default geolocation permissions
735 mSystemAllowGeolocationOrigins.stop();
736 mSystemAllowGeolocationOrigins = null;
737 }
738
739 protected boolean isActivityPaused() {
740 return mActivityPaused;
741 }
742
743 protected void onLowMemory() {
744 mTabControl.freeMemory();
745 }
746
747 @Override
748 public boolean shouldShowErrorConsole() {
749 return mShouldShowErrorConsole;
750 }
751
752 protected void setShouldShowErrorConsole(boolean show) {
753 if (show == mShouldShowErrorConsole) {
754 // Nothing to do.
755 return;
756 }
757 mShouldShowErrorConsole = show;
758 Tab t = mTabControl.getCurrentTab();
759 if (t == null) {
760 // There is no current tab so we cannot toggle the error console
761 return;
762 }
763 mUi.setShouldShowErrorConsole(t, show);
764 }
765
766 @Override
767 public void stopLoading() {
768 mLoadStopped = true;
769 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700770 WebView w = getCurrentTopWebView();
771 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700772 mUi.onPageStopped(tab);
773 }
774
775 boolean didUserStopLoading() {
776 return mLoadStopped;
777 }
778
779 // WebViewController
780
781 @Override
John Reck324d4402011-01-11 16:56:42 -0800782 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700783
784 // We've started to load a new page. If there was a pending message
785 // to save a screenshot then we will now take the new page and save
786 // an incorrect screenshot. Therefore, remove any pending thumbnail
787 // messages from the queue.
788 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800789 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700790
791 // reset sync timer to avoid sync starts during loading a page
792 CookieSyncManager.getInstance().resetSync();
793
794 if (!mNetworkHandler.isNetworkUp()) {
795 view.setNetworkAvailable(false);
796 }
797
798 // when BrowserActivity just starts, onPageStarted may be called before
799 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
800 // to start the timer. As we won't switch tabs while an activity is in
801 // pause state, we can ensure calling resume and pause in pair.
802 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800803 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700804 }
805 mLoadStopped = false;
806 if (!mNetworkHandler.isNetworkUp()) {
807 mNetworkHandler.createAndShowNetworkDialog();
808 }
809 endActionMode();
810
John Reck30c714c2010-12-16 17:30:34 -0800811 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700812
John Reck324d4402011-01-11 16:56:42 -0800813 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700814 // update the bookmark database for favicon
815 maybeUpdateFavicon(tab, null, url, favicon);
816
817 Performance.tracePageStart(url);
818
819 // Performance probe
820 if (false) {
821 Performance.onPageStarted();
822 }
823
824 }
825
826 @Override
John Reck324d4402011-01-11 16:56:42 -0800827 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800828 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800829 if (!tab.isPrivateBrowsingEnabled()
John Reckd8c74522011-06-14 08:45:00 -0700830 && !TextUtils.isEmpty(tab.getUrl())
831 && !tab.isSnapshot()) {
John Recka1696282011-07-08 14:10:37 -0700832 // Only update the bookmark screenshot if the user did not
833 // cancel the load early and there is not already
834 // a pending update for the tab.
Michael Kolb8233fac2010-10-26 16:08:53 -0700835 if (tab.inForeground() && !didUserStopLoading()
836 || !tab.inForeground()) {
John Recka1696282011-07-08 14:10:37 -0700837 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
838 mHandler.sendMessageDelayed(mHandler.obtainMessage(
839 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
840 500);
841 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700842 }
843 }
844 // pause the WebView timer and release the wake lock if it is finished
845 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800846 if (mActivityPaused && pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700847 releaseWakeLock();
Michael Kolb8233fac2010-10-26 16:08:53 -0700848 }
Martijn Coenenb2f93552011-06-14 10:48:35 +0200849
Michael Kolb8233fac2010-10-26 16:08:53 -0700850 // Performance probe
851 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800852 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700853 }
854
855 Performance.tracePageFinished();
856 }
857
858 @Override
John Reck30c714c2010-12-16 17:30:34 -0800859 public void onProgressChanged(Tab tab) {
John Reck6c2e2f32011-08-22 13:41:23 -0700860 mCrashRecoveryHandler.backupState();
John Reck30c714c2010-12-16 17:30:34 -0800861 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700862
863 if (newProgress == 100) {
864 CookieSyncManager.getInstance().sync();
865 // onProgressChanged() may continue to be called after the main
866 // frame has finished loading, as any remaining sub frames continue
867 // to load. We'll only get called once though with newProgress as
868 // 100 when everything is loaded. (onPageFinished is called once
869 // when the main frame completes loading regardless of the state of
870 // any sub frames so calls to onProgressChanges may continue after
871 // onPageFinished has executed)
872 if (mInLoad) {
873 mInLoad = false;
874 updateInLoadMenuItems(mCachedMenu);
875 }
876 } else {
877 if (!mInLoad) {
878 // onPageFinished may have already been called but a subframe is
879 // still loading and updating the progress. Reset mInLoad and
880 // update the menu items.
881 mInLoad = true;
882 updateInLoadMenuItems(mCachedMenu);
883 }
884 }
John Reck30c714c2010-12-16 17:30:34 -0800885 mUi.onProgressChanged(tab);
886 }
887
888 @Override
889 public void onUpdatedLockIcon(Tab tab) {
890 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700891 }
892
893 @Override
894 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800895 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800896 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800897 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700898 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
899 return;
900 }
901 // Update the title in the history database if not in private browsing mode
902 if (!tab.isPrivateBrowsingEnabled()) {
John Reckf57c0292011-07-21 18:15:39 -0700903 DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700904 }
905 }
906
907 @Override
908 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800909 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700910 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
911 }
912
913 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800914 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
915 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700916 }
917
918 @Override
919 public boolean shouldOverrideKeyEvent(KeyEvent event) {
920 if (mMenuIsDown) {
921 // only check shortcut key when MENU is held
922 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
923 event);
924 } else {
925 return false;
926 }
927 }
928
929 @Override
930 public void onUnhandledKeyEvent(KeyEvent event) {
931 if (!isActivityPaused()) {
932 if (event.getAction() == KeyEvent.ACTION_DOWN) {
933 mActivity.onKeyDown(event.getKeyCode(), event);
934 } else {
935 mActivity.onKeyUp(event.getKeyCode(), event);
936 }
937 }
938 }
939
940 @Override
John Reck324d4402011-01-11 16:56:42 -0800941 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700942 // Don't save anything in private browsing mode
943 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800944 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700945
John Reck324d4402011-01-11 16:56:42 -0800946 if (TextUtils.isEmpty(url)
947 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700948 return;
949 }
John Reckf57c0292011-07-21 18:15:39 -0700950 DataController.getInstance(mActivity).updateVisitedHistory(url);
John Reck6c2e2f32011-08-22 13:41:23 -0700951 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -0700952 }
953
954 @Override
955 public void getVisitedHistory(final ValueCallback<String[]> callback) {
956 AsyncTask<Void, Void, String[]> task =
957 new AsyncTask<Void, Void, String[]>() {
958 @Override
959 public String[] doInBackground(Void... unused) {
960 return Browser.getVisitedHistory(mActivity.getContentResolver());
961 }
962 @Override
963 public void onPostExecute(String[] result) {
964 callback.onReceiveValue(result);
965 }
966 };
967 task.execute();
968 }
969
970 @Override
971 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
972 final HttpAuthHandler handler, final String host,
973 final String realm) {
974 String username = null;
975 String password = null;
976
977 boolean reuseHttpAuthUsernamePassword
978 = handler.useHttpAuthUsernamePassword();
979
980 if (reuseHttpAuthUsernamePassword && view != null) {
981 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
982 if (credentials != null && credentials.length == 2) {
983 username = credentials[0];
984 password = credentials[1];
985 }
986 }
987
988 if (username != null && password != null) {
989 handler.proceed(username, password);
990 } else {
Ben Murdochfdd37112011-08-05 15:48:14 +0100991 if (tab.inForeground() && !handler.suppressDialog()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700992 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
993 } else {
994 handler.cancel();
995 }
996 }
997 }
998
999 @Override
1000 public void onDownloadStart(Tab tab, String url, String userAgent,
1001 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001002 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -05001003 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001004 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
1005 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001006 // This Tab was opened for the sole purpose of downloading a
1007 // file. Remove it.
1008 if (tab == mTabControl.getCurrentTab()) {
1009 // In this case, the Tab is still on top.
1010 goBackOnePageOrQuit();
1011 } else {
1012 // In this case, it is not.
1013 closeTab(tab);
1014 }
1015 }
1016 }
1017
1018 @Override
1019 public Bitmap getDefaultVideoPoster() {
1020 return mUi.getDefaultVideoPoster();
1021 }
1022
1023 @Override
1024 public View getVideoLoadingProgressView() {
1025 return mUi.getVideoLoadingProgressView();
1026 }
1027
1028 @Override
1029 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1030 SslError error) {
1031 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1032 }
1033
Patrick Scott92066772011-03-10 08:46:27 -05001034 @Override
1035 public void showAutoLogin(Tab tab) {
1036 assert tab.inForeground();
1037 // Update the title bar to show the auto-login request.
1038 mUi.showAutoLogin(tab);
1039 }
1040
1041 @Override
1042 public void hideAutoLogin(Tab tab) {
1043 assert tab.inForeground();
1044 mUi.hideAutoLogin(tab);
1045 }
1046
Michael Kolb8233fac2010-10-26 16:08:53 -07001047 // helper method
1048
1049 /*
1050 * Update the favorites icon if the private browsing isn't enabled and the
1051 * icon is valid.
1052 */
1053 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1054 final String url, Bitmap favicon) {
1055 if (favicon == null) {
1056 return;
1057 }
1058 if (!tab.isPrivateBrowsingEnabled()) {
1059 Bookmarks.updateFavicon(mActivity
1060 .getContentResolver(), originalUrl, url, favicon);
1061 }
1062 }
1063
Leon Scroggins4cd97792010-12-03 15:31:56 -05001064 @Override
1065 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001066 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001067 mUi.bookmarkedStatusHasChanged(tab);
1068 }
1069
Michael Kolb8233fac2010-10-26 16:08:53 -07001070 // end WebViewController
1071
1072 protected void pageUp() {
1073 getCurrentTopWebView().pageUp(false);
1074 }
1075
1076 protected void pageDown() {
1077 getCurrentTopWebView().pageDown(false);
1078 }
1079
1080 // callback from phone title bar
1081 public void editUrl() {
1082 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001083 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001084 }
1085
Michael Kolbcfa3af52010-12-14 10:36:11 -08001086 public void startVoiceSearch() {
1087 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1088 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1089 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1090 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1091 mActivity.getComponentName().flattenToString());
1092 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001093 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001094 mActivity.startActivity(intent);
1095 }
1096
Michael Kolb11d19782011-03-20 10:17:40 -07001097 @Override
1098 public void activateVoiceSearchMode(String title, List<String> results) {
1099 mUi.showVoiceTitleBar(title, results);
Michael Kolb8233fac2010-10-26 16:08:53 -07001100 }
1101
1102 public void revertVoiceSearchMode(Tab tab) {
1103 mUi.revertVoiceTitleBar(tab);
1104 }
1105
Michael Kolb736990c2011-03-20 10:01:20 -07001106 public boolean supportsVoiceSearch() {
John Reck35e9dd62011-04-25 09:01:54 -07001107 SearchEngine searchEngine = getSettings().getSearchEngine();
Michael Kolb736990c2011-03-20 10:01:20 -07001108 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1109 }
1110
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001111 public void showCustomView(Tab tab, View view, int requestedOrientation,
Michael Kolb8233fac2010-10-26 16:08:53 -07001112 WebChromeClient.CustomViewCallback callback) {
1113 if (tab.inForeground()) {
1114 if (mUi.isCustomViewShowing()) {
1115 callback.onCustomViewHidden();
1116 return;
1117 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001118 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001119 // Save the menu state and set it to empty while the custom
1120 // view is showing.
1121 mOldMenuState = mMenuState;
1122 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001123 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001124 }
1125 }
1126
1127 @Override
1128 public void hideCustomView() {
1129 if (mUi.isCustomViewShowing()) {
1130 mUi.onHideCustomView();
1131 // Reset the old menu state.
1132 mMenuState = mOldMenuState;
1133 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001134 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001135 }
1136 }
1137
1138 protected void onActivityResult(int requestCode, int resultCode,
1139 Intent intent) {
1140 if (getCurrentTopWebView() == null) return;
1141 switch (requestCode) {
1142 case PREFERENCES_PAGE:
1143 if (resultCode == Activity.RESULT_OK && intent != null) {
1144 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001145 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001146 mTabControl.removeParentChildRelationShips();
1147 }
1148 }
1149 break;
1150 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001151 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001152 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001153 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001154 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001155 case AUTOFILL_SETUP:
1156 // Determine whether a profile was actually set up or not
1157 // and if so, send the message back to the WebTextView to
1158 // fill the form with the new profile.
1159 if (getSettings().getAutoFillProfile() != null) {
1160 mAutoFillSetupMessage.sendToTarget();
1161 mAutoFillSetupMessage = null;
1162 }
1163 break;
John Reckd3e4d5b2011-07-13 15:48:43 -07001164 case COMBO_VIEW:
1165 if (intent == null || resultCode != Activity.RESULT_OK) {
1166 break;
1167 }
John Reck3ba45532011-08-11 16:26:53 -07001168 mUi.showWeb(false);
John Reckd3e4d5b2011-07-13 15:48:43 -07001169 if (Intent.ACTION_VIEW.equals(intent.getAction())) {
1170 Tab t = getCurrentTab();
1171 Uri uri = intent.getData();
1172 loadUrl(t, uri.toString());
1173 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
1174 String[] urls = intent.getStringArrayExtra(
1175 ComboViewActivity.EXTRA_OPEN_ALL);
1176 Tab parent = getCurrentTab();
1177 for (String url : urls) {
1178 parent = openTab(url, parent,
1179 !mSettings.openInBackground(), true);
1180 }
1181 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
1182 long id = intent.getLongExtra(
1183 ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
1184 if (id >= 0) {
1185 createNewSnapshotTab(id, true);
1186 }
1187 }
1188 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001189 default:
1190 break;
1191 }
1192 getCurrentTopWebView().requestFocus();
1193 }
1194
1195 /**
1196 * Open the Go page.
1197 * @param startWithHistory If true, open starting on the history tab.
1198 * Otherwise, start with the bookmarks tab.
1199 */
1200 @Override
1201 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1202 if (mTabControl.getCurrentWebView() == null) {
1203 return;
1204 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001205 // clear action mode
1206 if (isInCustomActionMode()) {
1207 endActionMode();
1208 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001209 Bundle extras = new Bundle();
1210 // Disable opening in a new window if we have maxed out the windows
1211 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1212 !mTabControl.canCreateNewTab());
John Reck2bc80422011-06-30 15:11:49 -07001213 mUi.showComboView(startWithHistory
1214 ? ComboViews.History : ComboViews.Bookmarks, extras);
Michael Kolb8233fac2010-10-26 16:08:53 -07001215 }
1216
1217 // combo view callbacks
1218
Michael Kolb8233fac2010-10-26 16:08:53 -07001219 // key handling
1220 protected void onBackKey() {
1221 if (!mUi.onBackKey()) {
1222 WebView subwindow = mTabControl.getCurrentSubWindow();
1223 if (subwindow != null) {
1224 if (subwindow.canGoBack()) {
1225 subwindow.goBack();
1226 } else {
1227 dismissSubWindow(mTabControl.getCurrentTab());
1228 }
1229 } else {
1230 goBackOnePageOrQuit();
1231 }
1232 }
1233 }
1234
Michael Kolb4bd767d2011-05-27 11:33:55 -07001235 protected boolean onMenuKey() {
1236 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001237 }
1238
Michael Kolb8233fac2010-10-26 16:08:53 -07001239 // menu handling and state
1240 // TODO: maybe put into separate handler
1241
1242 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckd73c5a22010-12-22 10:22:50 -08001243 if (mMenuState == EMPTY_MENU) {
1244 return false;
1245 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001246 MenuInflater inflater = mActivity.getMenuInflater();
1247 inflater.inflate(R.menu.browser, menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001248 return true;
1249 }
1250
1251 protected void onCreateContextMenu(ContextMenu menu, View v,
1252 ContextMenuInfo menuInfo) {
John Reck0f602f32011-07-07 15:38:43 -07001253 if (v instanceof TitleBar) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001254 return;
1255 }
1256 if (!(v instanceof WebView)) {
1257 return;
1258 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001259 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001260 WebView.HitTestResult result = webview.getHitTestResult();
1261 if (result == null) {
1262 return;
1263 }
1264
1265 int type = result.getType();
1266 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1267 Log.w(LOGTAG,
1268 "We should not show context menu when nothing is touched");
1269 return;
1270 }
1271 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1272 // let TextView handles context menu
1273 return;
1274 }
1275
1276 // Note, http://b/issue?id=1106666 is requesting that
1277 // an inflated menu can be used again. This is not available
1278 // yet, so inflate each time (yuk!)
1279 MenuInflater inflater = mActivity.getMenuInflater();
1280 inflater.inflate(R.menu.browsercontext, menu);
1281
1282 // Show the correct menu group
1283 final String extra = result.getExtra();
1284 menu.setGroupVisible(R.id.PHONE_MENU,
1285 type == WebView.HitTestResult.PHONE_TYPE);
1286 menu.setGroupVisible(R.id.EMAIL_MENU,
1287 type == WebView.HitTestResult.EMAIL_TYPE);
1288 menu.setGroupVisible(R.id.GEO_MENU,
1289 type == WebView.HitTestResult.GEO_TYPE);
1290 menu.setGroupVisible(R.id.IMAGE_MENU,
1291 type == WebView.HitTestResult.IMAGE_TYPE
1292 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1293 menu.setGroupVisible(R.id.ANCHOR_MENU,
1294 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1295 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001296 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1297 || type == WebView.HitTestResult.PHONE_TYPE
1298 || type == WebView.HitTestResult.EMAIL_TYPE
1299 || type == WebView.HitTestResult.GEO_TYPE;
1300 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1301 if (hitText) {
1302 menu.findItem(R.id.select_text_menu_id)
1303 .setOnMenuItemClickListener(new SelectText(webview));
1304 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001305 // Setup custom handling depending on the type
1306 switch (type) {
1307 case WebView.HitTestResult.PHONE_TYPE:
1308 menu.setHeaderTitle(Uri.decode(extra));
1309 menu.findItem(R.id.dial_context_menu_id).setIntent(
1310 new Intent(Intent.ACTION_VIEW, Uri
1311 .parse(WebView.SCHEME_TEL + extra)));
1312 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1313 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1314 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1315 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1316 addIntent);
1317 menu.findItem(R.id.copy_phone_context_menu_id)
1318 .setOnMenuItemClickListener(
1319 new Copy(extra));
1320 break;
1321
1322 case WebView.HitTestResult.EMAIL_TYPE:
1323 menu.setHeaderTitle(extra);
1324 menu.findItem(R.id.email_context_menu_id).setIntent(
1325 new Intent(Intent.ACTION_VIEW, Uri
1326 .parse(WebView.SCHEME_MAILTO + extra)));
1327 menu.findItem(R.id.copy_mail_context_menu_id)
1328 .setOnMenuItemClickListener(
1329 new Copy(extra));
1330 break;
1331
1332 case WebView.HitTestResult.GEO_TYPE:
1333 menu.setHeaderTitle(extra);
1334 menu.findItem(R.id.map_context_menu_id).setIntent(
1335 new Intent(Intent.ACTION_VIEW, Uri
1336 .parse(WebView.SCHEME_GEO
1337 + URLEncoder.encode(extra))));
1338 menu.findItem(R.id.copy_geo_context_menu_id)
1339 .setOnMenuItemClickListener(
1340 new Copy(extra));
1341 break;
1342
1343 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1344 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001345 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001346 // decide whether to show the open link in new tab option
1347 boolean showNewTab = mTabControl.canCreateNewTab();
1348 MenuItem newTabItem
1349 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001350 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001351 ? R.string.contextmenu_openlink_newwindow_background
1352 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001353 newTabItem.setVisible(showNewTab);
1354 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001355 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1356 newTabItem.setOnMenuItemClickListener(
1357 new MenuItem.OnMenuItemClickListener() {
1358 @Override
1359 public boolean onMenuItemClick(MenuItem item) {
1360 final HashMap<String, WebView> hrefMap =
1361 new HashMap<String, WebView>();
1362 hrefMap.put("webview", webview);
1363 final Message msg = mHandler.obtainMessage(
1364 FOCUS_NODE_HREF,
1365 R.id.open_newtab_context_menu_id,
1366 0, hrefMap);
1367 webview.requestFocusNodeHref(msg);
1368 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001369 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001370 });
1371 } else {
1372 newTabItem.setOnMenuItemClickListener(
1373 new MenuItem.OnMenuItemClickListener() {
1374 @Override
1375 public boolean onMenuItemClick(MenuItem item) {
1376 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001377 openTab(extra, parent,
1378 !mSettings.openInBackground(),
1379 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001380 return true;
1381 }
1382 });
1383 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001384 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001385 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1386 break;
1387 }
1388 // otherwise fall through to handle image part
1389 case WebView.HitTestResult.IMAGE_TYPE:
1390 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1391 menu.setHeaderTitle(extra);
1392 }
1393 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1394 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1395 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001396 setOnMenuItemClickListener(
1397 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001398 menu.findItem(R.id.set_wallpaper_context_menu_id).
1399 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1400 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001401 break;
1402
1403 default:
1404 Log.w(LOGTAG, "We should not get here.");
1405 break;
1406 }
1407 //update the ui
1408 mUi.onContextMenuCreated(menu);
1409 }
1410
1411 /**
1412 * As the menu can be open when loading state changes
1413 * we must manually update the state of the stop/reload menu
1414 * item
1415 */
1416 private void updateInLoadMenuItems(Menu menu) {
1417 if (menu == null) {
1418 return;
1419 }
1420 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1421 MenuItem src = mInLoad ?
1422 menu.findItem(R.id.stop_menu_id):
1423 menu.findItem(R.id.reload_menu_id);
1424 if (src != null) {
1425 dest.setIcon(src.getIcon());
1426 dest.setTitle(src.getTitle());
1427 }
1428 }
1429
John Reckb3417f02011-01-14 11:01:05 -08001430 boolean onPrepareOptionsMenu(Menu menu) {
John Recke1a03a32011-09-14 17:04:16 -07001431 updateInLoadMenuItems(menu);
1432 // hold on to the menu reference here; it is used by the page callbacks
1433 // to update the menu based on loading state
1434 mCachedMenu = menu;
Michael Kolb8233fac2010-10-26 16:08:53 -07001435 // Note: setVisible will decide whether an item is visible; while
1436 // setEnabled() will decide whether an item is enabled, which also means
1437 // whether the matching shortcut key will function.
1438 switch (mMenuState) {
1439 case EMPTY_MENU:
1440 if (mCurrentMenuState != mMenuState) {
1441 menu.setGroupVisible(R.id.MAIN_MENU, false);
1442 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1443 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1444 }
1445 break;
1446 default:
1447 if (mCurrentMenuState != mMenuState) {
1448 menu.setGroupVisible(R.id.MAIN_MENU, true);
1449 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1450 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1451 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001452 updateMenuState(getCurrentTab(), menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001453 break;
1454 }
1455 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001456 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001457 }
1458
Michael Kolb4bf79712011-07-14 14:18:12 -07001459 @Override
1460 public void updateMenuState(Tab tab, Menu menu) {
1461 boolean canGoBack = false;
1462 boolean canGoForward = false;
1463 boolean isHome = false;
John Reck42229bc2011-08-19 13:26:43 -07001464 boolean isDesktopUa = false;
John Recke1a03a32011-09-14 17:04:16 -07001465 boolean isLive = false;
Michael Kolb4bf79712011-07-14 14:18:12 -07001466 if (tab != null) {
1467 canGoBack = tab.canGoBack();
1468 canGoForward = tab.canGoForward();
1469 isHome = mSettings.getHomePage().equals(tab.getUrl());
John Reck42229bc2011-08-19 13:26:43 -07001470 isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
John Recke1a03a32011-09-14 17:04:16 -07001471 isLive = !tab.isSnapshot();
Michael Kolb4bf79712011-07-14 14:18:12 -07001472 }
1473 final MenuItem back = menu.findItem(R.id.back_menu_id);
1474 back.setEnabled(canGoBack);
1475
1476 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1477 home.setEnabled(!isHome);
1478
1479 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1480 forward.setEnabled(canGoForward);
1481
1482 final MenuItem source = menu.findItem(mInLoad ? R.id.stop_menu_id : R.id.reload_menu_id);
1483 final MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolb7ab75ee2011-07-14 16:36:38 -07001484 if (source != null && dest != null) {
1485 dest.setTitle(source.getTitle());
1486 dest.setIcon(source.getIcon());
1487 }
John Recke1a03a32011-09-14 17:04:16 -07001488 menu.setGroupVisible(R.id.NAV_MENU, isLive);
Michael Kolb4bf79712011-07-14 14:18:12 -07001489
1490 // decide whether to show the share link option
1491 PackageManager pm = mActivity.getPackageManager();
1492 Intent send = new Intent(Intent.ACTION_SEND);
1493 send.setType("text/plain");
1494 ResolveInfo ri = pm.resolveActivity(send,
1495 PackageManager.MATCH_DEFAULT_ONLY);
1496 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1497
1498 boolean isNavDump = mSettings.enableNavDump();
1499 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1500 nav.setVisible(isNavDump);
1501 nav.setEnabled(isNavDump);
1502
1503 boolean showDebugSettings = mSettings.isDebugEnabled();
1504 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1505 counter.setVisible(showDebugSettings);
1506 counter.setEnabled(showDebugSettings);
John Reck42229bc2011-08-19 13:26:43 -07001507 final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
1508 uaSwitcher.setChecked(isDesktopUa);
John Recke1a03a32011-09-14 17:04:16 -07001509 menu.setGroupVisible(R.id.LIVE_MENU, isLive);
1510 menu.setGroupVisible(R.id.SNAPSHOT_MENU, !isLive);
Michael Kolb4bf79712011-07-14 14:18:12 -07001511
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001512 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001513 }
1514
Michael Kolb8233fac2010-10-26 16:08:53 -07001515 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001516 if (null == getCurrentTopWebView()) {
1517 return false;
1518 }
1519 if (mMenuIsDown) {
1520 // The shortcut action consumes the MENU. Even if it is still down,
1521 // it won't trigger the next shortcut action. In the case of the
1522 // shortcut action triggering a new activity, like Bookmarks, we
1523 // won't get onKeyUp for MENU. So it is important to reset it here.
1524 mMenuIsDown = false;
1525 }
Michael Kolb3ca12752011-07-20 13:52:25 -07001526 if (mUi.onOptionsItemSelected(item)) {
1527 // ui callback handled it
1528 return true;
1529 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001530 switch (item.getItemId()) {
1531 // -- Main menu
1532 case R.id.new_tab_menu_id:
1533 openTabToHomePage();
1534 break;
1535
1536 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001537 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001538 break;
1539
1540 case R.id.goto_menu_id:
1541 editUrl();
1542 break;
1543
1544 case R.id.bookmarks_menu_id:
1545 bookmarksOrHistoryPicker(false);
1546 break;
1547
Michael Kolb8233fac2010-10-26 16:08:53 -07001548 case R.id.add_bookmark_menu_id:
John Recka60fffa2011-09-06 16:30:29 -07001549 Intent bookmarkIntent = createBookmarkCurrentPageIntent(false);
1550 if (bookmarkIntent != null) {
1551 mActivity.startActivity(bookmarkIntent);
1552 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001553 break;
1554
1555 case R.id.stop_reload_menu_id:
1556 if (mInLoad) {
1557 stopLoading();
1558 } else {
1559 getCurrentTopWebView().reload();
1560 }
1561 break;
1562
1563 case R.id.back_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001564 getCurrentTab().goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07001565 break;
1566
1567 case R.id.forward_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001568 getCurrentTab().goForward();
Michael Kolb8233fac2010-10-26 16:08:53 -07001569 break;
1570
1571 case R.id.close_menu_id:
1572 // Close the subwindow if it exists.
1573 if (mTabControl.getCurrentSubWindow() != null) {
1574 dismissSubWindow(mTabControl.getCurrentTab());
1575 break;
1576 }
1577 closeCurrentTab();
1578 break;
1579
1580 case R.id.homepage_menu_id:
1581 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07001582 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07001583 break;
1584
1585 case R.id.preferences_menu_id:
1586 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1587 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1588 getCurrentTopWebView().getUrl());
1589 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1590 break;
1591
1592 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001593 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001594 break;
1595
John Reck2bc80422011-06-30 15:11:49 -07001596 case R.id.save_snapshot_menu_id:
1597 final Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07001598 if (source == null) break;
John Reckd8c74522011-06-14 08:45:00 -07001599 final ContentResolver cr = mActivity.getContentResolver();
1600 final ContentValues values = source.createSnapshotValues();
John Reck2bc80422011-06-30 15:11:49 -07001601 if (values != null) {
1602 new AsyncTask<Tab, Void, Long>() {
John Reckd8c74522011-06-14 08:45:00 -07001603
John Reck2bc80422011-06-30 15:11:49 -07001604 @Override
1605 protected Long doInBackground(Tab... params) {
1606 Uri result = cr.insert(Snapshots.CONTENT_URI, values);
1607 long id = ContentUris.parseId(result);
1608 return id;
John Reckd8c74522011-06-14 08:45:00 -07001609 }
John Reckf33b1632011-06-04 20:00:23 -07001610
John Reck2bc80422011-06-30 15:11:49 -07001611 @Override
1612 protected void onPostExecute(Long id) {
1613 Bundle b = new Bundle();
1614 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
1615 mUi.showComboView(ComboViews.Snapshots, b);
1616 };
1617 }.execute(source);
1618 } else {
1619 Toast.makeText(mActivity, R.string.snapshot_failed,
Leon Scrogginsac993842011-02-02 12:54:07 -05001620 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001621 }
Leon Scrogginsac993842011-02-02 12:54:07 -05001622 break;
1623
Michael Kolb8233fac2010-10-26 16:08:53 -07001624 case R.id.page_info_menu_id:
Huahui Wuae0c0412011-06-28 10:17:05 -07001625 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001626 break;
1627
John Recke1a03a32011-09-14 17:04:16 -07001628 case R.id.snapshot_go_live:
1629 goLive();
1630 return true;
1631
Michael Kolb8233fac2010-10-26 16:08:53 -07001632 case R.id.classic_history_menu_id:
1633 bookmarksOrHistoryPicker(true);
1634 break;
1635
Michael Kolb8233fac2010-10-26 16:08:53 -07001636 case R.id.share_page_menu_id:
1637 Tab currentTab = mTabControl.getCurrentTab();
1638 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001639 return false;
1640 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001641 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001642 break;
1643
1644 case R.id.dump_nav_menu_id:
1645 getCurrentTopWebView().debugDump();
1646 break;
1647
1648 case R.id.dump_counters_menu_id:
1649 getCurrentTopWebView().dumpV8Counters();
1650 break;
1651
1652 case R.id.zoom_in_menu_id:
1653 getCurrentTopWebView().zoomIn();
1654 break;
1655
1656 case R.id.zoom_out_menu_id:
1657 getCurrentTopWebView().zoomOut();
1658 break;
1659
1660 case R.id.view_downloads_menu_id:
1661 viewDownloads();
1662 break;
1663
John Reck42229bc2011-08-19 13:26:43 -07001664 case R.id.ua_desktop_menu_id:
1665 WebView web = getCurrentWebView();
1666 mSettings.toggleDesktopUseragent(web);
1667 web.loadUrl(web.getOriginalUrl());
1668 break;
1669
Michael Kolb8233fac2010-10-26 16:08:53 -07001670 case R.id.window_one_menu_id:
1671 case R.id.window_two_menu_id:
1672 case R.id.window_three_menu_id:
1673 case R.id.window_four_menu_id:
1674 case R.id.window_five_menu_id:
1675 case R.id.window_six_menu_id:
1676 case R.id.window_seven_menu_id:
1677 case R.id.window_eight_menu_id:
1678 {
1679 int menuid = item.getItemId();
1680 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1681 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1682 Tab desiredTab = mTabControl.getTab(id);
1683 if (desiredTab != null &&
1684 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001685 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001686 }
1687 break;
1688 }
1689 }
1690 }
1691 break;
1692
1693 default:
1694 return false;
1695 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001696 return true;
1697 }
1698
John Recke1a03a32011-09-14 17:04:16 -07001699 private void goLive() {
1700 Tab t = getCurrentTab();
1701 t.loadUrl(t.getUrl(), null);
1702 }
1703
Michael Kolb8233fac2010-10-26 16:08:53 -07001704 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001705 // Let the History and Bookmark fragments handle menus they created.
1706 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1707 return false;
1708 }
1709
Michael Kolb8233fac2010-10-26 16:08:53 -07001710 int id = item.getItemId();
1711 boolean result = true;
1712 switch (id) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001713 // -- Browser context menu
1714 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001715 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001716 case R.id.copy_link_context_menu_id:
1717 final WebView webView = getCurrentTopWebView();
1718 if (null == webView) {
1719 result = false;
1720 break;
1721 }
1722 final HashMap<String, WebView> hrefMap =
1723 new HashMap<String, WebView>();
1724 hrefMap.put("webview", webView);
1725 final Message msg = mHandler.obtainMessage(
1726 FOCUS_NODE_HREF, id, 0, hrefMap);
1727 webView.requestFocusNodeHref(msg);
1728 break;
1729
1730 default:
1731 // For other context menus
1732 result = onOptionsItemSelected(item);
1733 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001734 return result;
1735 }
1736
1737 /**
1738 * support programmatically opening the context menu
1739 */
1740 public void openContextMenu(View view) {
1741 mActivity.openContextMenu(view);
1742 }
1743
1744 /**
1745 * programmatically open the options menu
1746 */
1747 public void openOptionsMenu() {
1748 mActivity.openOptionsMenu();
1749 }
1750
1751 public boolean onMenuOpened(int featureId, Menu menu) {
1752 if (mOptionsMenuOpen) {
1753 if (mConfigChanged) {
1754 // We do not need to make any changes to the state of the
1755 // title bar, since the only thing that happened was a
1756 // change in orientation
1757 mConfigChanged = false;
1758 } else {
1759 if (!mExtendedMenuOpen) {
1760 mExtendedMenuOpen = true;
1761 mUi.onExtendedMenuOpened();
1762 } else {
1763 // Switching the menu back to icon view, so show the
1764 // title bar once again.
1765 mExtendedMenuOpen = false;
1766 mUi.onExtendedMenuClosed(mInLoad);
Michael Kolb8233fac2010-10-26 16:08:53 -07001767 }
1768 }
1769 } else {
1770 // The options menu is closed, so open it, and show the title
1771 mOptionsMenuOpen = true;
1772 mConfigChanged = false;
1773 mExtendedMenuOpen = false;
1774 mUi.onOptionsMenuOpened();
1775 }
1776 return true;
1777 }
1778
1779 public void onOptionsMenuClosed(Menu menu) {
1780 mOptionsMenuOpen = false;
1781 mUi.onOptionsMenuClosed(mInLoad);
1782 }
1783
1784 public void onContextMenuClosed(Menu menu) {
1785 mUi.onContextMenuClosed(menu, mInLoad);
1786 }
1787
1788 // Helper method for getting the top window.
1789 @Override
1790 public WebView getCurrentTopWebView() {
1791 return mTabControl.getCurrentTopWebView();
1792 }
1793
1794 @Override
1795 public WebView getCurrentWebView() {
1796 return mTabControl.getCurrentWebView();
1797 }
1798
1799 /*
1800 * This method is called as a result of the user selecting the options
1801 * menu to see the download window. It shows the download window on top of
1802 * the current window.
1803 */
1804 void viewDownloads() {
1805 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1806 mActivity.startActivity(intent);
1807 }
1808
John Reck30b065e2011-07-19 10:58:05 -07001809 int getActionModeHeight() {
1810 TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
1811 new int[] { android.R.attr.actionBarSize });
1812 int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
1813 actionBarSizeTypedArray.recycle();
1814 return size;
1815 }
1816
Michael Kolb8233fac2010-10-26 16:08:53 -07001817 // action mode
1818
1819 void onActionModeStarted(ActionMode mode) {
1820 mUi.onActionModeStarted(mode);
1821 mActionMode = mode;
Michael Kolb42c0c062011-08-02 12:56:06 -07001822 if (mSimulateActionBarOverlayMode && !mUi.isEditingUrl()) {
John Reck30b065e2011-07-19 10:58:05 -07001823 WebView web = getCurrentWebView();
1824 // Simulate overlay mode by scrolling the webview the amount it will be
1825 // pushed down. Actual overlay mode doesn't work for us as otherwise
1826 // the CAB will, well, overlay the content, which breaks things like
1827 // find on page.
1828 int scrollBy = getActionModeHeight();
1829 web.scrollBy(0, scrollBy);
1830 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001831 }
1832
1833 /*
1834 * True if a custom ActionMode (i.e. find or select) is in use.
1835 */
1836 @Override
1837 public boolean isInCustomActionMode() {
1838 return mActionMode != null;
1839 }
1840
1841 /*
1842 * End the current ActionMode.
1843 */
1844 @Override
1845 public void endActionMode() {
1846 if (mActionMode != null) {
1847 mActionMode.finish();
1848 }
1849 }
1850
1851 /*
1852 * Called by find and select when they are finished. Replace title bars
1853 * as necessary.
1854 */
1855 public void onActionModeFinished(ActionMode mode) {
1856 if (!isInCustomActionMode()) return;
1857 mUi.onActionModeFinished(mInLoad);
1858 mActionMode = null;
John Reck30b065e2011-07-19 10:58:05 -07001859 if (mSimulateActionBarOverlayMode) {
1860 WebView web = getCurrentWebView();
1861 int scrollBy = getActionModeHeight();
1862 web.scrollBy(0, -scrollBy);
1863 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001864 }
1865
1866 boolean isInLoad() {
1867 return mInLoad;
1868 }
1869
1870 // bookmark handling
1871
1872 /**
1873 * add the current page as a bookmark to the given folder id
1874 * @param folderId use -1 for the default folder
John Reckd3e4d5b2011-07-13 15:48:43 -07001875 * @param editExisting If true, check to see whether the site is already
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001876 * bookmarked, and if it is, edit that bookmark. If false, and
1877 * the site is already bookmarked, do not attempt to edit the
1878 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001879 */
1880 @Override
John Reckd3e4d5b2011-07-13 15:48:43 -07001881 public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
John Recka60fffa2011-09-06 16:30:29 -07001882 WebView w = getCurrentTopWebView();
1883 if (w == null) {
1884 return null;
1885 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001886 Intent i = new Intent(mActivity,
1887 AddBookmarkPage.class);
Michael Kolb8233fac2010-10-26 16:08:53 -07001888 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1889 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1890 String touchIconUrl = w.getTouchIconUrl();
1891 if (touchIconUrl != null) {
1892 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1893 WebSettings settings = w.getSettings();
1894 if (settings != null) {
1895 i.putExtra(AddBookmarkPage.USER_AGENT,
1896 settings.getUserAgentString());
1897 }
1898 }
1899 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1900 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1901 getDesiredThumbnailHeight(mActivity)));
1902 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07001903 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001904 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1905 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001906 // Put the dialog at the upper right of the screen, covering the
1907 // star on the title bar.
1908 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07001909 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07001910 }
1911
1912 // file chooser
1913 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1914 mUploadHandler = new UploadHandler(this);
1915 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1916 }
1917
1918 // thumbnails
1919
1920 /**
1921 * Return the desired width for thumbnail screenshots, which are stored in
1922 * the database, and used on the bookmarks screen.
1923 * @param context Context for finding out the density of the screen.
1924 * @return desired width for thumbnail screenshot.
1925 */
1926 static int getDesiredThumbnailWidth(Context context) {
1927 return context.getResources().getDimensionPixelOffset(
1928 R.dimen.bookmarkThumbnailWidth);
1929 }
1930
1931 /**
1932 * Return the desired height for thumbnail screenshots, which are stored in
1933 * the database, and used on the bookmarks screen.
1934 * @param context Context for finding out the density of the screen.
1935 * @return desired height for thumbnail screenshot.
1936 */
1937 static int getDesiredThumbnailHeight(Context context) {
1938 return context.getResources().getDimensionPixelOffset(
1939 R.dimen.bookmarkThumbnailHeight);
1940 }
1941
John Reck8cc92352011-07-06 17:41:52 -07001942 static Bitmap createScreenshot(WebView view, int width, int height) {
John Reckd7dd9b22011-08-30 09:18:29 -07001943 if (view == null || view.getContentHeight() == 0
1944 || view.getContentWidth() == 0) {
1945 return null;
1946 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001947 // We render to a bitmap 2x the desired size so that we can then
1948 // re-scale it with filtering since canvas.scale doesn't filter
1949 // This helps reduce aliasing at the cost of being slightly blurry
1950 final int filter_scale = 2;
John Reckd7dd9b22011-08-30 09:18:29 -07001951 int scaledWidth = width * filter_scale;
1952 int scaledHeight = height * filter_scale;
1953 if (sThumbnailBitmap == null || sThumbnailBitmap.getWidth() != scaledWidth
1954 || sThumbnailBitmap.getHeight() != scaledHeight) {
1955 if (sThumbnailBitmap != null) {
1956 sThumbnailBitmap.recycle();
1957 sThumbnailBitmap = null;
1958 }
1959 sThumbnailBitmap =
1960 Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.RGB_565);
Michael Kolb8233fac2010-10-26 16:08:53 -07001961 }
John Reckd7dd9b22011-08-30 09:18:29 -07001962 Canvas canvas = new Canvas(sThumbnailBitmap);
1963 int contentWidth = view.getContentWidth();
1964 float overviewScale = scaledWidth / (view.getScale() * contentWidth);
1965 if (view instanceof BrowserWebView) {
1966 int dy = -((BrowserWebView)view).getTitleHeight();
1967 canvas.translate(0, dy * overviewScale);
1968 }
1969
1970 canvas.scale(overviewScale, overviewScale);
1971
1972 if (view instanceof BrowserWebView) {
1973 ((BrowserWebView)view).drawContent(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07001974 } else {
John Reckd7dd9b22011-08-30 09:18:29 -07001975 view.draw(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07001976 }
John Reckd7dd9b22011-08-30 09:18:29 -07001977 Bitmap ret = Bitmap.createScaledBitmap(sThumbnailBitmap,
1978 width, height, true);
Dianne Hackborn43cfe8a2011-08-02 16:59:35 -07001979 canvas.setBitmap(null);
John Reck5c6ac2f2011-01-05 10:18:03 -08001980 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001981 }
1982
John Reck34ef2672011-02-10 11:30:55 -08001983 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001984 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07001985 // FIXME: Would like to make sure there is actually something to
1986 // draw, but the API for that (WebViewCore.pictureReady()) is not
1987 // currently accessible here.
1988
John Reck34ef2672011-02-10 11:30:55 -08001989 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08001990 if (view == null) {
1991 // Tab was destroyed
1992 return;
1993 }
John Reck34ef2672011-02-10 11:30:55 -08001994 final String url = tab.getUrl();
1995 final String originalUrl = view.getOriginalUrl();
1996
1997 if (TextUtils.isEmpty(url)) {
1998 return;
1999 }
2000
2001 // Only update thumbnails for web urls (http(s)://), not for
2002 // about:, javascript:, data:, etc...
2003 // Unless it is a bookmarked site, then always update
2004 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2005 return;
2006 }
2007
Michael Kolb8233fac2010-10-26 16:08:53 -07002008 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2009 getDesiredThumbnailHeight(mActivity));
2010 if (bm == null) {
2011 return;
2012 }
2013
2014 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002015 new AsyncTask<Void, Void, Void>() {
2016 @Override
2017 protected Void doInBackground(Void... unused) {
2018 Cursor cursor = null;
2019 try {
2020 // TODO: Clean this up
2021 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2022 if (cursor != null && cursor.moveToFirst()) {
2023 final ByteArrayOutputStream os =
2024 new ByteArrayOutputStream();
2025 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002026
John Reck34ef2672011-02-10 11:30:55 -08002027 ContentValues values = new ContentValues();
2028 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002029
John Reck34ef2672011-02-10 11:30:55 -08002030 do {
John Reck617fd832011-02-16 14:35:59 -08002031 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002032 cr.update(Images.CONTENT_URI, values, null, null);
2033 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002034 }
John Reck34ef2672011-02-10 11:30:55 -08002035 } catch (IllegalStateException e) {
2036 // Ignore
2037 } finally {
2038 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002039 }
John Reck34ef2672011-02-10 11:30:55 -08002040 return null;
2041 }
2042 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002043 }
2044
2045 private class Copy implements OnMenuItemClickListener {
2046 private CharSequence mText;
2047
2048 public boolean onMenuItemClick(MenuItem item) {
2049 copy(mText);
2050 return true;
2051 }
2052
2053 public Copy(CharSequence toCopy) {
2054 mText = toCopy;
2055 }
2056 }
2057
Leon Scroggins63c02662010-11-18 15:16:27 -05002058 private static class Download implements OnMenuItemClickListener {
2059 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002060 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002061 private boolean mPrivateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002062
2063 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002064 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002065 null, null, mPrivateBrowsing);
Michael Kolb8233fac2010-10-26 16:08:53 -07002066 return true;
2067 }
2068
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002069 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002070 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002071 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002072 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002073 }
2074 }
2075
Cary Clark8974d282010-11-22 10:46:05 -05002076 private static class SelectText implements OnMenuItemClickListener {
2077 private WebView mWebView;
2078
2079 public boolean onMenuItemClick(MenuItem item) {
2080 if (mWebView != null) {
2081 return mWebView.selectText();
2082 }
2083 return false;
2084 }
2085
2086 public SelectText(WebView webView) {
2087 mWebView = webView;
2088 }
2089
2090 }
2091
Michael Kolb8233fac2010-10-26 16:08:53 -07002092 /********************** TODO: UI stuff *****************************/
2093
2094 // these methods have been copied, they still need to be cleaned up
2095
2096 /****************** tabs ***************************************************/
2097
2098 // basic tab interactions:
2099
2100 // it is assumed that tabcontrol already knows about the tab
2101 protected void addTab(Tab tab) {
2102 mUi.addTab(tab);
2103 }
2104
2105 protected void removeTab(Tab tab) {
2106 mUi.removeTab(tab);
2107 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002108 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002109 }
2110
Michael Kolbf2055602011-04-09 17:20:03 -07002111 @Override
2112 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002113 // monkey protection against delayed start
2114 if (tab != null) {
2115 mTabControl.setCurrentTab(tab);
2116 // the tab is guaranteed to have a webview after setCurrentTab
2117 mUi.setActiveTab(tab);
2118 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002119 }
2120
John Reck8bcafc12011-08-29 16:43:02 -07002121 protected void closeEmptyTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002122 Tab current = mTabControl.getCurrentTab();
2123 if (current != null
2124 && current.getWebView().copyBackForwardList().getSize() == 0) {
John Reck8bcafc12011-08-29 16:43:02 -07002125 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002126 }
2127 }
2128
John Reck26b18322011-06-21 13:08:58 -07002129 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002130 // Dismiss the subwindow if applicable.
2131 dismissSubWindow(appTab);
2132 // Since we might kill the WebView, remove it from the
2133 // content view first.
2134 mUi.detachTab(appTab);
2135 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002136 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002137 // TODO: analyze why the remove and add are necessary
2138 mUi.attachTab(appTab);
2139 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002140 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002141 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002142 } else {
2143 // If the tab was the current tab, we have to attach
2144 // it to the view system again.
2145 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002146 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002147 }
2148 }
2149
2150 // Remove the sub window if it exists. Also called by TabControl when the
2151 // user clicks the 'X' to dismiss a sub window.
2152 public void dismissSubWindow(Tab tab) {
2153 removeSubWindow(tab);
2154 // dismiss the subwindow. This will destroy the WebView.
2155 tab.dismissSubWindow();
2156 getCurrentTopWebView().requestFocus();
2157 }
2158
2159 @Override
2160 public void removeSubWindow(Tab t) {
2161 if (t.getSubWebView() != null) {
2162 mUi.removeSubWindow(t.getSubViewContainer());
2163 }
2164 }
2165
2166 @Override
2167 public void attachSubWindow(Tab tab) {
2168 if (tab.getSubWebView() != null) {
2169 mUi.attachSubWindow(tab.getSubViewContainer());
2170 getCurrentTopWebView().requestFocus();
2171 }
2172 }
2173
Mathew Inwood29721c22011-06-29 17:55:24 +01002174 private Tab showPreloadedTab(final UrlData urlData) {
2175 if (!urlData.isPreloaded()) {
2176 return null;
2177 }
2178 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2179 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2180 if (sbQuery != null) {
Mathew Inwood9ad1eac2011-09-15 11:29:50 +01002181 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002182 // Could not submit query. Fallback to regular tab creation
2183 tabControl.destroy();
2184 return null;
2185 }
2186 }
Michael Kolbff6a7482011-07-26 16:37:15 -07002187 // check tab count and make room for new tab
2188 if (!mTabControl.canCreateNewTab()) {
2189 Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
2190 if (leastUsed != null) {
2191 closeTab(leastUsed);
2192 }
2193 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002194 Tab t = tabControl.getTab();
Mathew Inwoode09305e2011-09-02 12:03:26 +01002195 t.refreshIdAfterPreload();
Mathew Inwood29721c22011-06-29 17:55:24 +01002196 mTabControl.addPreloadedTab(t);
2197 addTab(t);
2198 setActiveTab(t);
2199 return t;
2200 }
2201
Michael Kolb7bcafde2011-05-09 13:55:59 -07002202 // open a non inconito tab with the given url data
2203 // and set as active tab
2204 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002205 Tab tab = showPreloadedTab(urlData);
2206 if (tab == null) {
2207 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002208 if ((tab != null) && !urlData.isEmpty()) {
2209 loadUrlDataIn(tab, urlData);
2210 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002211 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002212 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002213 }
2214
Michael Kolb843510f2010-12-09 10:51:49 -08002215 @Override
2216 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002217 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002218 }
2219
Michael Kolb8233fac2010-10-26 16:08:53 -07002220 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002221 public Tab openIncognitoTab() {
2222 return openTab(INCOGNITO_URI, true, true, false);
2223 }
2224
2225 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002226 public Tab openTab(String url, boolean incognito, boolean setActive,
2227 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002228 return openTab(url, incognito, setActive, useCurrent, null);
2229 }
2230
2231 @Override
2232 public Tab openTab(String url, Tab parent, boolean setActive,
2233 boolean useCurrent) {
2234 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2235 setActive, useCurrent, parent);
2236 }
2237
2238 public Tab openTab(String url, boolean incognito, boolean setActive,
2239 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002240 Tab tab = createNewTab(incognito, setActive, useCurrent);
2241 if (tab != null) {
John Reck5949c662011-05-27 09:52:29 -07002242 if (parent != null && parent != tab) {
2243 parent.addChildTab(tab);
2244 }
Michael Kolb519d2282011-05-09 17:03:19 -07002245 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002246 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002247 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002248 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002249 return tab;
2250 }
2251
2252 // this method will attempt to create a new tab
2253 // incognito: private browsing tab
2254 // setActive: ste tab as current tab
2255 // useCurrent: if no new tab can be created, return current tab
2256 private Tab createNewTab(boolean incognito, boolean setActive,
2257 boolean useCurrent) {
2258 Tab tab = null;
2259 if (mTabControl.canCreateNewTab()) {
2260 tab = mTabControl.createNewTab(incognito);
2261 addTab(tab);
2262 if (setActive) {
2263 setActiveTab(tab);
2264 }
2265 } else {
2266 if (useCurrent) {
2267 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002268 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002269 } else {
2270 mUi.showMaxTabsWarning();
2271 }
2272 }
2273 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002274 }
2275
John Reck2bc80422011-06-30 15:11:49 -07002276 @Override
2277 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2278 SnapshotTab tab = null;
2279 if (mTabControl.canCreateNewTab()) {
2280 tab = mTabControl.createSnapshotTab(snapshotId);
2281 addTab(tab);
2282 if (setActive) {
2283 setActiveTab(tab);
2284 }
2285 } else {
2286 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07002287 }
2288 return tab;
2289 }
2290
Michael Kolb8233fac2010-10-26 16:08:53 -07002291 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002292 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002293 * @return boolean True if we successfully switched to a different tab. If
2294 * the indexth tab is null, or if that tab is the same as
2295 * the current one, return false.
2296 */
2297 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002298 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002299 Tab currentTab = mTabControl.getCurrentTab();
2300 if (tab == null || tab == currentTab) {
2301 return false;
2302 }
2303 setActiveTab(tab);
2304 return true;
2305 }
2306
2307 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002308 public void closeCurrentTab() {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002309 closeCurrentTab(false);
2310 }
2311
2312 protected void closeCurrentTab(boolean andQuit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002313 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07002314 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07002315 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08002316 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002317 return;
2318 }
Michael Kolbc831b632011-05-11 09:30:34 -07002319 final Tab current = mTabControl.getCurrentTab();
2320 final int pos = mTabControl.getCurrentPosition();
2321 Tab newTab = current.getParent();
2322 if (newTab == null) {
2323 newTab = mTabControl.getTab(pos + 1);
2324 if (newTab == null) {
2325 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002326 }
2327 }
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002328 if (andQuit) {
2329 mTabControl.setCurrentTab(newTab);
2330 closeTab(current);
2331 } else if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002332 // Close window
2333 closeTab(current);
2334 }
2335 }
2336
2337 /**
2338 * Close the tab, remove its associated title bar, and adjust mTabControl's
2339 * current tab to a valid value.
2340 */
2341 @Override
2342 public void closeTab(Tab tab) {
Michael Kolb2d59c322011-01-25 13:18:55 -08002343 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002344 }
2345
Michael Kolb8233fac2010-10-26 16:08:53 -07002346 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07002347 protected void loadUrlFromContext(String url) {
2348 Tab tab = getCurrentTab();
2349 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002350 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07002351 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002352 url = UrlUtils.smartUrlFilter(url);
2353 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07002354 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07002355 }
2356 }
2357 }
2358
2359 /**
2360 * Load the URL into the given WebView and update the title bar
2361 * to reflect the new load. Call this instead of WebView.loadUrl
2362 * directly.
2363 * @param view The WebView used to load url.
2364 * @param url The URL to load.
2365 */
John Reck71e51422011-07-01 16:49:28 -07002366 @Override
2367 public void loadUrl(Tab tab, String url) {
John Reck26b18322011-06-21 13:08:58 -07002368 loadUrl(tab, url, null);
2369 }
2370
2371 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
2372 if (tab != null) {
2373 dismissSubWindow(tab);
2374 tab.loadUrl(url, headers);
2375 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002376 }
2377
2378 /**
2379 * Load UrlData into a Tab and update the title bar to reflect the new
2380 * load. Call this instead of UrlData.loadIn directly.
2381 * @param t The Tab used to load.
2382 * @param data The UrlData being loaded.
2383 */
2384 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07002385 if (data != null) {
2386 if (data.mVoiceIntent != null) {
2387 t.activateVoiceSearchMode(data.mVoiceIntent);
Michael Kolb14612442011-06-24 13:06:29 -07002388 } else if (data.isPreloaded()) {
2389 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07002390 } else {
2391 loadUrl(t, data.mUrl, data.mHeaders);
2392 }
2393 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002394 }
2395
John Reck30c714c2010-12-16 17:30:34 -08002396 @Override
2397 public void onUserCanceledSsl(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08002398 // TODO: Figure out the "right" behavior
John Reckef654f12011-07-12 16:42:08 -07002399 if (tab.canGoBack()) {
2400 tab.goBack();
John Reck30c714c2010-12-16 17:30:34 -08002401 } else {
John Reckef654f12011-07-12 16:42:08 -07002402 tab.loadUrl(mSettings.getHomePage(), null);
John Reck30c714c2010-12-16 17:30:34 -08002403 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002404 }
2405
2406 void goBackOnePageOrQuit() {
2407 Tab current = mTabControl.getCurrentTab();
2408 if (current == null) {
2409 /*
2410 * Instead of finishing the activity, simply push this to the back
2411 * of the stack and let ActivityManager to choose the foreground
2412 * activity. As BrowserActivity is singleTask, it will be always the
2413 * root of the task. So we can use either true or false for
2414 * moveTaskToBack().
2415 */
2416 mActivity.moveTaskToBack(true);
2417 return;
2418 }
John Reckef654f12011-07-12 16:42:08 -07002419 if (current.canGoBack()) {
2420 current.goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07002421 } else {
2422 // Check to see if we are closing a window that was created by
2423 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002424 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002425 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002426 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002427 // Now we close the other tab
2428 closeTab(current);
2429 } else {
Michael Kolbe28b3472011-08-04 16:54:31 -07002430 if ((current.getAppId() != null) || current.closeOnBack()) {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002431 closeCurrentTab(true);
Michael Kolbe28b3472011-08-04 16:54:31 -07002432 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002433 /*
2434 * Instead of finishing the activity, simply push this to the back
2435 * of the stack and let ActivityManager to choose the foreground
2436 * activity. As BrowserActivity is singleTask, it will be always the
2437 * root of the task. So we can use either true or false for
2438 * moveTaskToBack().
2439 */
2440 mActivity.moveTaskToBack(true);
2441 }
2442 }
2443 }
2444
2445 /**
2446 * Feed the previously stored results strings to the BrowserProvider so that
2447 * the SearchDialog will show them instead of the standard searches.
2448 * @param result String to show on the editable line of the SearchDialog.
2449 */
2450 @Override
2451 public void showVoiceSearchResults(String result) {
2452 ContentProviderClient client = mActivity.getContentResolver()
2453 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2454 ContentProvider prov = client.getLocalContentProvider();
2455 BrowserProvider bp = (BrowserProvider) prov;
2456 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2457 client.release();
2458
2459 Bundle bundle = createGoogleSearchSourceBundle(
2460 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2461 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2462 startSearch(result, false, bundle, false);
2463 }
2464
2465 private void startSearch(String initialQuery, boolean selectInitialQuery,
2466 Bundle appSearchData, boolean globalSearch) {
2467 if (appSearchData == null) {
2468 appSearchData = createGoogleSearchSourceBundle(
2469 GOOGLE_SEARCH_SOURCE_TYPE);
2470 }
2471
2472 SearchEngine searchEngine = mSettings.getSearchEngine();
2473 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2474 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2475 }
2476 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2477 globalSearch);
2478 }
2479
2480 private Bundle createGoogleSearchSourceBundle(String source) {
2481 Bundle bundle = new Bundle();
2482 bundle.putString(Search.SOURCE, source);
2483 return bundle;
2484 }
2485
2486 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002487 * helper method for key handler
2488 * returns the current tab if it can't advance
2489 */
Michael Kolbc831b632011-05-11 09:30:34 -07002490 private Tab getNextTab() {
2491 return mTabControl.getTab(Math.min(mTabControl.getTabCount() - 1,
2492 mTabControl.getCurrentPosition() + 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002493 }
2494
2495 /**
2496 * helper method for key handler
2497 * returns the current tab if it can't advance
2498 */
Michael Kolbc831b632011-05-11 09:30:34 -07002499 private Tab getPrevTab() {
2500 return mTabControl.getTab(Math.max(0,
2501 mTabControl.getCurrentPosition() - 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002502 }
2503
2504 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002505 * handle key events in browser
2506 *
2507 * @param keyCode
2508 * @param event
2509 * @return true if handled, false to pass to super
2510 */
2511 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002512 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002513 // Even if MENU is already held down, we need to call to super to open
2514 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002515 if (!noModifiers
2516 && ((KeyEvent.KEYCODE_MENU == keyCode)
2517 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2518 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002519 mMenuIsDown = true;
2520 return false;
2521 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002522
Cary Clark8ff8c662010-12-29 15:03:05 -05002523 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07002524 Tab tab = getCurrentTab();
2525 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05002526
Cary Clark160bbb92011-01-10 11:17:07 -05002527 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2528 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002529
Michael Kolb8233fac2010-10-26 16:08:53 -07002530 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002531 case KeyEvent.KEYCODE_TAB:
2532 if (event.isCtrlPressed()) {
2533 if (event.isShiftPressed()) {
2534 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002535 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002536 } else {
2537 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002538 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002539 }
2540 return true;
2541 }
2542 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002543 case KeyEvent.KEYCODE_SPACE:
2544 // WebView/WebTextView handle the keys in the KeyDown. As
2545 // the Activity's shortcut keys are only handled when WebView
2546 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002547 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002548 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002549 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002550 pageDown();
2551 }
2552 return true;
2553 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002554 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002555 event.startTracking();
2556 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07002557 case KeyEvent.KEYCODE_FORWARD:
2558 if (!noModifiers) break;
2559 tab.goForward();
2560 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002561 case KeyEvent.KEYCODE_DPAD_LEFT:
2562 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002563 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05002564 return true;
2565 }
2566 break;
2567 case KeyEvent.KEYCODE_DPAD_RIGHT:
2568 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002569 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05002570 return true;
2571 }
2572 break;
2573 case KeyEvent.KEYCODE_A:
2574 if (ctrl) {
2575 webView.selectAll();
2576 return true;
2577 }
2578 break;
Michael Kolba4183062011-01-16 10:43:21 -08002579// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002580 case KeyEvent.KEYCODE_C:
2581 if (ctrl) {
2582 webView.copySelection();
2583 return true;
2584 }
2585 break;
Michael Kolba4183062011-01-16 10:43:21 -08002586// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002587// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002588// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002589// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002590// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002591// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002592// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002593// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002594// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002595// case KeyEvent.KEYCODE_M: // unused
2596// case KeyEvent.KEYCODE_N: // in Chrome: new window
2597// case KeyEvent.KEYCODE_O: // in Chrome: open file
2598// case KeyEvent.KEYCODE_P: // in Chrome: print page
2599// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002600// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002601// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2602 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002603 // we can't use the ctrl/shift flags, they check for
2604 // exclusive use of a modifier
2605 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002606 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002607 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002608 } else {
2609 openTabToHomePage();
2610 }
2611 return true;
2612 }
2613 break;
2614// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2615// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb5ae15bd2011-08-16 17:09:27 -07002616// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002617// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2618// case KeyEvent.KEYCODE_Y: // unused
2619// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002620 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002621 // it is a regular key and webview is not null
2622 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002623 }
2624
John Recke6bf4ab2011-02-24 15:48:05 -08002625 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2626 switch(keyCode) {
2627 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07002628 if (mUi.isWebShowing()) {
John Recke6bf4ab2011-02-24 15:48:05 -08002629 bookmarksOrHistoryPicker(true);
2630 return true;
2631 }
2632 break;
2633 }
2634 return false;
2635 }
2636
Michael Kolb8233fac2010-10-26 16:08:53 -07002637 boolean onKeyUp(int keyCode, KeyEvent event) {
Michael Kolb2814a362011-05-19 15:49:41 -07002638 if (KeyEvent.KEYCODE_MENU == keyCode) {
2639 mMenuIsDown = false;
2640 if (event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002641 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002642 }
2643 }
Cary Clark160bbb92011-01-10 11:17:07 -05002644 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002645 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002646 case KeyEvent.KEYCODE_BACK:
2647 if (event.isTracking() && !event.isCanceled()) {
2648 onBackKey();
2649 return true;
2650 }
2651 break;
2652 }
2653 return false;
2654 }
2655
2656 public boolean isMenuDown() {
2657 return mMenuIsDown;
2658 }
2659
Ben Murdoch8029a772010-11-16 11:58:21 +00002660 public void setupAutoFill(Message message) {
2661 // Open the settings activity at the AutoFill profile fragment so that
2662 // the user can create a new profile. When they return, we will dispatch
2663 // the message so that we can autofill the form using their new profile.
2664 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2665 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2666 AutoFillSettingsFragment.class.getName());
2667 mAutoFillSetupMessage = message;
2668 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2669 }
John Reckb3417f02011-01-14 11:01:05 -08002670
2671 @Override
Narayan Kamath5119edd2011-02-23 15:49:17 +00002672 public void registerDropdownChangeListener(DropdownChangeListener d) {
2673 mUi.registerDropdownChangeListener(d);
2674 }
Michael Kolbfbc579a2011-07-07 15:59:33 -07002675
2676 public boolean onSearchRequested() {
2677 mUi.editUrl(false);
2678 return true;
2679 }
2680
John Reck1cf4b792011-07-26 10:22:22 -07002681 @Override
2682 public boolean shouldCaptureThumbnails() {
2683 return mUi.shouldCaptureThumbnails();
2684 }
2685
Michael Kolbc3af0672011-08-09 10:24:41 -07002686 @Override
2687 public void setBlockEvents(boolean block) {
2688 mBlockEvents = block;
2689 }
2690
2691 public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002692 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002693 }
2694
2695 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002696 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002697 }
2698
2699 public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002700 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002701 }
2702
2703 public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002704 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002705 }
2706
2707 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002708 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002709 }
2710
Michael Kolb8233fac2010-10-26 16:08:53 -07002711}