blob: 282d4f2ef557439c44e9475914026af468f83214 [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
Michael Kolbc3af0672011-08-09 10:24:41 -0700214 private boolean mBlockEvents;
215
John Reckbc490d22011-07-22 15:04:59 -0700216 public Controller(Activity browser, boolean preloadCrashState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700217 mActivity = browser;
218 mSettings = BrowserSettings.getInstance();
219 mTabControl = new TabControl(this);
220 mSettings.setController(this);
John Reck378a4102011-06-09 16:23:01 -0700221 mCrashRecoveryHandler = CrashRecoveryHandler.initialize(this);
John Reckbc490d22011-07-22 15:04:59 -0700222 if (preloadCrashState) {
223 mCrashRecoveryHandler.preloadCrashState();
224 }
Michael Kolb14612442011-06-24 13:06:29 -0700225 mFactory = new BrowserWebViewFactory(browser);
Michael Kolb8233fac2010-10-26 16:08:53 -0700226
227 mUrlHandler = new UrlHandler(this);
228 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700229 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
230
Michael Kolb8233fac2010-10-26 16:08:53 -0700231 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500232 mBookmarksObserver = new ContentObserver(mHandler) {
233 @Override
234 public void onChange(boolean selfChange) {
235 int size = mTabControl.getTabCount();
236 for (int i = 0; i < size; i++) {
237 mTabControl.getTab(i).updateBookmarkedStatus();
238 }
239 }
240
241 };
242 browser.getContentResolver().registerContentObserver(
243 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700244
245 mNetworkHandler = new NetworkStateHandler(mActivity, this);
246 // Start watching the default geolocation permissions
247 mSystemAllowGeolocationOrigins =
248 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
249 mSystemAllowGeolocationOrigins.start();
250
John Reckaf262e72011-07-25 13:55:44 -0700251 openIconDatabase();
Michael Kolb8233fac2010-10-26 16:08:53 -0700252 }
253
Patrick Scott7d50a932011-02-04 09:27:26 -0500254 void start(final Bundle icicle, final Intent intent) {
Guang Zhu9e78f512011-05-04 11:45:11 -0700255 boolean noCrashRecovery = intent.getBooleanExtra(NO_CRASH_RECOVERY, false);
256 if (icicle != null || noCrashRecovery) {
John Reck847b5322011-04-14 17:02:18 -0700257 doStart(icicle, intent);
258 } else {
259 mCrashRecoveryHandler.startRecovery(intent);
260 }
261 }
262
263 void doStart(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700264 // Unless the last browser usage was within 24 hours, destroy any
265 // remaining incognito tabs.
266
267 Calendar lastActiveDate = icicle != null ?
268 (Calendar) icicle.getSerializable("lastActiveDate") : null;
269 Calendar today = Calendar.getInstance();
270 Calendar yesterday = Calendar.getInstance();
271 yesterday.add(Calendar.DATE, -1);
272
Patrick Scott7d50a932011-02-04 09:27:26 -0500273 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700274 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800275 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700276
Patrick Scott7d50a932011-02-04 09:27:26 -0500277 // Find out if we will restore any state and remember the tab.
Michael Kolbc831b632011-05-11 09:30:34 -0700278 final long currentTabId =
Patrick Scott7d50a932011-02-04 09:27:26 -0500279 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000280
Michael Kolbc831b632011-05-11 09:30:34 -0700281 if (currentTabId == -1) {
Patrick Scott7d50a932011-02-04 09:27:26 -0500282 // Not able to restore so we go ahead and clear session cookies. We
283 // must do this before trying to login the user as we don't want to
284 // clear any session cookies set during login.
285 CookieManager.getInstance().removeSessionCookie();
286 }
287
Patrick Scottd43e75a2011-03-14 14:47:23 -0400288 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500289 new Runnable() {
290 @Override public void run() {
Michael Kolbc831b632011-05-11 09:30:34 -0700291 onPreloginFinished(icicle, intent, currentTabId, restoreIncognitoTabs);
Patrick Scott7d50a932011-02-04 09:27:26 -0500292 }
293 });
294 }
295
Michael Kolbc831b632011-05-11 09:30:34 -0700296 private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId,
Patrick Scott7d50a932011-02-04 09:27:26 -0500297 boolean restoreIncognitoTabs) {
Michael Kolbc831b632011-05-11 09:30:34 -0700298 if (currentTabId == -1) {
John Reck1cf4b792011-07-26 10:22:22 -0700299 BackgroundHandler.execute(new PruneThumbnails(mActivity, null));
Michael Kolb8233fac2010-10-26 16:08:53 -0700300 final Bundle extra = intent.getExtras();
301 // Create an initial tab.
302 // If the intent is ACTION_VIEW and data is not null, the Browser is
303 // invoked to view the content by another application. In this case,
304 // the tab will be close when exit.
Michael Kolb14612442011-06-24 13:06:29 -0700305 UrlData urlData = IntentHandler.getUrlDataFromIntent(intent);
Michael Kolb7bcafde2011-05-09 13:55:59 -0700306 Tab t = null;
307 if (urlData.isEmpty()) {
308 t = openTabToHomePage();
309 } else {
310 t = openTab(urlData);
311 }
312 if (t != null) {
313 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
314 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700315 WebView webView = t.getWebView();
316 if (extra != null) {
317 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
318 if (scale > 0 && scale <= 1000) {
319 webView.setInitialScale(scale);
320 }
321 }
John Reckd8c74522011-06-14 08:45:00 -0700322 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700323 } else {
Michael Kolbc831b632011-05-11 09:30:34 -0700324 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
Patrick Scott7d50a932011-02-04 09:27:26 -0500325 mUi.needsRestoreAllTabs());
John Reck1cf4b792011-07-26 10:22:22 -0700326 List<Tab> tabs = mTabControl.getTabs();
327 ArrayList<Long> restoredTabs = new ArrayList<Long>(tabs.size());
328 for (Tab t : tabs) {
329 restoredTabs.add(t.getId());
330 }
331 BackgroundHandler.execute(new PruneThumbnails(mActivity, restoredTabs));
John Reck52be4782011-08-26 15:37:29 -0700332 if (tabs.size() == 0) {
333 openTabToHomePage();
334 }
John Reck1cf4b792011-07-26 10:22:22 -0700335 mUi.updateTabs(tabs);
Michael Kolb8233fac2010-10-26 16:08:53 -0700336 // TabControl.restoreState() will create a new tab even if
337 // restoring the state fails.
338 setActiveTab(mTabControl.getCurrentTab());
John Reck9dd4a412011-10-05 14:55:30 -0700339 // Handle the intent if needed. If icicle != null, we are restoring
340 // and the intent will be stale - ignore it.
341 if (icicle == null) {
342 mIntentHandler.onNewIntent(intent);
343 }
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;
Michael Kolb8233fac2010-10-26 16:08:53 -0700806 endActionMode();
807
John Reck30c714c2010-12-16 17:30:34 -0800808 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700809
John Reck324d4402011-01-11 16:56:42 -0800810 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700811 // update the bookmark database for favicon
812 maybeUpdateFavicon(tab, null, url, favicon);
813
814 Performance.tracePageStart(url);
815
816 // Performance probe
817 if (false) {
818 Performance.onPageStarted();
819 }
820
821 }
822
823 @Override
John Reck324d4402011-01-11 16:56:42 -0800824 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800825 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800826 if (!tab.isPrivateBrowsingEnabled()
John Reckd8c74522011-06-14 08:45:00 -0700827 && !TextUtils.isEmpty(tab.getUrl())
828 && !tab.isSnapshot()) {
John Recka1696282011-07-08 14:10:37 -0700829 // Only update the bookmark screenshot if the user did not
830 // cancel the load early and there is not already
831 // a pending update for the tab.
Michael Kolb8233fac2010-10-26 16:08:53 -0700832 if (tab.inForeground() && !didUserStopLoading()
833 || !tab.inForeground()) {
John Recka1696282011-07-08 14:10:37 -0700834 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
835 mHandler.sendMessageDelayed(mHandler.obtainMessage(
836 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
837 500);
838 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700839 }
840 }
841 // pause the WebView timer and release the wake lock if it is finished
842 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800843 if (mActivityPaused && pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700844 releaseWakeLock();
Michael Kolb8233fac2010-10-26 16:08:53 -0700845 }
Martijn Coenenb2f93552011-06-14 10:48:35 +0200846
Michael Kolb8233fac2010-10-26 16:08:53 -0700847 // Performance probe
848 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800849 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700850 }
851
852 Performance.tracePageFinished();
853 }
854
855 @Override
John Reck30c714c2010-12-16 17:30:34 -0800856 public void onProgressChanged(Tab tab) {
John Reck6c2e2f32011-08-22 13:41:23 -0700857 mCrashRecoveryHandler.backupState();
John Reck30c714c2010-12-16 17:30:34 -0800858 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700859
860 if (newProgress == 100) {
861 CookieSyncManager.getInstance().sync();
862 // onProgressChanged() may continue to be called after the main
863 // frame has finished loading, as any remaining sub frames continue
864 // to load. We'll only get called once though with newProgress as
865 // 100 when everything is loaded. (onPageFinished is called once
866 // when the main frame completes loading regardless of the state of
867 // any sub frames so calls to onProgressChanges may continue after
868 // onPageFinished has executed)
869 if (mInLoad) {
870 mInLoad = false;
871 updateInLoadMenuItems(mCachedMenu);
872 }
873 } else {
874 if (!mInLoad) {
875 // onPageFinished may have already been called but a subframe is
876 // still loading and updating the progress. Reset mInLoad and
877 // update the menu items.
878 mInLoad = true;
879 updateInLoadMenuItems(mCachedMenu);
880 }
881 }
John Reck30c714c2010-12-16 17:30:34 -0800882 mUi.onProgressChanged(tab);
883 }
884
885 @Override
Steve Block2466eff2011-10-03 15:33:09 +0100886 public void onUpdatedSecurityState(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800887 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700888 }
889
890 @Override
891 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800892 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800893 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800894 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700895 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
896 return;
897 }
898 // Update the title in the history database if not in private browsing mode
899 if (!tab.isPrivateBrowsingEnabled()) {
John Reckf57c0292011-07-21 18:15:39 -0700900 DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700901 }
902 }
903
904 @Override
905 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800906 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700907 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
908 }
909
910 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800911 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
912 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700913 }
914
915 @Override
916 public boolean shouldOverrideKeyEvent(KeyEvent event) {
917 if (mMenuIsDown) {
918 // only check shortcut key when MENU is held
919 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
920 event);
921 } else {
922 return false;
923 }
924 }
925
926 @Override
927 public void onUnhandledKeyEvent(KeyEvent event) {
928 if (!isActivityPaused()) {
929 if (event.getAction() == KeyEvent.ACTION_DOWN) {
930 mActivity.onKeyDown(event.getKeyCode(), event);
931 } else {
932 mActivity.onKeyUp(event.getKeyCode(), event);
933 }
934 }
935 }
936
937 @Override
John Reck324d4402011-01-11 16:56:42 -0800938 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700939 // Don't save anything in private browsing mode
940 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800941 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700942
John Reck324d4402011-01-11 16:56:42 -0800943 if (TextUtils.isEmpty(url)
944 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700945 return;
946 }
John Reckf57c0292011-07-21 18:15:39 -0700947 DataController.getInstance(mActivity).updateVisitedHistory(url);
John Reck6c2e2f32011-08-22 13:41:23 -0700948 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -0700949 }
950
951 @Override
952 public void getVisitedHistory(final ValueCallback<String[]> callback) {
953 AsyncTask<Void, Void, String[]> task =
954 new AsyncTask<Void, Void, String[]>() {
955 @Override
956 public String[] doInBackground(Void... unused) {
957 return Browser.getVisitedHistory(mActivity.getContentResolver());
958 }
959 @Override
960 public void onPostExecute(String[] result) {
961 callback.onReceiveValue(result);
962 }
963 };
964 task.execute();
965 }
966
967 @Override
968 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
969 final HttpAuthHandler handler, final String host,
970 final String realm) {
971 String username = null;
972 String password = null;
973
974 boolean reuseHttpAuthUsernamePassword
975 = handler.useHttpAuthUsernamePassword();
976
977 if (reuseHttpAuthUsernamePassword && view != null) {
978 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
979 if (credentials != null && credentials.length == 2) {
980 username = credentials[0];
981 password = credentials[1];
982 }
983 }
984
985 if (username != null && password != null) {
986 handler.proceed(username, password);
987 } else {
Ben Murdochfdd37112011-08-05 15:48:14 +0100988 if (tab.inForeground() && !handler.suppressDialog()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700989 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
990 } else {
991 handler.cancel();
992 }
993 }
994 }
995
996 @Override
997 public void onDownloadStart(Tab tab, String url, String userAgent,
998 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000999 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -05001000 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001001 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
1002 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001003 // This Tab was opened for the sole purpose of downloading a
1004 // file. Remove it.
1005 if (tab == mTabControl.getCurrentTab()) {
1006 // In this case, the Tab is still on top.
1007 goBackOnePageOrQuit();
1008 } else {
1009 // In this case, it is not.
1010 closeTab(tab);
1011 }
1012 }
1013 }
1014
1015 @Override
1016 public Bitmap getDefaultVideoPoster() {
1017 return mUi.getDefaultVideoPoster();
1018 }
1019
1020 @Override
1021 public View getVideoLoadingProgressView() {
1022 return mUi.getVideoLoadingProgressView();
1023 }
1024
1025 @Override
1026 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1027 SslError error) {
1028 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1029 }
1030
Patrick Scott92066772011-03-10 08:46:27 -05001031 @Override
1032 public void showAutoLogin(Tab tab) {
1033 assert tab.inForeground();
1034 // Update the title bar to show the auto-login request.
1035 mUi.showAutoLogin(tab);
1036 }
1037
1038 @Override
1039 public void hideAutoLogin(Tab tab) {
1040 assert tab.inForeground();
1041 mUi.hideAutoLogin(tab);
1042 }
1043
Michael Kolb8233fac2010-10-26 16:08:53 -07001044 // helper method
1045
1046 /*
1047 * Update the favorites icon if the private browsing isn't enabled and the
1048 * icon is valid.
1049 */
1050 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1051 final String url, Bitmap favicon) {
1052 if (favicon == null) {
1053 return;
1054 }
1055 if (!tab.isPrivateBrowsingEnabled()) {
1056 Bookmarks.updateFavicon(mActivity
1057 .getContentResolver(), originalUrl, url, favicon);
1058 }
1059 }
1060
Leon Scroggins4cd97792010-12-03 15:31:56 -05001061 @Override
1062 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001063 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001064 mUi.bookmarkedStatusHasChanged(tab);
1065 }
1066
Michael Kolb8233fac2010-10-26 16:08:53 -07001067 // end WebViewController
1068
1069 protected void pageUp() {
1070 getCurrentTopWebView().pageUp(false);
1071 }
1072
1073 protected void pageDown() {
1074 getCurrentTopWebView().pageDown(false);
1075 }
1076
1077 // callback from phone title bar
1078 public void editUrl() {
1079 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001080 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001081 }
1082
Michael Kolbcfa3af52010-12-14 10:36:11 -08001083 public void startVoiceSearch() {
1084 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1085 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1086 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1087 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1088 mActivity.getComponentName().flattenToString());
1089 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001090 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001091 mActivity.startActivity(intent);
1092 }
1093
Michael Kolb11d19782011-03-20 10:17:40 -07001094 @Override
1095 public void activateVoiceSearchMode(String title, List<String> results) {
1096 mUi.showVoiceTitleBar(title, results);
Michael Kolb8233fac2010-10-26 16:08:53 -07001097 }
1098
1099 public void revertVoiceSearchMode(Tab tab) {
1100 mUi.revertVoiceTitleBar(tab);
1101 }
1102
Michael Kolb736990c2011-03-20 10:01:20 -07001103 public boolean supportsVoiceSearch() {
John Reck35e9dd62011-04-25 09:01:54 -07001104 SearchEngine searchEngine = getSettings().getSearchEngine();
Michael Kolb736990c2011-03-20 10:01:20 -07001105 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1106 }
1107
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001108 public void showCustomView(Tab tab, View view, int requestedOrientation,
Michael Kolb8233fac2010-10-26 16:08:53 -07001109 WebChromeClient.CustomViewCallback callback) {
1110 if (tab.inForeground()) {
1111 if (mUi.isCustomViewShowing()) {
1112 callback.onCustomViewHidden();
1113 return;
1114 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001115 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001116 // Save the menu state and set it to empty while the custom
1117 // view is showing.
1118 mOldMenuState = mMenuState;
1119 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001120 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001121 }
1122 }
1123
1124 @Override
1125 public void hideCustomView() {
1126 if (mUi.isCustomViewShowing()) {
1127 mUi.onHideCustomView();
1128 // Reset the old menu state.
1129 mMenuState = mOldMenuState;
1130 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001131 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001132 }
1133 }
1134
1135 protected void onActivityResult(int requestCode, int resultCode,
1136 Intent intent) {
1137 if (getCurrentTopWebView() == null) return;
1138 switch (requestCode) {
1139 case PREFERENCES_PAGE:
1140 if (resultCode == Activity.RESULT_OK && intent != null) {
1141 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001142 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001143 mTabControl.removeParentChildRelationShips();
1144 }
1145 }
1146 break;
1147 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001148 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001149 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001150 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001151 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001152 case AUTOFILL_SETUP:
1153 // Determine whether a profile was actually set up or not
1154 // and if so, send the message back to the WebTextView to
1155 // fill the form with the new profile.
1156 if (getSettings().getAutoFillProfile() != null) {
1157 mAutoFillSetupMessage.sendToTarget();
1158 mAutoFillSetupMessage = null;
1159 }
1160 break;
John Reckd3e4d5b2011-07-13 15:48:43 -07001161 case COMBO_VIEW:
1162 if (intent == null || resultCode != Activity.RESULT_OK) {
1163 break;
1164 }
John Reck3ba45532011-08-11 16:26:53 -07001165 mUi.showWeb(false);
John Reckd3e4d5b2011-07-13 15:48:43 -07001166 if (Intent.ACTION_VIEW.equals(intent.getAction())) {
1167 Tab t = getCurrentTab();
1168 Uri uri = intent.getData();
1169 loadUrl(t, uri.toString());
1170 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
1171 String[] urls = intent.getStringArrayExtra(
1172 ComboViewActivity.EXTRA_OPEN_ALL);
1173 Tab parent = getCurrentTab();
1174 for (String url : urls) {
1175 parent = openTab(url, parent,
1176 !mSettings.openInBackground(), true);
1177 }
1178 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
1179 long id = intent.getLongExtra(
1180 ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
1181 if (id >= 0) {
1182 createNewSnapshotTab(id, true);
1183 }
1184 }
1185 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001186 default:
1187 break;
1188 }
1189 getCurrentTopWebView().requestFocus();
1190 }
1191
1192 /**
1193 * Open the Go page.
1194 * @param startWithHistory If true, open starting on the history tab.
1195 * Otherwise, start with the bookmarks tab.
1196 */
1197 @Override
1198 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1199 if (mTabControl.getCurrentWebView() == null) {
1200 return;
1201 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001202 // clear action mode
1203 if (isInCustomActionMode()) {
1204 endActionMode();
1205 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001206 Bundle extras = new Bundle();
1207 // Disable opening in a new window if we have maxed out the windows
1208 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1209 !mTabControl.canCreateNewTab());
John Reck2bc80422011-06-30 15:11:49 -07001210 mUi.showComboView(startWithHistory
1211 ? ComboViews.History : ComboViews.Bookmarks, extras);
Michael Kolb8233fac2010-10-26 16:08:53 -07001212 }
1213
1214 // combo view callbacks
1215
Michael Kolb8233fac2010-10-26 16:08:53 -07001216 // key handling
1217 protected void onBackKey() {
1218 if (!mUi.onBackKey()) {
1219 WebView subwindow = mTabControl.getCurrentSubWindow();
1220 if (subwindow != null) {
1221 if (subwindow.canGoBack()) {
1222 subwindow.goBack();
1223 } else {
1224 dismissSubWindow(mTabControl.getCurrentTab());
1225 }
1226 } else {
1227 goBackOnePageOrQuit();
1228 }
1229 }
1230 }
1231
Michael Kolb4bd767d2011-05-27 11:33:55 -07001232 protected boolean onMenuKey() {
1233 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001234 }
1235
Michael Kolb8233fac2010-10-26 16:08:53 -07001236 // menu handling and state
1237 // TODO: maybe put into separate handler
1238
1239 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckd73c5a22010-12-22 10:22:50 -08001240 if (mMenuState == EMPTY_MENU) {
1241 return false;
1242 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001243 MenuInflater inflater = mActivity.getMenuInflater();
1244 inflater.inflate(R.menu.browser, menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001245 return true;
1246 }
1247
1248 protected void onCreateContextMenu(ContextMenu menu, View v,
1249 ContextMenuInfo menuInfo) {
John Reck0f602f32011-07-07 15:38:43 -07001250 if (v instanceof TitleBar) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001251 return;
1252 }
1253 if (!(v instanceof WebView)) {
1254 return;
1255 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001256 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001257 WebView.HitTestResult result = webview.getHitTestResult();
1258 if (result == null) {
1259 return;
1260 }
1261
1262 int type = result.getType();
1263 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1264 Log.w(LOGTAG,
1265 "We should not show context menu when nothing is touched");
1266 return;
1267 }
1268 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1269 // let TextView handles context menu
1270 return;
1271 }
1272
1273 // Note, http://b/issue?id=1106666 is requesting that
1274 // an inflated menu can be used again. This is not available
1275 // yet, so inflate each time (yuk!)
1276 MenuInflater inflater = mActivity.getMenuInflater();
1277 inflater.inflate(R.menu.browsercontext, menu);
1278
1279 // Show the correct menu group
1280 final String extra = result.getExtra();
1281 menu.setGroupVisible(R.id.PHONE_MENU,
1282 type == WebView.HitTestResult.PHONE_TYPE);
1283 menu.setGroupVisible(R.id.EMAIL_MENU,
1284 type == WebView.HitTestResult.EMAIL_TYPE);
1285 menu.setGroupVisible(R.id.GEO_MENU,
1286 type == WebView.HitTestResult.GEO_TYPE);
1287 menu.setGroupVisible(R.id.IMAGE_MENU,
1288 type == WebView.HitTestResult.IMAGE_TYPE
1289 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1290 menu.setGroupVisible(R.id.ANCHOR_MENU,
1291 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1292 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001293 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1294 || type == WebView.HitTestResult.PHONE_TYPE
1295 || type == WebView.HitTestResult.EMAIL_TYPE
1296 || type == WebView.HitTestResult.GEO_TYPE;
1297 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1298 if (hitText) {
1299 menu.findItem(R.id.select_text_menu_id)
1300 .setOnMenuItemClickListener(new SelectText(webview));
1301 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001302 // Setup custom handling depending on the type
1303 switch (type) {
1304 case WebView.HitTestResult.PHONE_TYPE:
1305 menu.setHeaderTitle(Uri.decode(extra));
1306 menu.findItem(R.id.dial_context_menu_id).setIntent(
1307 new Intent(Intent.ACTION_VIEW, Uri
1308 .parse(WebView.SCHEME_TEL + extra)));
1309 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1310 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1311 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1312 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1313 addIntent);
1314 menu.findItem(R.id.copy_phone_context_menu_id)
1315 .setOnMenuItemClickListener(
1316 new Copy(extra));
1317 break;
1318
1319 case WebView.HitTestResult.EMAIL_TYPE:
1320 menu.setHeaderTitle(extra);
1321 menu.findItem(R.id.email_context_menu_id).setIntent(
1322 new Intent(Intent.ACTION_VIEW, Uri
1323 .parse(WebView.SCHEME_MAILTO + extra)));
1324 menu.findItem(R.id.copy_mail_context_menu_id)
1325 .setOnMenuItemClickListener(
1326 new Copy(extra));
1327 break;
1328
1329 case WebView.HitTestResult.GEO_TYPE:
1330 menu.setHeaderTitle(extra);
1331 menu.findItem(R.id.map_context_menu_id).setIntent(
1332 new Intent(Intent.ACTION_VIEW, Uri
1333 .parse(WebView.SCHEME_GEO
1334 + URLEncoder.encode(extra))));
1335 menu.findItem(R.id.copy_geo_context_menu_id)
1336 .setOnMenuItemClickListener(
1337 new Copy(extra));
1338 break;
1339
1340 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1341 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001342 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001343 // decide whether to show the open link in new tab option
1344 boolean showNewTab = mTabControl.canCreateNewTab();
1345 MenuItem newTabItem
1346 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001347 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001348 ? R.string.contextmenu_openlink_newwindow_background
1349 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001350 newTabItem.setVisible(showNewTab);
1351 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001352 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1353 newTabItem.setOnMenuItemClickListener(
1354 new MenuItem.OnMenuItemClickListener() {
1355 @Override
1356 public boolean onMenuItemClick(MenuItem item) {
1357 final HashMap<String, WebView> hrefMap =
1358 new HashMap<String, WebView>();
1359 hrefMap.put("webview", webview);
1360 final Message msg = mHandler.obtainMessage(
1361 FOCUS_NODE_HREF,
1362 R.id.open_newtab_context_menu_id,
1363 0, hrefMap);
1364 webview.requestFocusNodeHref(msg);
1365 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001366 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001367 });
1368 } else {
1369 newTabItem.setOnMenuItemClickListener(
1370 new MenuItem.OnMenuItemClickListener() {
1371 @Override
1372 public boolean onMenuItemClick(MenuItem item) {
1373 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001374 openTab(extra, parent,
1375 !mSettings.openInBackground(),
1376 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001377 return true;
1378 }
1379 });
1380 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001381 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001382 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1383 break;
1384 }
1385 // otherwise fall through to handle image part
1386 case WebView.HitTestResult.IMAGE_TYPE:
1387 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1388 menu.setHeaderTitle(extra);
1389 }
Michael Kolb3639c4c2011-09-28 15:36:40 -07001390 menu.findItem(R.id.view_image_context_menu_id)
1391 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1392 @Override
1393 public boolean onMenuItemClick(MenuItem item) {
1394 openTab(extra, mTabControl.getCurrentTab(), true, true);
1395 return false;
1396 }
1397 });
Michael Kolb8233fac2010-10-26 16:08:53 -07001398 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001399 setOnMenuItemClickListener(
1400 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001401 menu.findItem(R.id.set_wallpaper_context_menu_id).
1402 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1403 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001404 break;
1405
1406 default:
1407 Log.w(LOGTAG, "We should not get here.");
1408 break;
1409 }
1410 //update the ui
1411 mUi.onContextMenuCreated(menu);
1412 }
1413
1414 /**
1415 * As the menu can be open when loading state changes
1416 * we must manually update the state of the stop/reload menu
1417 * item
1418 */
1419 private void updateInLoadMenuItems(Menu menu) {
1420 if (menu == null) {
1421 return;
1422 }
1423 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1424 MenuItem src = mInLoad ?
1425 menu.findItem(R.id.stop_menu_id):
1426 menu.findItem(R.id.reload_menu_id);
1427 if (src != null) {
1428 dest.setIcon(src.getIcon());
1429 dest.setTitle(src.getTitle());
1430 }
1431 }
1432
John Reckb3417f02011-01-14 11:01:05 -08001433 boolean onPrepareOptionsMenu(Menu menu) {
John Recke1a03a32011-09-14 17:04:16 -07001434 updateInLoadMenuItems(menu);
1435 // hold on to the menu reference here; it is used by the page callbacks
1436 // to update the menu based on loading state
1437 mCachedMenu = menu;
Michael Kolb8233fac2010-10-26 16:08:53 -07001438 // Note: setVisible will decide whether an item is visible; while
1439 // setEnabled() will decide whether an item is enabled, which also means
1440 // whether the matching shortcut key will function.
1441 switch (mMenuState) {
1442 case EMPTY_MENU:
1443 if (mCurrentMenuState != mMenuState) {
1444 menu.setGroupVisible(R.id.MAIN_MENU, false);
1445 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1446 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1447 }
1448 break;
1449 default:
1450 if (mCurrentMenuState != mMenuState) {
1451 menu.setGroupVisible(R.id.MAIN_MENU, true);
1452 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1453 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1454 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001455 updateMenuState(getCurrentTab(), menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001456 break;
1457 }
1458 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001459 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001460 }
1461
Michael Kolb4bf79712011-07-14 14:18:12 -07001462 @Override
1463 public void updateMenuState(Tab tab, Menu menu) {
1464 boolean canGoBack = false;
1465 boolean canGoForward = false;
1466 boolean isHome = false;
John Reck42229bc2011-08-19 13:26:43 -07001467 boolean isDesktopUa = false;
John Recke1a03a32011-09-14 17:04:16 -07001468 boolean isLive = false;
Michael Kolb4bf79712011-07-14 14:18:12 -07001469 if (tab != null) {
1470 canGoBack = tab.canGoBack();
1471 canGoForward = tab.canGoForward();
1472 isHome = mSettings.getHomePage().equals(tab.getUrl());
John Reck42229bc2011-08-19 13:26:43 -07001473 isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
John Recke1a03a32011-09-14 17:04:16 -07001474 isLive = !tab.isSnapshot();
Michael Kolb4bf79712011-07-14 14:18:12 -07001475 }
1476 final MenuItem back = menu.findItem(R.id.back_menu_id);
1477 back.setEnabled(canGoBack);
1478
1479 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1480 home.setEnabled(!isHome);
1481
1482 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1483 forward.setEnabled(canGoForward);
1484
1485 final MenuItem source = menu.findItem(mInLoad ? R.id.stop_menu_id : R.id.reload_menu_id);
1486 final MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolb7ab75ee2011-07-14 16:36:38 -07001487 if (source != null && dest != null) {
1488 dest.setTitle(source.getTitle());
1489 dest.setIcon(source.getIcon());
1490 }
John Recke1a03a32011-09-14 17:04:16 -07001491 menu.setGroupVisible(R.id.NAV_MENU, isLive);
Michael Kolb4bf79712011-07-14 14:18:12 -07001492
1493 // decide whether to show the share link option
1494 PackageManager pm = mActivity.getPackageManager();
1495 Intent send = new Intent(Intent.ACTION_SEND);
1496 send.setType("text/plain");
1497 ResolveInfo ri = pm.resolveActivity(send,
1498 PackageManager.MATCH_DEFAULT_ONLY);
1499 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1500
1501 boolean isNavDump = mSettings.enableNavDump();
1502 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1503 nav.setVisible(isNavDump);
1504 nav.setEnabled(isNavDump);
1505
1506 boolean showDebugSettings = mSettings.isDebugEnabled();
1507 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1508 counter.setVisible(showDebugSettings);
1509 counter.setEnabled(showDebugSettings);
John Reck42229bc2011-08-19 13:26:43 -07001510 final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
1511 uaSwitcher.setChecked(isDesktopUa);
John Recke1a03a32011-09-14 17:04:16 -07001512 menu.setGroupVisible(R.id.LIVE_MENU, isLive);
1513 menu.setGroupVisible(R.id.SNAPSHOT_MENU, !isLive);
Michael Kolb4bf79712011-07-14 14:18:12 -07001514
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001515 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001516 }
1517
Michael Kolb8233fac2010-10-26 16:08:53 -07001518 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001519 if (null == getCurrentTopWebView()) {
1520 return false;
1521 }
1522 if (mMenuIsDown) {
1523 // The shortcut action consumes the MENU. Even if it is still down,
1524 // it won't trigger the next shortcut action. In the case of the
1525 // shortcut action triggering a new activity, like Bookmarks, we
1526 // won't get onKeyUp for MENU. So it is important to reset it here.
1527 mMenuIsDown = false;
1528 }
Michael Kolb3ca12752011-07-20 13:52:25 -07001529 if (mUi.onOptionsItemSelected(item)) {
1530 // ui callback handled it
1531 return true;
1532 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001533 switch (item.getItemId()) {
1534 // -- Main menu
1535 case R.id.new_tab_menu_id:
1536 openTabToHomePage();
1537 break;
1538
1539 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001540 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001541 break;
1542
1543 case R.id.goto_menu_id:
1544 editUrl();
1545 break;
1546
1547 case R.id.bookmarks_menu_id:
1548 bookmarksOrHistoryPicker(false);
1549 break;
1550
Michael Kolb8233fac2010-10-26 16:08:53 -07001551 case R.id.add_bookmark_menu_id:
John Recka60fffa2011-09-06 16:30:29 -07001552 Intent bookmarkIntent = createBookmarkCurrentPageIntent(false);
1553 if (bookmarkIntent != null) {
1554 mActivity.startActivity(bookmarkIntent);
1555 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001556 break;
1557
1558 case R.id.stop_reload_menu_id:
1559 if (mInLoad) {
1560 stopLoading();
1561 } else {
1562 getCurrentTopWebView().reload();
1563 }
1564 break;
1565
1566 case R.id.back_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001567 getCurrentTab().goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07001568 break;
1569
1570 case R.id.forward_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001571 getCurrentTab().goForward();
Michael Kolb8233fac2010-10-26 16:08:53 -07001572 break;
1573
1574 case R.id.close_menu_id:
1575 // Close the subwindow if it exists.
1576 if (mTabControl.getCurrentSubWindow() != null) {
1577 dismissSubWindow(mTabControl.getCurrentTab());
1578 break;
1579 }
1580 closeCurrentTab();
1581 break;
1582
1583 case R.id.homepage_menu_id:
1584 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07001585 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07001586 break;
1587
1588 case R.id.preferences_menu_id:
1589 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1590 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1591 getCurrentTopWebView().getUrl());
1592 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1593 break;
1594
1595 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001596 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001597 break;
1598
John Reck2bc80422011-06-30 15:11:49 -07001599 case R.id.save_snapshot_menu_id:
1600 final Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07001601 if (source == null) break;
John Reckd8c74522011-06-14 08:45:00 -07001602 final ContentResolver cr = mActivity.getContentResolver();
1603 final ContentValues values = source.createSnapshotValues();
John Reck2bc80422011-06-30 15:11:49 -07001604 if (values != null) {
1605 new AsyncTask<Tab, Void, Long>() {
John Reckd8c74522011-06-14 08:45:00 -07001606
John Reck2bc80422011-06-30 15:11:49 -07001607 @Override
1608 protected Long doInBackground(Tab... params) {
1609 Uri result = cr.insert(Snapshots.CONTENT_URI, values);
1610 long id = ContentUris.parseId(result);
1611 return id;
John Reckd8c74522011-06-14 08:45:00 -07001612 }
John Reckf33b1632011-06-04 20:00:23 -07001613
John Reck2bc80422011-06-30 15:11:49 -07001614 @Override
1615 protected void onPostExecute(Long id) {
1616 Bundle b = new Bundle();
1617 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
1618 mUi.showComboView(ComboViews.Snapshots, b);
1619 };
1620 }.execute(source);
1621 } else {
1622 Toast.makeText(mActivity, R.string.snapshot_failed,
Leon Scrogginsac993842011-02-02 12:54:07 -05001623 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001624 }
Leon Scrogginsac993842011-02-02 12:54:07 -05001625 break;
1626
Michael Kolb8233fac2010-10-26 16:08:53 -07001627 case R.id.page_info_menu_id:
Huahui Wuae0c0412011-06-28 10:17:05 -07001628 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001629 break;
1630
John Recke1a03a32011-09-14 17:04:16 -07001631 case R.id.snapshot_go_live:
1632 goLive();
1633 return true;
1634
Michael Kolb8233fac2010-10-26 16:08:53 -07001635 case R.id.classic_history_menu_id:
1636 bookmarksOrHistoryPicker(true);
1637 break;
1638
Michael Kolb8233fac2010-10-26 16:08:53 -07001639 case R.id.share_page_menu_id:
1640 Tab currentTab = mTabControl.getCurrentTab();
1641 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001642 return false;
1643 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001644 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001645 break;
1646
1647 case R.id.dump_nav_menu_id:
1648 getCurrentTopWebView().debugDump();
1649 break;
1650
1651 case R.id.dump_counters_menu_id:
1652 getCurrentTopWebView().dumpV8Counters();
1653 break;
1654
1655 case R.id.zoom_in_menu_id:
1656 getCurrentTopWebView().zoomIn();
1657 break;
1658
1659 case R.id.zoom_out_menu_id:
1660 getCurrentTopWebView().zoomOut();
1661 break;
1662
1663 case R.id.view_downloads_menu_id:
1664 viewDownloads();
1665 break;
1666
John Reck42229bc2011-08-19 13:26:43 -07001667 case R.id.ua_desktop_menu_id:
1668 WebView web = getCurrentWebView();
1669 mSettings.toggleDesktopUseragent(web);
1670 web.loadUrl(web.getOriginalUrl());
1671 break;
1672
Michael Kolb8233fac2010-10-26 16:08:53 -07001673 case R.id.window_one_menu_id:
1674 case R.id.window_two_menu_id:
1675 case R.id.window_three_menu_id:
1676 case R.id.window_four_menu_id:
1677 case R.id.window_five_menu_id:
1678 case R.id.window_six_menu_id:
1679 case R.id.window_seven_menu_id:
1680 case R.id.window_eight_menu_id:
1681 {
1682 int menuid = item.getItemId();
1683 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1684 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1685 Tab desiredTab = mTabControl.getTab(id);
1686 if (desiredTab != null &&
1687 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001688 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001689 }
1690 break;
1691 }
1692 }
1693 }
1694 break;
1695
1696 default:
1697 return false;
1698 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001699 return true;
1700 }
1701
John Recke1a03a32011-09-14 17:04:16 -07001702 private void goLive() {
1703 Tab t = getCurrentTab();
1704 t.loadUrl(t.getUrl(), null);
1705 }
1706
Michael Kolb8233fac2010-10-26 16:08:53 -07001707 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001708 // Let the History and Bookmark fragments handle menus they created.
1709 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1710 return false;
1711 }
1712
Michael Kolb8233fac2010-10-26 16:08:53 -07001713 int id = item.getItemId();
1714 boolean result = true;
1715 switch (id) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001716 // -- Browser context menu
1717 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001718 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001719 case R.id.copy_link_context_menu_id:
1720 final WebView webView = getCurrentTopWebView();
1721 if (null == webView) {
1722 result = false;
1723 break;
1724 }
1725 final HashMap<String, WebView> hrefMap =
1726 new HashMap<String, WebView>();
1727 hrefMap.put("webview", webView);
1728 final Message msg = mHandler.obtainMessage(
1729 FOCUS_NODE_HREF, id, 0, hrefMap);
1730 webView.requestFocusNodeHref(msg);
1731 break;
1732
1733 default:
1734 // For other context menus
1735 result = onOptionsItemSelected(item);
1736 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001737 return result;
1738 }
1739
1740 /**
1741 * support programmatically opening the context menu
1742 */
1743 public void openContextMenu(View view) {
1744 mActivity.openContextMenu(view);
1745 }
1746
1747 /**
1748 * programmatically open the options menu
1749 */
1750 public void openOptionsMenu() {
1751 mActivity.openOptionsMenu();
1752 }
1753
1754 public boolean onMenuOpened(int featureId, Menu menu) {
1755 if (mOptionsMenuOpen) {
1756 if (mConfigChanged) {
1757 // We do not need to make any changes to the state of the
1758 // title bar, since the only thing that happened was a
1759 // change in orientation
1760 mConfigChanged = false;
1761 } else {
1762 if (!mExtendedMenuOpen) {
1763 mExtendedMenuOpen = true;
1764 mUi.onExtendedMenuOpened();
1765 } else {
1766 // Switching the menu back to icon view, so show the
1767 // title bar once again.
1768 mExtendedMenuOpen = false;
1769 mUi.onExtendedMenuClosed(mInLoad);
Michael Kolb8233fac2010-10-26 16:08:53 -07001770 }
1771 }
1772 } else {
1773 // The options menu is closed, so open it, and show the title
1774 mOptionsMenuOpen = true;
1775 mConfigChanged = false;
1776 mExtendedMenuOpen = false;
1777 mUi.onOptionsMenuOpened();
1778 }
1779 return true;
1780 }
1781
1782 public void onOptionsMenuClosed(Menu menu) {
1783 mOptionsMenuOpen = false;
1784 mUi.onOptionsMenuClosed(mInLoad);
1785 }
1786
1787 public void onContextMenuClosed(Menu menu) {
1788 mUi.onContextMenuClosed(menu, mInLoad);
1789 }
1790
1791 // Helper method for getting the top window.
1792 @Override
1793 public WebView getCurrentTopWebView() {
1794 return mTabControl.getCurrentTopWebView();
1795 }
1796
1797 @Override
1798 public WebView getCurrentWebView() {
1799 return mTabControl.getCurrentWebView();
1800 }
1801
1802 /*
1803 * This method is called as a result of the user selecting the options
1804 * menu to see the download window. It shows the download window on top of
1805 * the current window.
1806 */
1807 void viewDownloads() {
1808 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1809 mActivity.startActivity(intent);
1810 }
1811
John Reck30b065e2011-07-19 10:58:05 -07001812 int getActionModeHeight() {
1813 TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
1814 new int[] { android.R.attr.actionBarSize });
1815 int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
1816 actionBarSizeTypedArray.recycle();
1817 return size;
1818 }
1819
Michael Kolb8233fac2010-10-26 16:08:53 -07001820 // action mode
1821
1822 void onActionModeStarted(ActionMode mode) {
1823 mUi.onActionModeStarted(mode);
1824 mActionMode = mode;
1825 }
1826
1827 /*
1828 * True if a custom ActionMode (i.e. find or select) is in use.
1829 */
1830 @Override
1831 public boolean isInCustomActionMode() {
1832 return mActionMode != null;
1833 }
1834
1835 /*
1836 * End the current ActionMode.
1837 */
1838 @Override
1839 public void endActionMode() {
1840 if (mActionMode != null) {
1841 mActionMode.finish();
1842 }
1843 }
1844
1845 /*
1846 * Called by find and select when they are finished. Replace title bars
1847 * as necessary.
1848 */
1849 public void onActionModeFinished(ActionMode mode) {
1850 if (!isInCustomActionMode()) return;
1851 mUi.onActionModeFinished(mInLoad);
1852 mActionMode = null;
1853 }
1854
1855 boolean isInLoad() {
1856 return mInLoad;
1857 }
1858
1859 // bookmark handling
1860
1861 /**
1862 * add the current page as a bookmark to the given folder id
1863 * @param folderId use -1 for the default folder
John Reckd3e4d5b2011-07-13 15:48:43 -07001864 * @param editExisting If true, check to see whether the site is already
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001865 * bookmarked, and if it is, edit that bookmark. If false, and
1866 * the site is already bookmarked, do not attempt to edit the
1867 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001868 */
1869 @Override
John Reckd3e4d5b2011-07-13 15:48:43 -07001870 public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
John Recka60fffa2011-09-06 16:30:29 -07001871 WebView w = getCurrentTopWebView();
1872 if (w == null) {
1873 return null;
1874 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001875 Intent i = new Intent(mActivity,
1876 AddBookmarkPage.class);
Michael Kolb8233fac2010-10-26 16:08:53 -07001877 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1878 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1879 String touchIconUrl = w.getTouchIconUrl();
1880 if (touchIconUrl != null) {
1881 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1882 WebSettings settings = w.getSettings();
1883 if (settings != null) {
1884 i.putExtra(AddBookmarkPage.USER_AGENT,
1885 settings.getUserAgentString());
1886 }
1887 }
1888 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1889 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1890 getDesiredThumbnailHeight(mActivity)));
1891 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07001892 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001893 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1894 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001895 // Put the dialog at the upper right of the screen, covering the
1896 // star on the title bar.
1897 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07001898 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07001899 }
1900
1901 // file chooser
1902 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1903 mUploadHandler = new UploadHandler(this);
1904 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1905 }
1906
1907 // thumbnails
1908
1909 /**
1910 * Return the desired width for thumbnail screenshots, which are stored in
1911 * the database, and used on the bookmarks screen.
1912 * @param context Context for finding out the density of the screen.
1913 * @return desired width for thumbnail screenshot.
1914 */
1915 static int getDesiredThumbnailWidth(Context context) {
1916 return context.getResources().getDimensionPixelOffset(
1917 R.dimen.bookmarkThumbnailWidth);
1918 }
1919
1920 /**
1921 * Return the desired height 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 height for thumbnail screenshot.
1925 */
1926 static int getDesiredThumbnailHeight(Context context) {
1927 return context.getResources().getDimensionPixelOffset(
1928 R.dimen.bookmarkThumbnailHeight);
1929 }
1930
John Reck8cc92352011-07-06 17:41:52 -07001931 static Bitmap createScreenshot(WebView view, int width, int height) {
John Reckd7dd9b22011-08-30 09:18:29 -07001932 if (view == null || view.getContentHeight() == 0
1933 || view.getContentWidth() == 0) {
1934 return null;
1935 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001936 // We render to a bitmap 2x the desired size so that we can then
1937 // re-scale it with filtering since canvas.scale doesn't filter
1938 // This helps reduce aliasing at the cost of being slightly blurry
1939 final int filter_scale = 2;
John Reckd7dd9b22011-08-30 09:18:29 -07001940 int scaledWidth = width * filter_scale;
1941 int scaledHeight = height * filter_scale;
1942 if (sThumbnailBitmap == null || sThumbnailBitmap.getWidth() != scaledWidth
1943 || sThumbnailBitmap.getHeight() != scaledHeight) {
1944 if (sThumbnailBitmap != null) {
1945 sThumbnailBitmap.recycle();
1946 sThumbnailBitmap = null;
1947 }
1948 sThumbnailBitmap =
1949 Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.RGB_565);
Michael Kolb8233fac2010-10-26 16:08:53 -07001950 }
John Reckd7dd9b22011-08-30 09:18:29 -07001951 Canvas canvas = new Canvas(sThumbnailBitmap);
1952 int contentWidth = view.getContentWidth();
1953 float overviewScale = scaledWidth / (view.getScale() * contentWidth);
1954 if (view instanceof BrowserWebView) {
1955 int dy = -((BrowserWebView)view).getTitleHeight();
1956 canvas.translate(0, dy * overviewScale);
1957 }
1958
1959 canvas.scale(overviewScale, overviewScale);
1960
1961 if (view instanceof BrowserWebView) {
1962 ((BrowserWebView)view).drawContent(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07001963 } else {
John Reckd7dd9b22011-08-30 09:18:29 -07001964 view.draw(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07001965 }
John Reckd7dd9b22011-08-30 09:18:29 -07001966 Bitmap ret = Bitmap.createScaledBitmap(sThumbnailBitmap,
1967 width, height, true);
Dianne Hackborn43cfe8a2011-08-02 16:59:35 -07001968 canvas.setBitmap(null);
John Reck5c6ac2f2011-01-05 10:18:03 -08001969 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001970 }
1971
John Reck34ef2672011-02-10 11:30:55 -08001972 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001973 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07001974 // FIXME: Would like to make sure there is actually something to
1975 // draw, but the API for that (WebViewCore.pictureReady()) is not
1976 // currently accessible here.
1977
John Reck34ef2672011-02-10 11:30:55 -08001978 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08001979 if (view == null) {
1980 // Tab was destroyed
1981 return;
1982 }
John Reck34ef2672011-02-10 11:30:55 -08001983 final String url = tab.getUrl();
1984 final String originalUrl = view.getOriginalUrl();
1985
1986 if (TextUtils.isEmpty(url)) {
1987 return;
1988 }
1989
1990 // Only update thumbnails for web urls (http(s)://), not for
1991 // about:, javascript:, data:, etc...
1992 // Unless it is a bookmarked site, then always update
1993 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
1994 return;
1995 }
1996
Michael Kolb8233fac2010-10-26 16:08:53 -07001997 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1998 getDesiredThumbnailHeight(mActivity));
1999 if (bm == null) {
2000 return;
2001 }
2002
2003 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002004 new AsyncTask<Void, Void, Void>() {
2005 @Override
2006 protected Void doInBackground(Void... unused) {
2007 Cursor cursor = null;
2008 try {
2009 // TODO: Clean this up
2010 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2011 if (cursor != null && cursor.moveToFirst()) {
2012 final ByteArrayOutputStream os =
2013 new ByteArrayOutputStream();
2014 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002015
John Reck34ef2672011-02-10 11:30:55 -08002016 ContentValues values = new ContentValues();
2017 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002018
John Reck34ef2672011-02-10 11:30:55 -08002019 do {
John Reck617fd832011-02-16 14:35:59 -08002020 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002021 cr.update(Images.CONTENT_URI, values, null, null);
2022 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002023 }
John Reck34ef2672011-02-10 11:30:55 -08002024 } catch (IllegalStateException e) {
2025 // Ignore
2026 } finally {
2027 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002028 }
John Reck34ef2672011-02-10 11:30:55 -08002029 return null;
2030 }
2031 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002032 }
2033
2034 private class Copy implements OnMenuItemClickListener {
2035 private CharSequence mText;
2036
2037 public boolean onMenuItemClick(MenuItem item) {
2038 copy(mText);
2039 return true;
2040 }
2041
2042 public Copy(CharSequence toCopy) {
2043 mText = toCopy;
2044 }
2045 }
2046
Leon Scroggins63c02662010-11-18 15:16:27 -05002047 private static class Download implements OnMenuItemClickListener {
2048 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002049 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002050 private boolean mPrivateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002051
2052 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002053 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002054 null, null, mPrivateBrowsing);
Michael Kolb8233fac2010-10-26 16:08:53 -07002055 return true;
2056 }
2057
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002058 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002059 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002060 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002061 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002062 }
2063 }
2064
Cary Clark8974d282010-11-22 10:46:05 -05002065 private static class SelectText implements OnMenuItemClickListener {
2066 private WebView mWebView;
2067
2068 public boolean onMenuItemClick(MenuItem item) {
2069 if (mWebView != null) {
2070 return mWebView.selectText();
2071 }
2072 return false;
2073 }
2074
2075 public SelectText(WebView webView) {
2076 mWebView = webView;
2077 }
2078
2079 }
2080
Michael Kolb8233fac2010-10-26 16:08:53 -07002081 /********************** TODO: UI stuff *****************************/
2082
2083 // these methods have been copied, they still need to be cleaned up
2084
2085 /****************** tabs ***************************************************/
2086
2087 // basic tab interactions:
2088
2089 // it is assumed that tabcontrol already knows about the tab
2090 protected void addTab(Tab tab) {
2091 mUi.addTab(tab);
2092 }
2093
2094 protected void removeTab(Tab tab) {
2095 mUi.removeTab(tab);
2096 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002097 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002098 }
2099
Michael Kolbf2055602011-04-09 17:20:03 -07002100 @Override
2101 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002102 // monkey protection against delayed start
2103 if (tab != null) {
2104 mTabControl.setCurrentTab(tab);
2105 // the tab is guaranteed to have a webview after setCurrentTab
2106 mUi.setActiveTab(tab);
2107 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002108 }
2109
John Reck8bcafc12011-08-29 16:43:02 -07002110 protected void closeEmptyTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002111 Tab current = mTabControl.getCurrentTab();
2112 if (current != null
2113 && current.getWebView().copyBackForwardList().getSize() == 0) {
John Reck8bcafc12011-08-29 16:43:02 -07002114 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002115 }
2116 }
2117
John Reck26b18322011-06-21 13:08:58 -07002118 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002119 // Dismiss the subwindow if applicable.
2120 dismissSubWindow(appTab);
2121 // Since we might kill the WebView, remove it from the
2122 // content view first.
2123 mUi.detachTab(appTab);
2124 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002125 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002126 // TODO: analyze why the remove and add are necessary
2127 mUi.attachTab(appTab);
2128 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002129 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002130 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002131 } else {
2132 // If the tab was the current tab, we have to attach
2133 // it to the view system again.
2134 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002135 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002136 }
2137 }
2138
2139 // Remove the sub window if it exists. Also called by TabControl when the
2140 // user clicks the 'X' to dismiss a sub window.
2141 public void dismissSubWindow(Tab tab) {
2142 removeSubWindow(tab);
2143 // dismiss the subwindow. This will destroy the WebView.
2144 tab.dismissSubWindow();
2145 getCurrentTopWebView().requestFocus();
2146 }
2147
2148 @Override
2149 public void removeSubWindow(Tab t) {
2150 if (t.getSubWebView() != null) {
2151 mUi.removeSubWindow(t.getSubViewContainer());
2152 }
2153 }
2154
2155 @Override
2156 public void attachSubWindow(Tab tab) {
2157 if (tab.getSubWebView() != null) {
2158 mUi.attachSubWindow(tab.getSubViewContainer());
2159 getCurrentTopWebView().requestFocus();
2160 }
2161 }
2162
Mathew Inwood29721c22011-06-29 17:55:24 +01002163 private Tab showPreloadedTab(final UrlData urlData) {
2164 if (!urlData.isPreloaded()) {
2165 return null;
2166 }
2167 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2168 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2169 if (sbQuery != null) {
Mathew Inwood9ad1eac2011-09-15 11:29:50 +01002170 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002171 // Could not submit query. Fallback to regular tab creation
2172 tabControl.destroy();
2173 return null;
2174 }
2175 }
Michael Kolbff6a7482011-07-26 16:37:15 -07002176 // check tab count and make room for new tab
2177 if (!mTabControl.canCreateNewTab()) {
2178 Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
2179 if (leastUsed != null) {
2180 closeTab(leastUsed);
2181 }
2182 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002183 Tab t = tabControl.getTab();
Mathew Inwoode09305e2011-09-02 12:03:26 +01002184 t.refreshIdAfterPreload();
Mathew Inwood29721c22011-06-29 17:55:24 +01002185 mTabControl.addPreloadedTab(t);
2186 addTab(t);
2187 setActiveTab(t);
2188 return t;
2189 }
2190
Michael Kolb7bcafde2011-05-09 13:55:59 -07002191 // open a non inconito tab with the given url data
2192 // and set as active tab
2193 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002194 Tab tab = showPreloadedTab(urlData);
2195 if (tab == null) {
2196 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002197 if ((tab != null) && !urlData.isEmpty()) {
2198 loadUrlDataIn(tab, urlData);
2199 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002200 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002201 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002202 }
2203
Michael Kolb843510f2010-12-09 10:51:49 -08002204 @Override
2205 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002206 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002207 }
2208
Michael Kolb8233fac2010-10-26 16:08:53 -07002209 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002210 public Tab openIncognitoTab() {
2211 return openTab(INCOGNITO_URI, true, true, false);
2212 }
2213
2214 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002215 public Tab openTab(String url, boolean incognito, boolean setActive,
2216 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002217 return openTab(url, incognito, setActive, useCurrent, null);
2218 }
2219
2220 @Override
2221 public Tab openTab(String url, Tab parent, boolean setActive,
2222 boolean useCurrent) {
2223 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2224 setActive, useCurrent, parent);
2225 }
2226
2227 public Tab openTab(String url, boolean incognito, boolean setActive,
2228 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002229 Tab tab = createNewTab(incognito, setActive, useCurrent);
2230 if (tab != null) {
John Reck5949c662011-05-27 09:52:29 -07002231 if (parent != null && parent != tab) {
2232 parent.addChildTab(tab);
2233 }
Michael Kolb519d2282011-05-09 17:03:19 -07002234 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002235 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002236 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002237 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002238 return tab;
2239 }
2240
2241 // this method will attempt to create a new tab
2242 // incognito: private browsing tab
2243 // setActive: ste tab as current tab
2244 // useCurrent: if no new tab can be created, return current tab
2245 private Tab createNewTab(boolean incognito, boolean setActive,
2246 boolean useCurrent) {
2247 Tab tab = null;
2248 if (mTabControl.canCreateNewTab()) {
2249 tab = mTabControl.createNewTab(incognito);
2250 addTab(tab);
2251 if (setActive) {
2252 setActiveTab(tab);
2253 }
2254 } else {
2255 if (useCurrent) {
2256 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002257 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002258 } else {
2259 mUi.showMaxTabsWarning();
2260 }
2261 }
2262 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002263 }
2264
John Reck2bc80422011-06-30 15:11:49 -07002265 @Override
2266 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2267 SnapshotTab tab = null;
2268 if (mTabControl.canCreateNewTab()) {
2269 tab = mTabControl.createSnapshotTab(snapshotId);
2270 addTab(tab);
2271 if (setActive) {
2272 setActiveTab(tab);
2273 }
2274 } else {
2275 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07002276 }
2277 return tab;
2278 }
2279
Michael Kolb8233fac2010-10-26 16:08:53 -07002280 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002281 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002282 * @return boolean True if we successfully switched to a different tab. If
2283 * the indexth tab is null, or if that tab is the same as
2284 * the current one, return false.
2285 */
2286 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002287 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002288 Tab currentTab = mTabControl.getCurrentTab();
2289 if (tab == null || tab == currentTab) {
2290 return false;
2291 }
2292 setActiveTab(tab);
2293 return true;
2294 }
2295
2296 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002297 public void closeCurrentTab() {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002298 closeCurrentTab(false);
2299 }
2300
2301 protected void closeCurrentTab(boolean andQuit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002302 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07002303 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07002304 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08002305 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002306 return;
2307 }
Michael Kolbc831b632011-05-11 09:30:34 -07002308 final Tab current = mTabControl.getCurrentTab();
2309 final int pos = mTabControl.getCurrentPosition();
2310 Tab newTab = current.getParent();
2311 if (newTab == null) {
2312 newTab = mTabControl.getTab(pos + 1);
2313 if (newTab == null) {
2314 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002315 }
2316 }
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002317 if (andQuit) {
2318 mTabControl.setCurrentTab(newTab);
2319 closeTab(current);
2320 } else if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002321 // Close window
2322 closeTab(current);
2323 }
2324 }
2325
2326 /**
2327 * Close the tab, remove its associated title bar, and adjust mTabControl's
2328 * current tab to a valid value.
2329 */
2330 @Override
2331 public void closeTab(Tab tab) {
Michael Kolb2d59c322011-01-25 13:18:55 -08002332 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002333 }
2334
Michael Kolb8233fac2010-10-26 16:08:53 -07002335 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07002336 protected void loadUrlFromContext(String url) {
2337 Tab tab = getCurrentTab();
2338 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002339 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07002340 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002341 url = UrlUtils.smartUrlFilter(url);
2342 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07002343 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07002344 }
2345 }
2346 }
2347
2348 /**
2349 * Load the URL into the given WebView and update the title bar
2350 * to reflect the new load. Call this instead of WebView.loadUrl
2351 * directly.
2352 * @param view The WebView used to load url.
2353 * @param url The URL to load.
2354 */
John Reck71e51422011-07-01 16:49:28 -07002355 @Override
2356 public void loadUrl(Tab tab, String url) {
John Reck26b18322011-06-21 13:08:58 -07002357 loadUrl(tab, url, null);
2358 }
2359
2360 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
2361 if (tab != null) {
2362 dismissSubWindow(tab);
2363 tab.loadUrl(url, headers);
Michael Kolba53c9892011-10-05 13:31:40 -07002364 mUi.onProgressChanged(tab);
John Reck26b18322011-06-21 13:08:58 -07002365 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002366 }
2367
2368 /**
2369 * Load UrlData into a Tab and update the title bar to reflect the new
2370 * load. Call this instead of UrlData.loadIn directly.
2371 * @param t The Tab used to load.
2372 * @param data The UrlData being loaded.
2373 */
2374 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07002375 if (data != null) {
2376 if (data.mVoiceIntent != null) {
2377 t.activateVoiceSearchMode(data.mVoiceIntent);
Michael Kolb14612442011-06-24 13:06:29 -07002378 } else if (data.isPreloaded()) {
2379 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07002380 } else {
2381 loadUrl(t, data.mUrl, data.mHeaders);
2382 }
2383 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002384 }
2385
John Reck30c714c2010-12-16 17:30:34 -08002386 @Override
2387 public void onUserCanceledSsl(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08002388 // TODO: Figure out the "right" behavior
John Reckef654f12011-07-12 16:42:08 -07002389 if (tab.canGoBack()) {
2390 tab.goBack();
John Reck30c714c2010-12-16 17:30:34 -08002391 } else {
John Reckef654f12011-07-12 16:42:08 -07002392 tab.loadUrl(mSettings.getHomePage(), null);
John Reck30c714c2010-12-16 17:30:34 -08002393 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002394 }
2395
2396 void goBackOnePageOrQuit() {
2397 Tab current = mTabControl.getCurrentTab();
2398 if (current == null) {
2399 /*
2400 * Instead of finishing the activity, simply push this to the back
2401 * of the stack and let ActivityManager to choose the foreground
2402 * activity. As BrowserActivity is singleTask, it will be always the
2403 * root of the task. So we can use either true or false for
2404 * moveTaskToBack().
2405 */
2406 mActivity.moveTaskToBack(true);
2407 return;
2408 }
John Reckef654f12011-07-12 16:42:08 -07002409 if (current.canGoBack()) {
2410 current.goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07002411 } else {
2412 // Check to see if we are closing a window that was created by
2413 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002414 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002415 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002416 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002417 // Now we close the other tab
2418 closeTab(current);
2419 } else {
Michael Kolbe28b3472011-08-04 16:54:31 -07002420 if ((current.getAppId() != null) || current.closeOnBack()) {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002421 closeCurrentTab(true);
Michael Kolbe28b3472011-08-04 16:54:31 -07002422 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002423 /*
2424 * Instead of finishing the activity, simply push this to the back
2425 * of the stack and let ActivityManager to choose the foreground
2426 * activity. As BrowserActivity is singleTask, it will be always the
2427 * root of the task. So we can use either true or false for
2428 * moveTaskToBack().
2429 */
2430 mActivity.moveTaskToBack(true);
2431 }
2432 }
2433 }
2434
2435 /**
2436 * Feed the previously stored results strings to the BrowserProvider so that
2437 * the SearchDialog will show them instead of the standard searches.
2438 * @param result String to show on the editable line of the SearchDialog.
2439 */
2440 @Override
2441 public void showVoiceSearchResults(String result) {
2442 ContentProviderClient client = mActivity.getContentResolver()
2443 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2444 ContentProvider prov = client.getLocalContentProvider();
2445 BrowserProvider bp = (BrowserProvider) prov;
2446 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2447 client.release();
2448
2449 Bundle bundle = createGoogleSearchSourceBundle(
2450 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2451 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2452 startSearch(result, false, bundle, false);
2453 }
2454
2455 private void startSearch(String initialQuery, boolean selectInitialQuery,
2456 Bundle appSearchData, boolean globalSearch) {
2457 if (appSearchData == null) {
2458 appSearchData = createGoogleSearchSourceBundle(
2459 GOOGLE_SEARCH_SOURCE_TYPE);
2460 }
2461
2462 SearchEngine searchEngine = mSettings.getSearchEngine();
2463 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2464 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2465 }
2466 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2467 globalSearch);
2468 }
2469
2470 private Bundle createGoogleSearchSourceBundle(String source) {
2471 Bundle bundle = new Bundle();
2472 bundle.putString(Search.SOURCE, source);
2473 return bundle;
2474 }
2475
2476 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002477 * helper method for key handler
2478 * returns the current tab if it can't advance
2479 */
Michael Kolbc831b632011-05-11 09:30:34 -07002480 private Tab getNextTab() {
2481 return mTabControl.getTab(Math.min(mTabControl.getTabCount() - 1,
2482 mTabControl.getCurrentPosition() + 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002483 }
2484
2485 /**
2486 * helper method for key handler
2487 * returns the current tab if it can't advance
2488 */
Michael Kolbc831b632011-05-11 09:30:34 -07002489 private Tab getPrevTab() {
2490 return mTabControl.getTab(Math.max(0,
2491 mTabControl.getCurrentPosition() - 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002492 }
2493
2494 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002495 * handle key events in browser
2496 *
2497 * @param keyCode
2498 * @param event
2499 * @return true if handled, false to pass to super
2500 */
2501 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002502 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002503 // Even if MENU is already held down, we need to call to super to open
2504 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002505 if (!noModifiers
2506 && ((KeyEvent.KEYCODE_MENU == keyCode)
2507 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2508 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002509 mMenuIsDown = true;
2510 return false;
2511 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002512
Cary Clark8ff8c662010-12-29 15:03:05 -05002513 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07002514 Tab tab = getCurrentTab();
2515 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05002516
Cary Clark160bbb92011-01-10 11:17:07 -05002517 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2518 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002519
Michael Kolb8233fac2010-10-26 16:08:53 -07002520 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002521 case KeyEvent.KEYCODE_TAB:
2522 if (event.isCtrlPressed()) {
2523 if (event.isShiftPressed()) {
2524 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002525 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002526 } else {
2527 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002528 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002529 }
2530 return true;
2531 }
2532 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002533 case KeyEvent.KEYCODE_SPACE:
2534 // WebView/WebTextView handle the keys in the KeyDown. As
2535 // the Activity's shortcut keys are only handled when WebView
2536 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002537 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002538 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002539 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002540 pageDown();
2541 }
2542 return true;
2543 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002544 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002545 event.startTracking();
2546 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07002547 case KeyEvent.KEYCODE_FORWARD:
2548 if (!noModifiers) break;
2549 tab.goForward();
2550 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002551 case KeyEvent.KEYCODE_DPAD_LEFT:
2552 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002553 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05002554 return true;
2555 }
2556 break;
2557 case KeyEvent.KEYCODE_DPAD_RIGHT:
2558 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002559 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05002560 return true;
2561 }
2562 break;
2563 case KeyEvent.KEYCODE_A:
2564 if (ctrl) {
2565 webView.selectAll();
2566 return true;
2567 }
2568 break;
Michael Kolba4183062011-01-16 10:43:21 -08002569// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002570 case KeyEvent.KEYCODE_C:
2571 if (ctrl) {
2572 webView.copySelection();
2573 return true;
2574 }
2575 break;
Michael Kolba4183062011-01-16 10:43:21 -08002576// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002577// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002578// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002579// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002580// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002581// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002582// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002583// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002584// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002585// case KeyEvent.KEYCODE_M: // unused
2586// case KeyEvent.KEYCODE_N: // in Chrome: new window
2587// case KeyEvent.KEYCODE_O: // in Chrome: open file
2588// case KeyEvent.KEYCODE_P: // in Chrome: print page
2589// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002590// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002591// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2592 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002593 // we can't use the ctrl/shift flags, they check for
2594 // exclusive use of a modifier
2595 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002596 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002597 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002598 } else {
2599 openTabToHomePage();
2600 }
2601 return true;
2602 }
2603 break;
2604// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2605// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb5ae15bd2011-08-16 17:09:27 -07002606// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002607// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2608// case KeyEvent.KEYCODE_Y: // unused
2609// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002610 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002611 // it is a regular key and webview is not null
2612 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002613 }
2614
John Recke6bf4ab2011-02-24 15:48:05 -08002615 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2616 switch(keyCode) {
2617 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07002618 if (mUi.isWebShowing()) {
John Recke6bf4ab2011-02-24 15:48:05 -08002619 bookmarksOrHistoryPicker(true);
2620 return true;
2621 }
2622 break;
2623 }
2624 return false;
2625 }
2626
Michael Kolb8233fac2010-10-26 16:08:53 -07002627 boolean onKeyUp(int keyCode, KeyEvent event) {
Michael Kolb2814a362011-05-19 15:49:41 -07002628 if (KeyEvent.KEYCODE_MENU == keyCode) {
2629 mMenuIsDown = false;
2630 if (event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002631 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002632 }
2633 }
Cary Clark160bbb92011-01-10 11:17:07 -05002634 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002635 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002636 case KeyEvent.KEYCODE_BACK:
2637 if (event.isTracking() && !event.isCanceled()) {
2638 onBackKey();
2639 return true;
2640 }
2641 break;
2642 }
2643 return false;
2644 }
2645
2646 public boolean isMenuDown() {
2647 return mMenuIsDown;
2648 }
2649
Ben Murdoch8029a772010-11-16 11:58:21 +00002650 public void setupAutoFill(Message message) {
2651 // Open the settings activity at the AutoFill profile fragment so that
2652 // the user can create a new profile. When they return, we will dispatch
2653 // the message so that we can autofill the form using their new profile.
2654 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2655 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2656 AutoFillSettingsFragment.class.getName());
2657 mAutoFillSetupMessage = message;
2658 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2659 }
John Reckb3417f02011-01-14 11:01:05 -08002660
2661 @Override
Narayan Kamath5119edd2011-02-23 15:49:17 +00002662 public void registerDropdownChangeListener(DropdownChangeListener d) {
2663 mUi.registerDropdownChangeListener(d);
2664 }
Michael Kolbfbc579a2011-07-07 15:59:33 -07002665
2666 public boolean onSearchRequested() {
2667 mUi.editUrl(false);
2668 return true;
2669 }
2670
John Reck1cf4b792011-07-26 10:22:22 -07002671 @Override
2672 public boolean shouldCaptureThumbnails() {
2673 return mUi.shouldCaptureThumbnails();
2674 }
2675
Michael Kolbc3af0672011-08-09 10:24:41 -07002676 @Override
2677 public void setBlockEvents(boolean block) {
2678 mBlockEvents = block;
2679 }
2680
2681 public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002682 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002683 }
2684
2685 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002686 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002687 }
2688
2689 public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002690 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002691 }
2692
2693 public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002694 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002695 }
2696
2697 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002698 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002699 }
2700
Michael Kolb8233fac2010-10-26 16:08:53 -07002701}