blob: 3093085aa45ad5f77033c8cb6a711fd7967f3625 [file] [log] [blame]
Michael Kolb8233fac2010-10-26 16:08:53 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
Michael Kolb8233fac2010-10-26 16:08:53 -070019import android.app.Activity;
20import android.app.DownloadManager;
21import android.app.SearchManager;
22import android.content.ClipboardManager;
23import android.content.ContentProvider;
24import android.content.ContentProviderClient;
25import android.content.ContentResolver;
John Reckd8c74522011-06-14 08:45:00 -070026import android.content.ContentUris;
Michael Kolb8233fac2010-10-26 16:08:53 -070027import android.content.ContentValues;
28import android.content.Context;
29import android.content.Intent;
30import android.content.pm.PackageManager;
31import android.content.pm.ResolveInfo;
32import android.content.res.Configuration;
John Reck30b065e2011-07-19 10:58:05 -070033import android.content.res.TypedArray;
Leon Scroggins1961ed22010-12-07 15:22:21 -050034import android.database.ContentObserver;
Michael Kolb8233fac2010-10-26 16:08:53 -070035import android.database.Cursor;
36import android.database.sqlite.SQLiteDatabase;
Michael Kolb8233fac2010-10-26 16:08:53 -070037import android.graphics.Bitmap;
38import android.graphics.Canvas;
39import android.graphics.Picture;
40import android.net.Uri;
41import android.net.http.SslError;
42import android.os.AsyncTask;
43import android.os.Bundle;
44import android.os.Handler;
45import android.os.Message;
46import android.os.PowerManager;
47import android.os.PowerManager.WakeLock;
Ben Murdoch8029a772010-11-16 11:58:21 +000048import android.preference.PreferenceActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -070049import android.provider.Browser;
50import android.provider.BrowserContract;
Michael Kolb8233fac2010-10-26 16:08:53 -070051import android.provider.BrowserContract.Images;
52import android.provider.ContactsContract;
53import android.provider.ContactsContract.Intents.Insert;
Michael Kolbcfa3af52010-12-14 10:36:11 -080054import android.speech.RecognizerIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070055import android.text.TextUtils;
56import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080057import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070058import android.view.ActionMode;
59import android.view.ContextMenu;
60import android.view.ContextMenu.ContextMenuInfo;
61import android.view.Gravity;
62import android.view.KeyEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070063import android.view.Menu;
64import android.view.MenuInflater;
65import android.view.MenuItem;
66import android.view.MenuItem.OnMenuItemClickListener;
Michael Kolbc3af0672011-08-09 10:24:41 -070067import android.view.MotionEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070068import android.view.View;
69import android.webkit.CookieManager;
70import android.webkit.CookieSyncManager;
71import android.webkit.HttpAuthHandler;
72import android.webkit.SslErrorHandler;
73import android.webkit.ValueCallback;
74import android.webkit.WebChromeClient;
75import android.webkit.WebIconDatabase;
76import android.webkit.WebSettings;
77import android.webkit.WebView;
Leon Scrogginsac993842011-02-02 12:54:07 -050078import android.widget.Toast;
Michael Kolb8233fac2010-10-26 16:08:53 -070079
Michael Kolb4bd767d2011-05-27 11:33:55 -070080import com.android.browser.IntentHandler.UrlData;
John Reck2bc80422011-06-30 15:11:49 -070081import com.android.browser.UI.ComboViews;
Michael Kolb4bd767d2011-05-27 11:33:55 -070082import com.android.browser.UI.DropdownChangeListener;
83import com.android.browser.provider.BrowserProvider;
John Reck1cf4b792011-07-26 10:22:22 -070084import com.android.browser.provider.BrowserProvider2.Thumbnails;
John Reck8cc92352011-07-06 17:41:52 -070085import com.android.browser.provider.SnapshotProvider.Snapshots;
Michael Kolb4bd767d2011-05-27 11:33:55 -070086import com.android.browser.search.SearchEngine;
87import com.android.common.Search;
88
Michael Kolb8233fac2010-10-26 16:08:53 -070089import java.io.ByteArrayOutputStream;
Michael Kolb8233fac2010-10-26 16:08:53 -070090import java.net.URLEncoder;
John Reck1cf4b792011-07-26 10:22:22 -070091import java.util.ArrayList;
Michael Kolb8233fac2010-10-26 16:08:53 -070092import java.util.Calendar;
93import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -080094import java.util.List;
John Reck26b18322011-06-21 13:08:58 -070095import java.util.Map;
Michael Kolb8233fac2010-10-26 16:08:53 -070096
97/**
98 * Controller for browser
99 */
100public class Controller
101 implements WebViewController, UiController {
102
103 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800104 private static final String SEND_APP_ID_EXTRA =
105 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
Michael Kolba4261fd2011-05-05 11:27:37 -0700106 private static final String INCOGNITO_URI = "browser:incognito";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800107
Michael Kolb8233fac2010-10-26 16:08:53 -0700108
109 // public message ids
110 public final static int LOAD_URL = 1001;
111 public final static int STOP_LOAD = 1002;
112
113 // Message Ids
114 private static final int FOCUS_NODE_HREF = 102;
115 private static final int RELEASE_WAKELOCK = 107;
116
117 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
118
119 private static final int OPEN_BOOKMARKS = 201;
120
121 private static final int EMPTY_MENU = -1;
122
Michael Kolb8233fac2010-10-26 16:08:53 -0700123 // activity requestCode
John Reckd3e4d5b2011-07-13 15:48:43 -0700124 final static int COMBO_VIEW = 1;
Michael Kolb8233fac2010-10-26 16:08:53 -0700125 final static int PREFERENCES_PAGE = 3;
126 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000127 final static int AUTOFILL_SETUP = 5;
128
Michael Kolb8233fac2010-10-26 16:08:53 -0700129 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
130
131 // As the ids are dynamically created, we can't guarantee that they will
132 // be in sequence, so this static array maps ids to a window number.
133 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
134 { R.id.window_one_menu_id, R.id.window_two_menu_id,
135 R.id.window_three_menu_id, R.id.window_four_menu_id,
136 R.id.window_five_menu_id, R.id.window_six_menu_id,
137 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
138
139 // "source" parameter for Google search through search key
140 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
141 // "source" parameter for Google search through simplily type
142 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
143
Guang Zhu9e78f512011-05-04 11:45:11 -0700144 // "no-crash-recovery" parameter in intetnt to suppress crash recovery
145 final static String NO_CRASH_RECOVERY = "no-crash-recovery";
146
Michael Kolb8233fac2010-10-26 16:08:53 -0700147 private Activity mActivity;
148 private UI mUi;
149 private TabControl mTabControl;
150 private BrowserSettings mSettings;
151 private WebViewFactory mFactory;
152
153 private WakeLock mWakeLock;
154
155 private UrlHandler mUrlHandler;
156 private UploadHandler mUploadHandler;
157 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700158 private PageDialogsHandler mPageDialogsHandler;
159 private NetworkStateHandler mNetworkHandler;
Martijn Coenenb2f93552011-06-14 10:48:35 +0200160 private NfcHandler mNfcHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700161
Ben Murdoch8029a772010-11-16 11:58:21 +0000162 private Message mAutoFillSetupMessage;
163
Michael Kolb8233fac2010-10-26 16:08:53 -0700164 private boolean mShouldShowErrorConsole;
165
166 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
167
168 // FIXME, temp address onPrepareMenu performance problem.
169 // When we move everything out of view, we should rewrite this.
170 private int mCurrentMenuState = 0;
171 private int mMenuState = R.id.MAIN_MENU;
172 private int mOldMenuState = EMPTY_MENU;
173 private Menu mCachedMenu;
174
Michael Kolb8233fac2010-10-26 16:08:53 -0700175 private boolean mMenuIsDown;
176
177 // For select and find, we keep track of the ActionMode so that
178 // finish() can be called as desired.
179 private ActionMode mActionMode;
180
181 /**
182 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
183 * of whether the configuration has changed. The first onMenuOpened call
184 * after a configuration change is simply a reopening of the same menu
185 * (i.e. mIconView did not change).
186 */
187 private boolean mConfigChanged;
188
189 /**
190 * Keeps track of whether the options menu is open. This is important in
191 * determining whether to show or hide the title bar overlay
192 */
193 private boolean mOptionsMenuOpen;
194
195 /**
196 * Whether or not the options menu is in its bigger, popup menu form. When
197 * true, we want the title bar overlay to be gone. When false, we do not.
198 * Only meaningful if mOptionsMenuOpen is true.
199 */
200 private boolean mExtendedMenuOpen;
201
202 private boolean mInLoad;
203
204 private boolean mActivityPaused = true;
205 private boolean mLoadStopped;
206
207 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500208 // Checks to see when the bookmarks database has changed, and updates the
209 // Tabs' notion of whether they represent bookmarked sites.
210 private ContentObserver mBookmarksObserver;
John Reck847b5322011-04-14 17:02:18 -0700211 private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700212
John Reck30b065e2011-07-19 10:58:05 -0700213 private boolean mSimulateActionBarOverlayMode;
214
Michael Kolbc3af0672011-08-09 10:24:41 -0700215 private boolean mBlockEvents;
216
John Reckbc490d22011-07-22 15:04:59 -0700217 public Controller(Activity browser, boolean preloadCrashState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700218 mActivity = browser;
219 mSettings = BrowserSettings.getInstance();
220 mTabControl = new TabControl(this);
221 mSettings.setController(this);
John Reck378a4102011-06-09 16:23:01 -0700222 mCrashRecoveryHandler = CrashRecoveryHandler.initialize(this);
John Reckbc490d22011-07-22 15:04:59 -0700223 if (preloadCrashState) {
224 mCrashRecoveryHandler.preloadCrashState();
225 }
Michael Kolb14612442011-06-24 13:06:29 -0700226 mFactory = new BrowserWebViewFactory(browser);
Michael Kolb8233fac2010-10-26 16:08:53 -0700227
228 mUrlHandler = new UrlHandler(this);
229 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700230 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
Martijn Coenenb2f93552011-06-14 10:48:35 +0200231 mNfcHandler = new NfcHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700232
Michael Kolb8233fac2010-10-26 16:08:53 -0700233 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500234 mBookmarksObserver = new ContentObserver(mHandler) {
235 @Override
236 public void onChange(boolean selfChange) {
237 int size = mTabControl.getTabCount();
238 for (int i = 0; i < size; i++) {
239 mTabControl.getTab(i).updateBookmarkedStatus();
240 }
241 }
242
243 };
244 browser.getContentResolver().registerContentObserver(
245 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700246
247 mNetworkHandler = new NetworkStateHandler(mActivity, this);
248 // Start watching the default geolocation permissions
249 mSystemAllowGeolocationOrigins =
250 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
251 mSystemAllowGeolocationOrigins.start();
252
John Reckaf262e72011-07-25 13:55:44 -0700253 openIconDatabase();
John Reck30b065e2011-07-19 10:58:05 -0700254 mSimulateActionBarOverlayMode = !BrowserActivity.isTablet(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700255 }
256
Patrick Scott7d50a932011-02-04 09:27:26 -0500257 void start(final Bundle icicle, final Intent intent) {
Guang Zhu9e78f512011-05-04 11:45:11 -0700258 boolean noCrashRecovery = intent.getBooleanExtra(NO_CRASH_RECOVERY, false);
259 if (icicle != null || noCrashRecovery) {
John Reck847b5322011-04-14 17:02:18 -0700260 doStart(icicle, intent);
261 } else {
262 mCrashRecoveryHandler.startRecovery(intent);
263 }
264 }
265
266 void doStart(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700267 // Unless the last browser usage was within 24 hours, destroy any
268 // remaining incognito tabs.
269
270 Calendar lastActiveDate = icicle != null ?
271 (Calendar) icicle.getSerializable("lastActiveDate") : null;
272 Calendar today = Calendar.getInstance();
273 Calendar yesterday = Calendar.getInstance();
274 yesterday.add(Calendar.DATE, -1);
275
Patrick Scott7d50a932011-02-04 09:27:26 -0500276 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700277 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800278 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700279
Patrick Scott7d50a932011-02-04 09:27:26 -0500280 // Find out if we will restore any state and remember the tab.
Michael Kolbc831b632011-05-11 09:30:34 -0700281 final long currentTabId =
Patrick Scott7d50a932011-02-04 09:27:26 -0500282 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000283
Michael Kolbc831b632011-05-11 09:30:34 -0700284 if (currentTabId == -1) {
Patrick Scott7d50a932011-02-04 09:27:26 -0500285 // Not able to restore so we go ahead and clear session cookies. We
286 // must do this before trying to login the user as we don't want to
287 // clear any session cookies set during login.
288 CookieManager.getInstance().removeSessionCookie();
289 }
290
Patrick Scottd43e75a2011-03-14 14:47:23 -0400291 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500292 new Runnable() {
293 @Override public void run() {
Michael Kolbc831b632011-05-11 09:30:34 -0700294 onPreloginFinished(icicle, intent, currentTabId, restoreIncognitoTabs);
Patrick Scott7d50a932011-02-04 09:27:26 -0500295 }
296 });
297 }
298
Michael Kolbc831b632011-05-11 09:30:34 -0700299 private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId,
Patrick Scott7d50a932011-02-04 09:27:26 -0500300 boolean restoreIncognitoTabs) {
Michael Kolbc831b632011-05-11 09:30:34 -0700301 if (currentTabId == -1) {
John Reck1cf4b792011-07-26 10:22:22 -0700302 BackgroundHandler.execute(new PruneThumbnails(mActivity, null));
Michael Kolb8233fac2010-10-26 16:08:53 -0700303 final Bundle extra = intent.getExtras();
304 // Create an initial tab.
305 // If the intent is ACTION_VIEW and data is not null, the Browser is
306 // invoked to view the content by another application. In this case,
307 // the tab will be close when exit.
Michael Kolb14612442011-06-24 13:06:29 -0700308 UrlData urlData = IntentHandler.getUrlDataFromIntent(intent);
Michael Kolb7bcafde2011-05-09 13:55:59 -0700309 Tab t = null;
310 if (urlData.isEmpty()) {
311 t = openTabToHomePage();
312 } else {
313 t = openTab(urlData);
314 }
315 if (t != null) {
316 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
317 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700318 WebView webView = t.getWebView();
319 if (extra != null) {
320 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
321 if (scale > 0 && scale <= 1000) {
322 webView.setInitialScale(scale);
323 }
324 }
John Reckd8c74522011-06-14 08:45:00 -0700325 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700326 } else {
Michael Kolbc831b632011-05-11 09:30:34 -0700327 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
Patrick Scott7d50a932011-02-04 09:27:26 -0500328 mUi.needsRestoreAllTabs());
John Reck1cf4b792011-07-26 10:22:22 -0700329 List<Tab> tabs = mTabControl.getTabs();
330 ArrayList<Long> restoredTabs = new ArrayList<Long>(tabs.size());
331 for (Tab t : tabs) {
332 restoredTabs.add(t.getId());
333 }
334 BackgroundHandler.execute(new PruneThumbnails(mActivity, restoredTabs));
335 mUi.updateTabs(tabs);
Michael Kolb8233fac2010-10-26 16:08:53 -0700336 // TabControl.restoreState() will create a new tab even if
337 // restoring the state fails.
338 setActiveTab(mTabControl.getCurrentTab());
John Reckdb22ec42011-06-29 11:31:24 -0700339 // Handle the intent
340 mIntentHandler.onNewIntent(intent);
Michael Kolb8233fac2010-10-26 16:08:53 -0700341 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700342 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700343 String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb8233fac2010-10-26 16:08:53 -0700344 if (jsFlags.trim().length() != 0) {
345 getCurrentWebView().setJsFlags(jsFlags);
346 }
John Reck439c9a52010-12-14 10:04:39 -0800347 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
348 bookmarksOrHistoryPicker(false);
349 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700350 }
351
John Reck1cf4b792011-07-26 10:22:22 -0700352 private static class PruneThumbnails implements Runnable {
353 private Context mContext;
354 private List<Long> mIds;
355
356 PruneThumbnails(Context context, List<Long> preserveIds) {
357 mContext = context.getApplicationContext();
358 mIds = preserveIds;
359 }
360
361 @Override
362 public void run() {
363 ContentResolver cr = mContext.getContentResolver();
364 if (mIds == null || mIds.size() == 0) {
365 cr.delete(Thumbnails.CONTENT_URI, null, null);
366 } else {
367 int length = mIds.size();
368 StringBuilder where = new StringBuilder();
369 where.append(Thumbnails._ID);
370 where.append(" not in (");
371 for (int i = 0; i < length; i++) {
372 where.append(mIds.get(i));
373 if (i < (length - 1)) {
374 where.append(",");
375 }
376 }
377 where.append(")");
378 cr.delete(Thumbnails.CONTENT_URI, where.toString(), null);
379 }
380 }
381
382 }
383
Michael Kolb1514bb72010-11-22 09:11:48 -0800384 @Override
385 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700386 return mFactory;
387 }
388
389 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800390 public void onSetWebView(Tab tab, WebView view) {
391 mUi.onSetWebView(tab, view);
392 }
393
394 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800395 public void createSubWindow(Tab tab) {
396 endActionMode();
397 WebView mainView = tab.getWebView();
398 WebView subView = mFactory.createWebView((mainView == null)
399 ? false
400 : mainView.isPrivateBrowsingEnabled());
401 mUi.createSubWindow(tab, subView);
402 }
403
404 @Override
Michael Kolb14612442011-06-24 13:06:29 -0700405 public Context getContext() {
406 return mActivity;
407 }
408
409 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700410 public Activity getActivity() {
411 return mActivity;
412 }
413
414 void setUi(UI ui) {
415 mUi = ui;
416 }
417
418 BrowserSettings getSettings() {
419 return mSettings;
420 }
421
422 IntentHandler getIntentHandler() {
423 return mIntentHandler;
424 }
425
426 @Override
427 public UI getUi() {
428 return mUi;
429 }
430
431 int getMaxTabs() {
432 return mActivity.getResources().getInteger(R.integer.max_tabs);
433 }
434
435 @Override
436 public TabControl getTabControl() {
437 return mTabControl;
438 }
439
Michael Kolb1bf23132010-11-19 12:55:12 -0800440 @Override
441 public List<Tab> getTabs() {
442 return mTabControl.getTabs();
443 }
444
John Reckaf262e72011-07-25 13:55:44 -0700445 // Open the icon database.
446 private void openIconDatabase() {
447 // We have to call getInstance on the UI thread
448 final WebIconDatabase instance = WebIconDatabase.getInstance();
449 BackgroundHandler.execute(new Runnable() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000450
John Reckaf262e72011-07-25 13:55:44 -0700451 @Override
452 public void run() {
453 instance.open(mActivity.getDir("icons", 0).getPath());
Michael Kolb8233fac2010-10-26 16:08:53 -0700454 }
John Reckaf262e72011-07-25 13:55:44 -0700455 });
Michael Kolb8233fac2010-10-26 16:08:53 -0700456 }
457
458 private void startHandler() {
459 mHandler = new Handler() {
460
461 @Override
462 public void handleMessage(Message msg) {
463 switch (msg.what) {
464 case OPEN_BOOKMARKS:
465 bookmarksOrHistoryPicker(false);
466 break;
467 case FOCUS_NODE_HREF:
468 {
469 String url = (String) msg.getData().get("url");
470 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500471 String src = (String) msg.getData().get("src");
472 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700473 if (TextUtils.isEmpty(url)) {
474 break;
475 }
476 HashMap focusNodeMap = (HashMap) msg.obj;
477 WebView view = (WebView) focusNodeMap.get("webview");
478 // Only apply the action if the top window did not change.
479 if (getCurrentTopWebView() != view) {
480 break;
481 }
482 switch (msg.arg1) {
483 case R.id.open_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700484 loadUrlFromContext(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700485 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500486 case R.id.view_image_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700487 loadUrlFromContext(src);
Cary Clark043c2d62010-12-15 11:19:39 -0500488 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500489 case R.id.open_newtab_context_menu_id:
490 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -0700491 openTab(url, parent,
492 !mSettings.openInBackground(), true);
Leon Scroggins026f2542010-11-22 13:26:12 -0500493 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700494 case R.id.copy_link_context_menu_id:
495 copy(url);
496 break;
497 case R.id.save_link_context_menu_id:
498 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500499 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000500 mActivity, url, null, null, null,
501 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700502 break;
503 }
504 break;
505 }
506
507 case LOAD_URL:
John Reck26b18322011-06-21 13:08:58 -0700508 loadUrlFromContext((String) msg.obj);
Michael Kolb8233fac2010-10-26 16:08:53 -0700509 break;
510
511 case STOP_LOAD:
512 stopLoading();
513 break;
514
515 case RELEASE_WAKELOCK:
John Reckf57c0292011-07-21 18:15:39 -0700516 if (mWakeLock != null && mWakeLock.isHeld()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700517 mWakeLock.release();
518 // if we reach here, Browser should be still in the
519 // background loading after WAKELOCK_TIMEOUT (5-min).
520 // To avoid burning the battery, stop loading.
521 mTabControl.stopAllLoading();
522 }
523 break;
524
525 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800526 Tab tab = (Tab) msg.obj;
527 if (tab != null) {
528 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700529 }
530 break;
531 }
532 }
533 };
534
535 }
536
John Reckef654f12011-07-12 16:42:08 -0700537 @Override
Martijn Coenenb2f93552011-06-14 10:48:35 +0200538 public Tab getCurrentTab() {
539 return mTabControl.getCurrentTab();
540 }
541
Michael Kolbba99c5d2010-11-29 14:57:41 -0800542 @Override
543 public void shareCurrentPage() {
544 shareCurrentPage(mTabControl.getCurrentTab());
545 }
546
547 private void shareCurrentPage(Tab tab) {
548 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800549 sharePage(mActivity, tab.getTitle(),
550 tab.getUrl(), tab.getFavicon(),
551 createScreenshot(tab.getWebView(),
552 getDesiredThumbnailWidth(mActivity),
553 getDesiredThumbnailHeight(mActivity)));
554 }
555 }
556
Michael Kolb8233fac2010-10-26 16:08:53 -0700557 /**
558 * Share a page, providing the title, url, favicon, and a screenshot. Uses
559 * an {@link Intent} to launch the Activity chooser.
560 * @param c Context used to launch a new Activity.
561 * @param title Title of the page. Stored in the Intent with
562 * {@link Intent#EXTRA_SUBJECT}
563 * @param url URL of the page. Stored in the Intent with
564 * {@link Intent#EXTRA_TEXT}
565 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
566 * with {@link Browser#EXTRA_SHARE_FAVICON}
567 * @param screenshot Bitmap of a screenshot of the page. Stored in the
568 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
569 */
570 static final void sharePage(Context c, String title, String url,
571 Bitmap favicon, Bitmap screenshot) {
572 Intent send = new Intent(Intent.ACTION_SEND);
573 send.setType("text/plain");
574 send.putExtra(Intent.EXTRA_TEXT, url);
575 send.putExtra(Intent.EXTRA_SUBJECT, title);
576 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
577 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
578 try {
579 c.startActivity(Intent.createChooser(send, c.getString(
580 R.string.choosertitle_sharevia)));
581 } catch(android.content.ActivityNotFoundException ex) {
582 // if no app handles it, do nothing
583 }
584 }
585
586 private void copy(CharSequence text) {
587 ClipboardManager cm = (ClipboardManager) mActivity
588 .getSystemService(Context.CLIPBOARD_SERVICE);
589 cm.setText(text);
590 }
591
592 // lifecycle
593
594 protected void onConfgurationChanged(Configuration config) {
595 mConfigChanged = true;
596 if (mPageDialogsHandler != null) {
597 mPageDialogsHandler.onConfigurationChanged(config);
598 }
599 mUi.onConfigurationChanged(config);
600 }
601
602 @Override
603 public void handleNewIntent(Intent intent) {
Michael Kolb59e232c2011-08-18 17:19:53 -0700604 if (!mUi.isWebShowing()) {
605 mUi.showWeb(false);
606 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700607 mIntentHandler.onNewIntent(intent);
608 }
609
610 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800611 if (mUi.isCustomViewShowing()) {
612 hideCustomView();
613 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700614 if (mActivityPaused) {
615 Log.e(LOGTAG, "BrowserActivity is already paused.");
616 return;
617 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700618 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800619 Tab tab = mTabControl.getCurrentTab();
620 if (tab != null) {
621 tab.pause();
622 if (!pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700623 if (mWakeLock == null) {
624 PowerManager pm = (PowerManager) mActivity
625 .getSystemService(Context.POWER_SERVICE);
626 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
627 }
Michael Kolb70976932010-11-30 11:34:01 -0800628 mWakeLock.acquire();
629 mHandler.sendMessageDelayed(mHandler
630 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
631 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700632 }
633 mUi.onPause();
634 mNetworkHandler.onPause();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200635 mNfcHandler.onPause();
Michael Kolb8233fac2010-10-26 16:08:53 -0700636
637 WebView.disablePlatformNotifications();
638 }
639
John Reck1cf4b792011-07-26 10:22:22 -0700640 void onSaveInstanceState(Bundle outState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700641 // the default implementation requires each view to have an id. As the
642 // browser handles the state itself and it doesn't use id for the views,
643 // don't call the default implementation. Otherwise it will trigger the
644 // warning like this, "couldn't save which view has focus because the
645 // focused view XXX has no id".
646
647 // Save all the tabs
John Reck1cf4b792011-07-26 10:22:22 -0700648 mTabControl.saveState(outState);
John Reck24f18262011-06-17 14:47:20 -0700649 if (!outState.isEmpty()) {
650 // Save time so that we know how old incognito tabs (if any) are.
651 outState.putSerializable("lastActiveDate", Calendar.getInstance());
652 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700653 }
654
655 void onResume() {
656 if (!mActivityPaused) {
657 Log.e(LOGTAG, "BrowserActivity is already resumed.");
658 return;
659 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700660 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800661 Tab current = mTabControl.getCurrentTab();
662 if (current != null) {
663 current.resume();
664 resumeWebViewTimers(current);
665 }
John Reckf57c0292011-07-21 18:15:39 -0700666 releaseWakeLock();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200667
Michael Kolb8233fac2010-10-26 16:08:53 -0700668 mUi.onResume();
669 mNetworkHandler.onResume();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200670 mNfcHandler.onResume();
Michael Kolb8233fac2010-10-26 16:08:53 -0700671 WebView.enablePlatformNotifications();
672 }
673
John Reckf57c0292011-07-21 18:15:39 -0700674 private void releaseWakeLock() {
675 if (mWakeLock != null && mWakeLock.isHeld()) {
676 mHandler.removeMessages(RELEASE_WAKELOCK);
677 mWakeLock.release();
678 }
679 }
680
Michael Kolb70976932010-11-30 11:34:01 -0800681 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800682 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800683 * @param tab guaranteed non-null
684 */
685 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700686 boolean inLoad = tab.inPageLoad();
687 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
688 CookieSyncManager.getInstance().startSync();
689 WebView w = tab.getWebView();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100690 WebViewTimersControl.getInstance().onBrowserActivityResume(w);
Michael Kolb8233fac2010-10-26 16:08:53 -0700691 }
692 }
693
Michael Kolb70976932010-11-30 11:34:01 -0800694 /**
695 * Pause all WebView timers using the WebView of the given tab
696 * @param tab
697 * @return true if the timers are paused or tab is null
698 */
699 private boolean pauseWebViewTimers(Tab tab) {
700 if (tab == null) {
701 return true;
702 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700703 CookieSyncManager.getInstance().stopSync();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100704 WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView());
Michael Kolb8233fac2010-10-26 16:08:53 -0700705 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700706 }
Michael Kolb70976932010-11-30 11:34:01 -0800707 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700708 }
709
710 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800711 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700712 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
713 mUploadHandler = null;
714 }
715 if (mTabControl == null) return;
716 mUi.onDestroy();
717 // Remove the current tab and sub window
718 Tab t = mTabControl.getCurrentTab();
719 if (t != null) {
720 dismissSubWindow(t);
721 removeTab(t);
722 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500723 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700724 // Destroy all the tabs
725 mTabControl.destroy();
726 WebIconDatabase.getInstance().close();
727 // Stop watching the default geolocation permissions
728 mSystemAllowGeolocationOrigins.stop();
729 mSystemAllowGeolocationOrigins = null;
730 }
731
732 protected boolean isActivityPaused() {
733 return mActivityPaused;
734 }
735
736 protected void onLowMemory() {
737 mTabControl.freeMemory();
738 }
739
740 @Override
741 public boolean shouldShowErrorConsole() {
742 return mShouldShowErrorConsole;
743 }
744
745 protected void setShouldShowErrorConsole(boolean show) {
746 if (show == mShouldShowErrorConsole) {
747 // Nothing to do.
748 return;
749 }
750 mShouldShowErrorConsole = show;
751 Tab t = mTabControl.getCurrentTab();
752 if (t == null) {
753 // There is no current tab so we cannot toggle the error console
754 return;
755 }
756 mUi.setShouldShowErrorConsole(t, show);
757 }
758
759 @Override
760 public void stopLoading() {
761 mLoadStopped = true;
762 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700763 WebView w = getCurrentTopWebView();
764 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700765 mUi.onPageStopped(tab);
766 }
767
768 boolean didUserStopLoading() {
769 return mLoadStopped;
770 }
771
772 // WebViewController
773
774 @Override
John Reck324d4402011-01-11 16:56:42 -0800775 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700776
777 // We've started to load a new page. If there was a pending message
778 // to save a screenshot then we will now take the new page and save
779 // an incorrect screenshot. Therefore, remove any pending thumbnail
780 // messages from the queue.
781 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800782 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700783
784 // reset sync timer to avoid sync starts during loading a page
785 CookieSyncManager.getInstance().resetSync();
786
787 if (!mNetworkHandler.isNetworkUp()) {
788 view.setNetworkAvailable(false);
789 }
790
791 // when BrowserActivity just starts, onPageStarted may be called before
792 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
793 // to start the timer. As we won't switch tabs while an activity is in
794 // pause state, we can ensure calling resume and pause in pair.
795 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800796 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700797 }
798 mLoadStopped = false;
799 if (!mNetworkHandler.isNetworkUp()) {
800 mNetworkHandler.createAndShowNetworkDialog();
801 }
802 endActionMode();
803
John Reck30c714c2010-12-16 17:30:34 -0800804 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700805
John Reck324d4402011-01-11 16:56:42 -0800806 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700807 // update the bookmark database for favicon
808 maybeUpdateFavicon(tab, null, url, favicon);
809
810 Performance.tracePageStart(url);
811
812 // Performance probe
813 if (false) {
814 Performance.onPageStarted();
815 }
816
817 }
818
819 @Override
John Reck324d4402011-01-11 16:56:42 -0800820 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800821 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800822 if (!tab.isPrivateBrowsingEnabled()
John Reckd8c74522011-06-14 08:45:00 -0700823 && !TextUtils.isEmpty(tab.getUrl())
824 && !tab.isSnapshot()) {
John Recka1696282011-07-08 14:10:37 -0700825 // Only update the bookmark screenshot if the user did not
826 // cancel the load early and there is not already
827 // a pending update for the tab.
Michael Kolb8233fac2010-10-26 16:08:53 -0700828 if (tab.inForeground() && !didUserStopLoading()
829 || !tab.inForeground()) {
John Recka1696282011-07-08 14:10:37 -0700830 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
831 mHandler.sendMessageDelayed(mHandler.obtainMessage(
832 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
833 500);
834 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700835 }
836 }
837 // pause the WebView timer and release the wake lock if it is finished
838 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800839 if (mActivityPaused && pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700840 releaseWakeLock();
Michael Kolb8233fac2010-10-26 16:08:53 -0700841 }
Martijn Coenenb2f93552011-06-14 10:48:35 +0200842
Michael Kolb8233fac2010-10-26 16:08:53 -0700843 // Performance probe
844 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800845 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700846 }
847
848 Performance.tracePageFinished();
849 }
850
851 @Override
John Reck30c714c2010-12-16 17:30:34 -0800852 public void onProgressChanged(Tab tab) {
John Reck6c2e2f32011-08-22 13:41:23 -0700853 mCrashRecoveryHandler.backupState();
John Reck30c714c2010-12-16 17:30:34 -0800854 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700855
856 if (newProgress == 100) {
857 CookieSyncManager.getInstance().sync();
858 // onProgressChanged() may continue to be called after the main
859 // frame has finished loading, as any remaining sub frames continue
860 // to load. We'll only get called once though with newProgress as
861 // 100 when everything is loaded. (onPageFinished is called once
862 // when the main frame completes loading regardless of the state of
863 // any sub frames so calls to onProgressChanges may continue after
864 // onPageFinished has executed)
865 if (mInLoad) {
866 mInLoad = false;
867 updateInLoadMenuItems(mCachedMenu);
868 }
869 } else {
870 if (!mInLoad) {
871 // onPageFinished may have already been called but a subframe is
872 // still loading and updating the progress. Reset mInLoad and
873 // update the menu items.
874 mInLoad = true;
875 updateInLoadMenuItems(mCachedMenu);
876 }
877 }
John Reck30c714c2010-12-16 17:30:34 -0800878 mUi.onProgressChanged(tab);
879 }
880
881 @Override
882 public void onUpdatedLockIcon(Tab tab) {
883 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700884 }
885
886 @Override
887 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800888 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800889 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800890 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700891 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
892 return;
893 }
894 // Update the title in the history database if not in private browsing mode
895 if (!tab.isPrivateBrowsingEnabled()) {
John Reckf57c0292011-07-21 18:15:39 -0700896 DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700897 }
898 }
899
900 @Override
901 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800902 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700903 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
904 }
905
906 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800907 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
908 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700909 }
910
911 @Override
912 public boolean shouldOverrideKeyEvent(KeyEvent event) {
913 if (mMenuIsDown) {
914 // only check shortcut key when MENU is held
915 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
916 event);
917 } else {
918 return false;
919 }
920 }
921
922 @Override
923 public void onUnhandledKeyEvent(KeyEvent event) {
924 if (!isActivityPaused()) {
925 if (event.getAction() == KeyEvent.ACTION_DOWN) {
926 mActivity.onKeyDown(event.getKeyCode(), event);
927 } else {
928 mActivity.onKeyUp(event.getKeyCode(), event);
929 }
930 }
931 }
932
933 @Override
John Reck324d4402011-01-11 16:56:42 -0800934 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700935 // Don't save anything in private browsing mode
936 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800937 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700938
John Reck324d4402011-01-11 16:56:42 -0800939 if (TextUtils.isEmpty(url)
940 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700941 return;
942 }
John Reckf57c0292011-07-21 18:15:39 -0700943 DataController.getInstance(mActivity).updateVisitedHistory(url);
John Reck6c2e2f32011-08-22 13:41:23 -0700944 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -0700945 }
946
947 @Override
948 public void getVisitedHistory(final ValueCallback<String[]> callback) {
949 AsyncTask<Void, Void, String[]> task =
950 new AsyncTask<Void, Void, String[]>() {
951 @Override
952 public String[] doInBackground(Void... unused) {
953 return Browser.getVisitedHistory(mActivity.getContentResolver());
954 }
955 @Override
956 public void onPostExecute(String[] result) {
957 callback.onReceiveValue(result);
958 }
959 };
960 task.execute();
961 }
962
963 @Override
964 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
965 final HttpAuthHandler handler, final String host,
966 final String realm) {
967 String username = null;
968 String password = null;
969
970 boolean reuseHttpAuthUsernamePassword
971 = handler.useHttpAuthUsernamePassword();
972
973 if (reuseHttpAuthUsernamePassword && view != null) {
974 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
975 if (credentials != null && credentials.length == 2) {
976 username = credentials[0];
977 password = credentials[1];
978 }
979 }
980
981 if (username != null && password != null) {
982 handler.proceed(username, password);
983 } else {
Ben Murdochfdd37112011-08-05 15:48:14 +0100984 if (tab.inForeground() && !handler.suppressDialog()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700985 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
986 } else {
987 handler.cancel();
988 }
989 }
990 }
991
992 @Override
993 public void onDownloadStart(Tab tab, String url, String userAgent,
994 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000995 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -0500996 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000997 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
998 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700999 // This Tab was opened for the sole purpose of downloading a
1000 // file. Remove it.
1001 if (tab == mTabControl.getCurrentTab()) {
1002 // In this case, the Tab is still on top.
1003 goBackOnePageOrQuit();
1004 } else {
1005 // In this case, it is not.
1006 closeTab(tab);
1007 }
1008 }
1009 }
1010
1011 @Override
1012 public Bitmap getDefaultVideoPoster() {
1013 return mUi.getDefaultVideoPoster();
1014 }
1015
1016 @Override
1017 public View getVideoLoadingProgressView() {
1018 return mUi.getVideoLoadingProgressView();
1019 }
1020
1021 @Override
1022 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1023 SslError error) {
1024 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1025 }
1026
Patrick Scott92066772011-03-10 08:46:27 -05001027 @Override
1028 public void showAutoLogin(Tab tab) {
1029 assert tab.inForeground();
1030 // Update the title bar to show the auto-login request.
1031 mUi.showAutoLogin(tab);
1032 }
1033
1034 @Override
1035 public void hideAutoLogin(Tab tab) {
1036 assert tab.inForeground();
1037 mUi.hideAutoLogin(tab);
1038 }
1039
Michael Kolb8233fac2010-10-26 16:08:53 -07001040 // helper method
1041
1042 /*
1043 * Update the favorites icon if the private browsing isn't enabled and the
1044 * icon is valid.
1045 */
1046 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1047 final String url, Bitmap favicon) {
1048 if (favicon == null) {
1049 return;
1050 }
1051 if (!tab.isPrivateBrowsingEnabled()) {
1052 Bookmarks.updateFavicon(mActivity
1053 .getContentResolver(), originalUrl, url, favicon);
1054 }
1055 }
1056
Leon Scroggins4cd97792010-12-03 15:31:56 -05001057 @Override
1058 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001059 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001060 mUi.bookmarkedStatusHasChanged(tab);
1061 }
1062
Michael Kolb8233fac2010-10-26 16:08:53 -07001063 // end WebViewController
1064
1065 protected void pageUp() {
1066 getCurrentTopWebView().pageUp(false);
1067 }
1068
1069 protected void pageDown() {
1070 getCurrentTopWebView().pageDown(false);
1071 }
1072
1073 // callback from phone title bar
1074 public void editUrl() {
1075 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001076 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001077 }
1078
Michael Kolbcfa3af52010-12-14 10:36:11 -08001079 public void startVoiceSearch() {
1080 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1081 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1082 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1083 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1084 mActivity.getComponentName().flattenToString());
1085 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001086 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001087 mActivity.startActivity(intent);
1088 }
1089
Michael Kolb11d19782011-03-20 10:17:40 -07001090 @Override
1091 public void activateVoiceSearchMode(String title, List<String> results) {
1092 mUi.showVoiceTitleBar(title, results);
Michael Kolb8233fac2010-10-26 16:08:53 -07001093 }
1094
1095 public void revertVoiceSearchMode(Tab tab) {
1096 mUi.revertVoiceTitleBar(tab);
1097 }
1098
Michael Kolb736990c2011-03-20 10:01:20 -07001099 public boolean supportsVoiceSearch() {
John Reck35e9dd62011-04-25 09:01:54 -07001100 SearchEngine searchEngine = getSettings().getSearchEngine();
Michael Kolb736990c2011-03-20 10:01:20 -07001101 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1102 }
1103
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001104 public void showCustomView(Tab tab, View view, int requestedOrientation,
Michael Kolb8233fac2010-10-26 16:08:53 -07001105 WebChromeClient.CustomViewCallback callback) {
1106 if (tab.inForeground()) {
1107 if (mUi.isCustomViewShowing()) {
1108 callback.onCustomViewHidden();
1109 return;
1110 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001111 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001112 // Save the menu state and set it to empty while the custom
1113 // view is showing.
1114 mOldMenuState = mMenuState;
1115 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001116 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001117 }
1118 }
1119
1120 @Override
1121 public void hideCustomView() {
1122 if (mUi.isCustomViewShowing()) {
1123 mUi.onHideCustomView();
1124 // Reset the old menu state.
1125 mMenuState = mOldMenuState;
1126 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001127 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001128 }
1129 }
1130
1131 protected void onActivityResult(int requestCode, int resultCode,
1132 Intent intent) {
1133 if (getCurrentTopWebView() == null) return;
1134 switch (requestCode) {
1135 case PREFERENCES_PAGE:
1136 if (resultCode == Activity.RESULT_OK && intent != null) {
1137 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001138 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001139 mTabControl.removeParentChildRelationShips();
1140 }
1141 }
1142 break;
1143 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001144 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001145 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001146 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001147 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001148 case AUTOFILL_SETUP:
1149 // Determine whether a profile was actually set up or not
1150 // and if so, send the message back to the WebTextView to
1151 // fill the form with the new profile.
1152 if (getSettings().getAutoFillProfile() != null) {
1153 mAutoFillSetupMessage.sendToTarget();
1154 mAutoFillSetupMessage = null;
1155 }
1156 break;
John Reckd3e4d5b2011-07-13 15:48:43 -07001157 case COMBO_VIEW:
1158 if (intent == null || resultCode != Activity.RESULT_OK) {
1159 break;
1160 }
John Reck3ba45532011-08-11 16:26:53 -07001161 mUi.showWeb(false);
John Reckd3e4d5b2011-07-13 15:48:43 -07001162 if (Intent.ACTION_VIEW.equals(intent.getAction())) {
1163 Tab t = getCurrentTab();
1164 Uri uri = intent.getData();
1165 loadUrl(t, uri.toString());
1166 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
1167 String[] urls = intent.getStringArrayExtra(
1168 ComboViewActivity.EXTRA_OPEN_ALL);
1169 Tab parent = getCurrentTab();
1170 for (String url : urls) {
1171 parent = openTab(url, parent,
1172 !mSettings.openInBackground(), true);
1173 }
1174 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
1175 long id = intent.getLongExtra(
1176 ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
1177 if (id >= 0) {
1178 createNewSnapshotTab(id, true);
1179 }
1180 }
1181 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001182 default:
1183 break;
1184 }
1185 getCurrentTopWebView().requestFocus();
1186 }
1187
1188 /**
1189 * Open the Go page.
1190 * @param startWithHistory If true, open starting on the history tab.
1191 * Otherwise, start with the bookmarks tab.
1192 */
1193 @Override
1194 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1195 if (mTabControl.getCurrentWebView() == null) {
1196 return;
1197 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001198 // clear action mode
1199 if (isInCustomActionMode()) {
1200 endActionMode();
1201 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001202 Bundle extras = new Bundle();
1203 // Disable opening in a new window if we have maxed out the windows
1204 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1205 !mTabControl.canCreateNewTab());
John Reck2bc80422011-06-30 15:11:49 -07001206 mUi.showComboView(startWithHistory
1207 ? ComboViews.History : ComboViews.Bookmarks, extras);
Michael Kolb8233fac2010-10-26 16:08:53 -07001208 }
1209
1210 // combo view callbacks
1211
1212 /**
1213 * callback from ComboPage when clear history is requested
1214 */
1215 public void onRemoveParentChildRelationships() {
1216 mTabControl.removeParentChildRelationShips();
1217 }
1218
Michael Kolb8233fac2010-10-26 16:08:53 -07001219 // key handling
1220 protected void onBackKey() {
1221 if (!mUi.onBackKey()) {
1222 WebView subwindow = mTabControl.getCurrentSubWindow();
1223 if (subwindow != null) {
1224 if (subwindow.canGoBack()) {
1225 subwindow.goBack();
1226 } else {
1227 dismissSubWindow(mTabControl.getCurrentTab());
1228 }
1229 } else {
1230 goBackOnePageOrQuit();
1231 }
1232 }
1233 }
1234
Michael Kolb4bd767d2011-05-27 11:33:55 -07001235 protected boolean onMenuKey() {
1236 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001237 }
1238
Michael Kolb8233fac2010-10-26 16:08:53 -07001239 // menu handling and state
1240 // TODO: maybe put into separate handler
1241
1242 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckd73c5a22010-12-22 10:22:50 -08001243 if (mMenuState == EMPTY_MENU) {
1244 return false;
1245 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001246 MenuInflater inflater = mActivity.getMenuInflater();
1247 inflater.inflate(R.menu.browser, menu);
1248 updateInLoadMenuItems(menu);
1249 // hold on to the menu reference here; it is used by the page callbacks
1250 // to update the menu based on loading state
1251 mCachedMenu = menu;
1252 return true;
1253 }
1254
1255 protected void onCreateContextMenu(ContextMenu menu, View v,
1256 ContextMenuInfo menuInfo) {
John Reck0f602f32011-07-07 15:38:43 -07001257 if (v instanceof TitleBar) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001258 return;
1259 }
1260 if (!(v instanceof WebView)) {
1261 return;
1262 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001263 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001264 WebView.HitTestResult result = webview.getHitTestResult();
1265 if (result == null) {
1266 return;
1267 }
1268
1269 int type = result.getType();
1270 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1271 Log.w(LOGTAG,
1272 "We should not show context menu when nothing is touched");
1273 return;
1274 }
1275 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1276 // let TextView handles context menu
1277 return;
1278 }
1279
1280 // Note, http://b/issue?id=1106666 is requesting that
1281 // an inflated menu can be used again. This is not available
1282 // yet, so inflate each time (yuk!)
1283 MenuInflater inflater = mActivity.getMenuInflater();
1284 inflater.inflate(R.menu.browsercontext, menu);
1285
1286 // Show the correct menu group
1287 final String extra = result.getExtra();
1288 menu.setGroupVisible(R.id.PHONE_MENU,
1289 type == WebView.HitTestResult.PHONE_TYPE);
1290 menu.setGroupVisible(R.id.EMAIL_MENU,
1291 type == WebView.HitTestResult.EMAIL_TYPE);
1292 menu.setGroupVisible(R.id.GEO_MENU,
1293 type == WebView.HitTestResult.GEO_TYPE);
1294 menu.setGroupVisible(R.id.IMAGE_MENU,
1295 type == WebView.HitTestResult.IMAGE_TYPE
1296 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1297 menu.setGroupVisible(R.id.ANCHOR_MENU,
1298 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1299 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001300 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1301 || type == WebView.HitTestResult.PHONE_TYPE
1302 || type == WebView.HitTestResult.EMAIL_TYPE
1303 || type == WebView.HitTestResult.GEO_TYPE;
1304 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1305 if (hitText) {
1306 menu.findItem(R.id.select_text_menu_id)
1307 .setOnMenuItemClickListener(new SelectText(webview));
1308 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001309 // Setup custom handling depending on the type
1310 switch (type) {
1311 case WebView.HitTestResult.PHONE_TYPE:
1312 menu.setHeaderTitle(Uri.decode(extra));
1313 menu.findItem(R.id.dial_context_menu_id).setIntent(
1314 new Intent(Intent.ACTION_VIEW, Uri
1315 .parse(WebView.SCHEME_TEL + extra)));
1316 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1317 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1318 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1319 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1320 addIntent);
1321 menu.findItem(R.id.copy_phone_context_menu_id)
1322 .setOnMenuItemClickListener(
1323 new Copy(extra));
1324 break;
1325
1326 case WebView.HitTestResult.EMAIL_TYPE:
1327 menu.setHeaderTitle(extra);
1328 menu.findItem(R.id.email_context_menu_id).setIntent(
1329 new Intent(Intent.ACTION_VIEW, Uri
1330 .parse(WebView.SCHEME_MAILTO + extra)));
1331 menu.findItem(R.id.copy_mail_context_menu_id)
1332 .setOnMenuItemClickListener(
1333 new Copy(extra));
1334 break;
1335
1336 case WebView.HitTestResult.GEO_TYPE:
1337 menu.setHeaderTitle(extra);
1338 menu.findItem(R.id.map_context_menu_id).setIntent(
1339 new Intent(Intent.ACTION_VIEW, Uri
1340 .parse(WebView.SCHEME_GEO
1341 + URLEncoder.encode(extra))));
1342 menu.findItem(R.id.copy_geo_context_menu_id)
1343 .setOnMenuItemClickListener(
1344 new Copy(extra));
1345 break;
1346
1347 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1348 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001349 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001350 // decide whether to show the open link in new tab option
1351 boolean showNewTab = mTabControl.canCreateNewTab();
1352 MenuItem newTabItem
1353 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001354 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001355 ? R.string.contextmenu_openlink_newwindow_background
1356 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001357 newTabItem.setVisible(showNewTab);
1358 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001359 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1360 newTabItem.setOnMenuItemClickListener(
1361 new MenuItem.OnMenuItemClickListener() {
1362 @Override
1363 public boolean onMenuItemClick(MenuItem item) {
1364 final HashMap<String, WebView> hrefMap =
1365 new HashMap<String, WebView>();
1366 hrefMap.put("webview", webview);
1367 final Message msg = mHandler.obtainMessage(
1368 FOCUS_NODE_HREF,
1369 R.id.open_newtab_context_menu_id,
1370 0, hrefMap);
1371 webview.requestFocusNodeHref(msg);
1372 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001373 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001374 });
1375 } else {
1376 newTabItem.setOnMenuItemClickListener(
1377 new MenuItem.OnMenuItemClickListener() {
1378 @Override
1379 public boolean onMenuItemClick(MenuItem item) {
1380 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001381 openTab(extra, parent,
1382 !mSettings.openInBackground(),
1383 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001384 return true;
1385 }
1386 });
1387 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001388 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001389 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1390 break;
1391 }
1392 // otherwise fall through to handle image part
1393 case WebView.HitTestResult.IMAGE_TYPE:
1394 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1395 menu.setHeaderTitle(extra);
1396 }
1397 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1398 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1399 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001400 setOnMenuItemClickListener(
1401 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001402 menu.findItem(R.id.set_wallpaper_context_menu_id).
1403 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1404 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001405 break;
1406
1407 default:
1408 Log.w(LOGTAG, "We should not get here.");
1409 break;
1410 }
1411 //update the ui
1412 mUi.onContextMenuCreated(menu);
1413 }
1414
1415 /**
1416 * As the menu can be open when loading state changes
1417 * we must manually update the state of the stop/reload menu
1418 * item
1419 */
1420 private void updateInLoadMenuItems(Menu menu) {
1421 if (menu == null) {
1422 return;
1423 }
1424 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1425 MenuItem src = mInLoad ?
1426 menu.findItem(R.id.stop_menu_id):
1427 menu.findItem(R.id.reload_menu_id);
1428 if (src != null) {
1429 dest.setIcon(src.getIcon());
1430 dest.setTitle(src.getTitle());
1431 }
1432 }
1433
John Reckb3417f02011-01-14 11:01:05 -08001434 boolean onPrepareOptionsMenu(Menu menu) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001435 // Note: setVisible will decide whether an item is visible; while
1436 // setEnabled() will decide whether an item is enabled, which also means
1437 // whether the matching shortcut key will function.
1438 switch (mMenuState) {
1439 case EMPTY_MENU:
1440 if (mCurrentMenuState != mMenuState) {
1441 menu.setGroupVisible(R.id.MAIN_MENU, false);
1442 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1443 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1444 }
1445 break;
1446 default:
1447 if (mCurrentMenuState != mMenuState) {
1448 menu.setGroupVisible(R.id.MAIN_MENU, true);
1449 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1450 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1451 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001452 updateMenuState(getCurrentTab(), menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001453 break;
1454 }
1455 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001456 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001457 }
1458
Michael Kolb4bf79712011-07-14 14:18:12 -07001459 @Override
1460 public void updateMenuState(Tab tab, Menu menu) {
1461 boolean canGoBack = false;
1462 boolean canGoForward = false;
1463 boolean isHome = false;
John Reck42229bc2011-08-19 13:26:43 -07001464 boolean isDesktopUa = false;
Michael Kolb4bf79712011-07-14 14:18:12 -07001465 if (tab != null) {
1466 canGoBack = tab.canGoBack();
1467 canGoForward = tab.canGoForward();
1468 isHome = mSettings.getHomePage().equals(tab.getUrl());
John Reck42229bc2011-08-19 13:26:43 -07001469 isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
Michael Kolb4bf79712011-07-14 14:18:12 -07001470 }
1471 final MenuItem back = menu.findItem(R.id.back_menu_id);
1472 back.setEnabled(canGoBack);
1473
1474 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1475 home.setEnabled(!isHome);
1476
1477 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1478 forward.setEnabled(canGoForward);
1479
1480 final MenuItem source = menu.findItem(mInLoad ? R.id.stop_menu_id : R.id.reload_menu_id);
1481 final MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolb7ab75ee2011-07-14 16:36:38 -07001482 if (source != null && dest != null) {
1483 dest.setTitle(source.getTitle());
1484 dest.setIcon(source.getIcon());
1485 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001486
1487 // decide whether to show the share link option
1488 PackageManager pm = mActivity.getPackageManager();
1489 Intent send = new Intent(Intent.ACTION_SEND);
1490 send.setType("text/plain");
1491 ResolveInfo ri = pm.resolveActivity(send,
1492 PackageManager.MATCH_DEFAULT_ONLY);
1493 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1494
1495 boolean isNavDump = mSettings.enableNavDump();
1496 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1497 nav.setVisible(isNavDump);
1498 nav.setEnabled(isNavDump);
1499
1500 boolean showDebugSettings = mSettings.isDebugEnabled();
1501 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1502 counter.setVisible(showDebugSettings);
1503 counter.setEnabled(showDebugSettings);
John Reck42229bc2011-08-19 13:26:43 -07001504 final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
1505 uaSwitcher.setChecked(isDesktopUa);
Michael Kolb4bf79712011-07-14 14:18:12 -07001506
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001507 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001508 }
1509
Michael Kolb8233fac2010-10-26 16:08:53 -07001510 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001511 if (null == getCurrentTopWebView()) {
1512 return false;
1513 }
1514 if (mMenuIsDown) {
1515 // The shortcut action consumes the MENU. Even if it is still down,
1516 // it won't trigger the next shortcut action. In the case of the
1517 // shortcut action triggering a new activity, like Bookmarks, we
1518 // won't get onKeyUp for MENU. So it is important to reset it here.
1519 mMenuIsDown = false;
1520 }
Michael Kolb3ca12752011-07-20 13:52:25 -07001521 if (mUi.onOptionsItemSelected(item)) {
1522 // ui callback handled it
1523 return true;
1524 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001525 switch (item.getItemId()) {
1526 // -- Main menu
1527 case R.id.new_tab_menu_id:
1528 openTabToHomePage();
1529 break;
1530
1531 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001532 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001533 break;
1534
1535 case R.id.goto_menu_id:
1536 editUrl();
1537 break;
1538
1539 case R.id.bookmarks_menu_id:
1540 bookmarksOrHistoryPicker(false);
1541 break;
1542
Michael Kolb8233fac2010-10-26 16:08:53 -07001543 case R.id.add_bookmark_menu_id:
John Reckd3e4d5b2011-07-13 15:48:43 -07001544 mActivity.startActivity(createBookmarkCurrentPageIntent(false));
Michael Kolb8233fac2010-10-26 16:08:53 -07001545 break;
1546
1547 case R.id.stop_reload_menu_id:
1548 if (mInLoad) {
1549 stopLoading();
1550 } else {
1551 getCurrentTopWebView().reload();
1552 }
1553 break;
1554
1555 case R.id.back_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001556 getCurrentTab().goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07001557 break;
1558
1559 case R.id.forward_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001560 getCurrentTab().goForward();
Michael Kolb8233fac2010-10-26 16:08:53 -07001561 break;
1562
1563 case R.id.close_menu_id:
1564 // Close the subwindow if it exists.
1565 if (mTabControl.getCurrentSubWindow() != null) {
1566 dismissSubWindow(mTabControl.getCurrentTab());
1567 break;
1568 }
1569 closeCurrentTab();
1570 break;
1571
1572 case R.id.homepage_menu_id:
1573 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07001574 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07001575 break;
1576
1577 case R.id.preferences_menu_id:
1578 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1579 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1580 getCurrentTopWebView().getUrl());
1581 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1582 break;
1583
1584 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001585 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001586 break;
1587
John Reck2bc80422011-06-30 15:11:49 -07001588 case R.id.save_snapshot_menu_id:
1589 final Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07001590 if (source == null) break;
John Reckd8c74522011-06-14 08:45:00 -07001591 final ContentResolver cr = mActivity.getContentResolver();
1592 final ContentValues values = source.createSnapshotValues();
John Reck2bc80422011-06-30 15:11:49 -07001593 if (values != null) {
1594 new AsyncTask<Tab, Void, Long>() {
John Reckd8c74522011-06-14 08:45:00 -07001595
John Reck2bc80422011-06-30 15:11:49 -07001596 @Override
1597 protected Long doInBackground(Tab... params) {
1598 Uri result = cr.insert(Snapshots.CONTENT_URI, values);
1599 long id = ContentUris.parseId(result);
1600 return id;
John Reckd8c74522011-06-14 08:45:00 -07001601 }
John Reckf33b1632011-06-04 20:00:23 -07001602
John Reck2bc80422011-06-30 15:11:49 -07001603 @Override
1604 protected void onPostExecute(Long id) {
1605 Bundle b = new Bundle();
1606 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
1607 mUi.showComboView(ComboViews.Snapshots, b);
1608 };
1609 }.execute(source);
1610 } else {
1611 Toast.makeText(mActivity, R.string.snapshot_failed,
Leon Scrogginsac993842011-02-02 12:54:07 -05001612 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001613 }
Leon Scrogginsac993842011-02-02 12:54:07 -05001614 break;
1615
Michael Kolb8233fac2010-10-26 16:08:53 -07001616 case R.id.page_info_menu_id:
Huahui Wuae0c0412011-06-28 10:17:05 -07001617 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001618 break;
1619
1620 case R.id.classic_history_menu_id:
1621 bookmarksOrHistoryPicker(true);
1622 break;
1623
Michael Kolb8233fac2010-10-26 16:08:53 -07001624 case R.id.share_page_menu_id:
1625 Tab currentTab = mTabControl.getCurrentTab();
1626 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001627 return false;
1628 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001629 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001630 break;
1631
1632 case R.id.dump_nav_menu_id:
1633 getCurrentTopWebView().debugDump();
1634 break;
1635
1636 case R.id.dump_counters_menu_id:
1637 getCurrentTopWebView().dumpV8Counters();
1638 break;
1639
1640 case R.id.zoom_in_menu_id:
1641 getCurrentTopWebView().zoomIn();
1642 break;
1643
1644 case R.id.zoom_out_menu_id:
1645 getCurrentTopWebView().zoomOut();
1646 break;
1647
1648 case R.id.view_downloads_menu_id:
1649 viewDownloads();
1650 break;
1651
John Reck42229bc2011-08-19 13:26:43 -07001652 case R.id.ua_desktop_menu_id:
1653 WebView web = getCurrentWebView();
1654 mSettings.toggleDesktopUseragent(web);
1655 web.loadUrl(web.getOriginalUrl());
1656 break;
1657
Michael Kolb8233fac2010-10-26 16:08:53 -07001658 case R.id.window_one_menu_id:
1659 case R.id.window_two_menu_id:
1660 case R.id.window_three_menu_id:
1661 case R.id.window_four_menu_id:
1662 case R.id.window_five_menu_id:
1663 case R.id.window_six_menu_id:
1664 case R.id.window_seven_menu_id:
1665 case R.id.window_eight_menu_id:
1666 {
1667 int menuid = item.getItemId();
1668 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1669 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1670 Tab desiredTab = mTabControl.getTab(id);
1671 if (desiredTab != null &&
1672 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001673 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001674 }
1675 break;
1676 }
1677 }
1678 }
1679 break;
1680
1681 default:
1682 return false;
1683 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001684 return true;
1685 }
1686
1687 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001688 // Let the History and Bookmark fragments handle menus they created.
1689 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1690 return false;
1691 }
1692
Michael Kolb8233fac2010-10-26 16:08:53 -07001693 int id = item.getItemId();
1694 boolean result = true;
1695 switch (id) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001696 // -- Browser context menu
1697 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001698 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001699 case R.id.copy_link_context_menu_id:
1700 final WebView webView = getCurrentTopWebView();
1701 if (null == webView) {
1702 result = false;
1703 break;
1704 }
1705 final HashMap<String, WebView> hrefMap =
1706 new HashMap<String, WebView>();
1707 hrefMap.put("webview", webView);
1708 final Message msg = mHandler.obtainMessage(
1709 FOCUS_NODE_HREF, id, 0, hrefMap);
1710 webView.requestFocusNodeHref(msg);
1711 break;
1712
1713 default:
1714 // For other context menus
1715 result = onOptionsItemSelected(item);
1716 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001717 return result;
1718 }
1719
1720 /**
1721 * support programmatically opening the context menu
1722 */
1723 public void openContextMenu(View view) {
1724 mActivity.openContextMenu(view);
1725 }
1726
1727 /**
1728 * programmatically open the options menu
1729 */
1730 public void openOptionsMenu() {
1731 mActivity.openOptionsMenu();
1732 }
1733
1734 public boolean onMenuOpened(int featureId, Menu menu) {
1735 if (mOptionsMenuOpen) {
1736 if (mConfigChanged) {
1737 // We do not need to make any changes to the state of the
1738 // title bar, since the only thing that happened was a
1739 // change in orientation
1740 mConfigChanged = false;
1741 } else {
1742 if (!mExtendedMenuOpen) {
1743 mExtendedMenuOpen = true;
1744 mUi.onExtendedMenuOpened();
1745 } else {
1746 // Switching the menu back to icon view, so show the
1747 // title bar once again.
1748 mExtendedMenuOpen = false;
1749 mUi.onExtendedMenuClosed(mInLoad);
Michael Kolb8233fac2010-10-26 16:08:53 -07001750 }
1751 }
1752 } else {
1753 // The options menu is closed, so open it, and show the title
1754 mOptionsMenuOpen = true;
1755 mConfigChanged = false;
1756 mExtendedMenuOpen = false;
1757 mUi.onOptionsMenuOpened();
1758 }
1759 return true;
1760 }
1761
1762 public void onOptionsMenuClosed(Menu menu) {
1763 mOptionsMenuOpen = false;
1764 mUi.onOptionsMenuClosed(mInLoad);
1765 }
1766
1767 public void onContextMenuClosed(Menu menu) {
1768 mUi.onContextMenuClosed(menu, mInLoad);
1769 }
1770
1771 // Helper method for getting the top window.
1772 @Override
1773 public WebView getCurrentTopWebView() {
1774 return mTabControl.getCurrentTopWebView();
1775 }
1776
1777 @Override
1778 public WebView getCurrentWebView() {
1779 return mTabControl.getCurrentWebView();
1780 }
1781
1782 /*
1783 * This method is called as a result of the user selecting the options
1784 * menu to see the download window. It shows the download window on top of
1785 * the current window.
1786 */
1787 void viewDownloads() {
1788 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1789 mActivity.startActivity(intent);
1790 }
1791
John Reck30b065e2011-07-19 10:58:05 -07001792 int getActionModeHeight() {
1793 TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
1794 new int[] { android.R.attr.actionBarSize });
1795 int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
1796 actionBarSizeTypedArray.recycle();
1797 return size;
1798 }
1799
Michael Kolb8233fac2010-10-26 16:08:53 -07001800 // action mode
1801
1802 void onActionModeStarted(ActionMode mode) {
1803 mUi.onActionModeStarted(mode);
1804 mActionMode = mode;
Michael Kolb42c0c062011-08-02 12:56:06 -07001805 if (mSimulateActionBarOverlayMode && !mUi.isEditingUrl()) {
John Reck30b065e2011-07-19 10:58:05 -07001806 WebView web = getCurrentWebView();
1807 // Simulate overlay mode by scrolling the webview the amount it will be
1808 // pushed down. Actual overlay mode doesn't work for us as otherwise
1809 // the CAB will, well, overlay the content, which breaks things like
1810 // find on page.
1811 int scrollBy = getActionModeHeight();
1812 web.scrollBy(0, scrollBy);
1813 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001814 }
1815
1816 /*
1817 * True if a custom ActionMode (i.e. find or select) is in use.
1818 */
1819 @Override
1820 public boolean isInCustomActionMode() {
1821 return mActionMode != null;
1822 }
1823
1824 /*
1825 * End the current ActionMode.
1826 */
1827 @Override
1828 public void endActionMode() {
1829 if (mActionMode != null) {
1830 mActionMode.finish();
1831 }
1832 }
1833
1834 /*
1835 * Called by find and select when they are finished. Replace title bars
1836 * as necessary.
1837 */
1838 public void onActionModeFinished(ActionMode mode) {
1839 if (!isInCustomActionMode()) return;
1840 mUi.onActionModeFinished(mInLoad);
1841 mActionMode = null;
John Reck30b065e2011-07-19 10:58:05 -07001842 if (mSimulateActionBarOverlayMode) {
1843 WebView web = getCurrentWebView();
1844 int scrollBy = getActionModeHeight();
1845 web.scrollBy(0, -scrollBy);
1846 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001847 }
1848
1849 boolean isInLoad() {
1850 return mInLoad;
1851 }
1852
1853 // bookmark handling
1854
1855 /**
1856 * add the current page as a bookmark to the given folder id
1857 * @param folderId use -1 for the default folder
John Reckd3e4d5b2011-07-13 15:48:43 -07001858 * @param editExisting If true, check to see whether the site is already
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001859 * bookmarked, and if it is, edit that bookmark. If false, and
1860 * the site is already bookmarked, do not attempt to edit the
1861 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001862 */
1863 @Override
John Reckd3e4d5b2011-07-13 15:48:43 -07001864 public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001865 Intent i = new Intent(mActivity,
1866 AddBookmarkPage.class);
1867 WebView w = getCurrentTopWebView();
1868 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1869 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1870 String touchIconUrl = w.getTouchIconUrl();
1871 if (touchIconUrl != null) {
1872 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1873 WebSettings settings = w.getSettings();
1874 if (settings != null) {
1875 i.putExtra(AddBookmarkPage.USER_AGENT,
1876 settings.getUserAgentString());
1877 }
1878 }
1879 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1880 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1881 getDesiredThumbnailHeight(mActivity)));
1882 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07001883 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001884 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1885 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001886 // Put the dialog at the upper right of the screen, covering the
1887 // star on the title bar.
1888 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07001889 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07001890 }
1891
1892 // file chooser
1893 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1894 mUploadHandler = new UploadHandler(this);
1895 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1896 }
1897
1898 // thumbnails
1899
1900 /**
1901 * Return the desired width for thumbnail screenshots, which are stored in
1902 * the database, and used on the bookmarks screen.
1903 * @param context Context for finding out the density of the screen.
1904 * @return desired width for thumbnail screenshot.
1905 */
1906 static int getDesiredThumbnailWidth(Context context) {
1907 return context.getResources().getDimensionPixelOffset(
1908 R.dimen.bookmarkThumbnailWidth);
1909 }
1910
1911 /**
1912 * Return the desired height for thumbnail screenshots, which are stored in
1913 * the database, and used on the bookmarks screen.
1914 * @param context Context for finding out the density of the screen.
1915 * @return desired height for thumbnail screenshot.
1916 */
1917 static int getDesiredThumbnailHeight(Context context) {
1918 return context.getResources().getDimensionPixelOffset(
1919 R.dimen.bookmarkThumbnailHeight);
1920 }
1921
John Reck8cc92352011-07-06 17:41:52 -07001922 static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001923 // We render to a bitmap 2x the desired size so that we can then
1924 // re-scale it with filtering since canvas.scale doesn't filter
1925 // This helps reduce aliasing at the cost of being slightly blurry
1926 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001927 Picture thumbnail = view.capturePicture();
1928 if (thumbnail == null) {
1929 return null;
1930 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001931 width *= filter_scale;
1932 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001933 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1934 Canvas canvas = new Canvas(bm);
1935 // May need to tweak these values to determine what is the
1936 // best scale factor
1937 int thumbnailWidth = thumbnail.getWidth();
1938 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001939 float scaleFactor = 1.0f;
Michael Kolbeb95db42011-03-03 10:38:40 -08001940 if (thumbnailWidth > 0 && thumbnailHeight > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001941 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001942 } else {
1943 return null;
1944 }
John Reckfe49ab42010-11-16 17:09:37 -08001945
Michael Kolbeb95db42011-03-03 10:38:40 -08001946 float scaleFactorY = (float) height / (float)thumbnailHeight;
1947 if (scaleFactorY > scaleFactor) {
1948 // The picture is narrower than the requested AR
1949 // Center the thumnail and crop the sides
1950 scaleFactor = scaleFactorY;
John Reckfe49ab42010-11-16 17:09:37 -08001951 float wx = (thumbnailWidth * scaleFactor) - width;
1952 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001953 }
1954
John Reckfe49ab42010-11-16 17:09:37 -08001955 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001956
1957 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001958 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
1959 height / filter_scale, true);
Dianne Hackborn43cfe8a2011-08-02 16:59:35 -07001960 canvas.setBitmap(null);
John Reck5c6ac2f2011-01-05 10:18:03 -08001961 bm.recycle();
1962 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001963 }
1964
John Reck34ef2672011-02-10 11:30:55 -08001965 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001966 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07001967 // FIXME: Would like to make sure there is actually something to
1968 // draw, but the API for that (WebViewCore.pictureReady()) is not
1969 // currently accessible here.
1970
John Reck34ef2672011-02-10 11:30:55 -08001971 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08001972 if (view == null) {
1973 // Tab was destroyed
1974 return;
1975 }
John Reck34ef2672011-02-10 11:30:55 -08001976 final String url = tab.getUrl();
1977 final String originalUrl = view.getOriginalUrl();
1978
1979 if (TextUtils.isEmpty(url)) {
1980 return;
1981 }
1982
1983 // Only update thumbnails for web urls (http(s)://), not for
1984 // about:, javascript:, data:, etc...
1985 // Unless it is a bookmarked site, then always update
1986 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
1987 return;
1988 }
1989
Michael Kolb8233fac2010-10-26 16:08:53 -07001990 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1991 getDesiredThumbnailHeight(mActivity));
1992 if (bm == null) {
1993 return;
1994 }
1995
1996 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08001997 new AsyncTask<Void, Void, Void>() {
1998 @Override
1999 protected Void doInBackground(Void... unused) {
2000 Cursor cursor = null;
2001 try {
2002 // TODO: Clean this up
2003 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2004 if (cursor != null && cursor.moveToFirst()) {
2005 final ByteArrayOutputStream os =
2006 new ByteArrayOutputStream();
2007 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002008
John Reck34ef2672011-02-10 11:30:55 -08002009 ContentValues values = new ContentValues();
2010 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002011
John Reck34ef2672011-02-10 11:30:55 -08002012 do {
John Reck617fd832011-02-16 14:35:59 -08002013 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002014 cr.update(Images.CONTENT_URI, values, null, null);
2015 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002016 }
John Reck34ef2672011-02-10 11:30:55 -08002017 } catch (IllegalStateException e) {
2018 // Ignore
2019 } finally {
2020 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002021 }
John Reck34ef2672011-02-10 11:30:55 -08002022 return null;
2023 }
2024 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002025 }
2026
2027 private class Copy implements OnMenuItemClickListener {
2028 private CharSequence mText;
2029
2030 public boolean onMenuItemClick(MenuItem item) {
2031 copy(mText);
2032 return true;
2033 }
2034
2035 public Copy(CharSequence toCopy) {
2036 mText = toCopy;
2037 }
2038 }
2039
Leon Scroggins63c02662010-11-18 15:16:27 -05002040 private static class Download implements OnMenuItemClickListener {
2041 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002042 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002043 private boolean mPrivateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002044
2045 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002046 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002047 null, null, mPrivateBrowsing);
Michael Kolb8233fac2010-10-26 16:08:53 -07002048 return true;
2049 }
2050
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002051 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002052 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002053 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002054 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002055 }
2056 }
2057
Cary Clark8974d282010-11-22 10:46:05 -05002058 private static class SelectText implements OnMenuItemClickListener {
2059 private WebView mWebView;
2060
2061 public boolean onMenuItemClick(MenuItem item) {
2062 if (mWebView != null) {
2063 return mWebView.selectText();
2064 }
2065 return false;
2066 }
2067
2068 public SelectText(WebView webView) {
2069 mWebView = webView;
2070 }
2071
2072 }
2073
Michael Kolb8233fac2010-10-26 16:08:53 -07002074 /********************** TODO: UI stuff *****************************/
2075
2076 // these methods have been copied, they still need to be cleaned up
2077
2078 /****************** tabs ***************************************************/
2079
2080 // basic tab interactions:
2081
2082 // it is assumed that tabcontrol already knows about the tab
2083 protected void addTab(Tab tab) {
2084 mUi.addTab(tab);
2085 }
2086
2087 protected void removeTab(Tab tab) {
2088 mUi.removeTab(tab);
2089 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002090 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002091 }
2092
Michael Kolbf2055602011-04-09 17:20:03 -07002093 @Override
2094 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002095 // monkey protection against delayed start
2096 if (tab != null) {
2097 mTabControl.setCurrentTab(tab);
2098 // the tab is guaranteed to have a webview after setCurrentTab
2099 mUi.setActiveTab(tab);
2100 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002101 }
2102
2103 protected void closeEmptyChildTab() {
2104 Tab current = mTabControl.getCurrentTab();
2105 if (current != null
2106 && current.getWebView().copyBackForwardList().getSize() == 0) {
Michael Kolbc831b632011-05-11 09:30:34 -07002107 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002108 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002109 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002110 closeTab(current);
2111 }
2112 }
2113 }
2114
John Reck26b18322011-06-21 13:08:58 -07002115 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002116 // Dismiss the subwindow if applicable.
2117 dismissSubWindow(appTab);
2118 // Since we might kill the WebView, remove it from the
2119 // content view first.
2120 mUi.detachTab(appTab);
2121 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002122 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002123 // TODO: analyze why the remove and add are necessary
2124 mUi.attachTab(appTab);
2125 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002126 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002127 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002128 } else {
2129 // If the tab was the current tab, we have to attach
2130 // it to the view system again.
2131 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002132 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002133 }
2134 }
2135
2136 // Remove the sub window if it exists. Also called by TabControl when the
2137 // user clicks the 'X' to dismiss a sub window.
2138 public void dismissSubWindow(Tab tab) {
2139 removeSubWindow(tab);
2140 // dismiss the subwindow. This will destroy the WebView.
2141 tab.dismissSubWindow();
2142 getCurrentTopWebView().requestFocus();
2143 }
2144
2145 @Override
2146 public void removeSubWindow(Tab t) {
2147 if (t.getSubWebView() != null) {
2148 mUi.removeSubWindow(t.getSubViewContainer());
2149 }
2150 }
2151
2152 @Override
2153 public void attachSubWindow(Tab tab) {
2154 if (tab.getSubWebView() != null) {
2155 mUi.attachSubWindow(tab.getSubViewContainer());
2156 getCurrentTopWebView().requestFocus();
2157 }
2158 }
2159
Mathew Inwood29721c22011-06-29 17:55:24 +01002160 private Tab showPreloadedTab(final UrlData urlData) {
2161 if (!urlData.isPreloaded()) {
2162 return null;
2163 }
2164 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2165 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2166 if (sbQuery != null) {
2167 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
2168 // Could not submit query. Fallback to regular tab creation
2169 tabControl.destroy();
2170 return null;
2171 }
2172 }
Michael Kolbff6a7482011-07-26 16:37:15 -07002173 // check tab count and make room for new tab
2174 if (!mTabControl.canCreateNewTab()) {
2175 Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
2176 if (leastUsed != null) {
2177 closeTab(leastUsed);
2178 }
2179 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002180 Tab t = tabControl.getTab();
2181 mTabControl.addPreloadedTab(t);
2182 addTab(t);
2183 setActiveTab(t);
2184 return t;
2185 }
2186
Michael Kolb7bcafde2011-05-09 13:55:59 -07002187 // open a non inconito tab with the given url data
2188 // and set as active tab
2189 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002190 Tab tab = showPreloadedTab(urlData);
2191 if (tab == null) {
2192 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002193 if ((tab != null) && !urlData.isEmpty()) {
2194 loadUrlDataIn(tab, urlData);
2195 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002196 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002197 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002198 }
2199
Michael Kolb843510f2010-12-09 10:51:49 -08002200 @Override
2201 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002202 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002203 }
2204
Michael Kolb8233fac2010-10-26 16:08:53 -07002205 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002206 public Tab openIncognitoTab() {
2207 return openTab(INCOGNITO_URI, true, true, false);
2208 }
2209
2210 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002211 public Tab openTab(String url, boolean incognito, boolean setActive,
2212 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002213 return openTab(url, incognito, setActive, useCurrent, null);
2214 }
2215
2216 @Override
2217 public Tab openTab(String url, Tab parent, boolean setActive,
2218 boolean useCurrent) {
2219 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2220 setActive, useCurrent, parent);
2221 }
2222
2223 public Tab openTab(String url, boolean incognito, boolean setActive,
2224 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002225 Tab tab = createNewTab(incognito, setActive, useCurrent);
2226 if (tab != null) {
John Reck5949c662011-05-27 09:52:29 -07002227 if (parent != null && parent != tab) {
2228 parent.addChildTab(tab);
2229 }
Michael Kolb519d2282011-05-09 17:03:19 -07002230 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002231 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002232 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002233 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002234 return tab;
2235 }
2236
2237 // this method will attempt to create a new tab
2238 // incognito: private browsing tab
2239 // setActive: ste tab as current tab
2240 // useCurrent: if no new tab can be created, return current tab
2241 private Tab createNewTab(boolean incognito, boolean setActive,
2242 boolean useCurrent) {
2243 Tab tab = null;
2244 if (mTabControl.canCreateNewTab()) {
2245 tab = mTabControl.createNewTab(incognito);
2246 addTab(tab);
2247 if (setActive) {
2248 setActiveTab(tab);
2249 }
2250 } else {
2251 if (useCurrent) {
2252 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002253 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002254 } else {
2255 mUi.showMaxTabsWarning();
2256 }
2257 }
2258 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002259 }
2260
John Reck2bc80422011-06-30 15:11:49 -07002261 @Override
2262 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2263 SnapshotTab tab = null;
2264 if (mTabControl.canCreateNewTab()) {
2265 tab = mTabControl.createSnapshotTab(snapshotId);
2266 addTab(tab);
2267 if (setActive) {
2268 setActiveTab(tab);
2269 }
2270 } else {
2271 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07002272 }
2273 return tab;
2274 }
2275
Michael Kolb8233fac2010-10-26 16:08:53 -07002276 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002277 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002278 * @return boolean True if we successfully switched to a different tab. If
2279 * the indexth tab is null, or if that tab is the same as
2280 * the current one, return false.
2281 */
2282 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002283 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002284 Tab currentTab = mTabControl.getCurrentTab();
2285 if (tab == null || tab == currentTab) {
2286 return false;
2287 }
2288 setActiveTab(tab);
2289 return true;
2290 }
2291
2292 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002293 public void closeCurrentTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002294 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07002295 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07002296 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08002297 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002298 return;
2299 }
Michael Kolbc831b632011-05-11 09:30:34 -07002300 final Tab current = mTabControl.getCurrentTab();
2301 final int pos = mTabControl.getCurrentPosition();
2302 Tab newTab = current.getParent();
2303 if (newTab == null) {
2304 newTab = mTabControl.getTab(pos + 1);
2305 if (newTab == null) {
2306 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002307 }
2308 }
Michael Kolbc831b632011-05-11 09:30:34 -07002309 if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002310 // Close window
2311 closeTab(current);
2312 }
2313 }
2314
2315 /**
2316 * Close the tab, remove its associated title bar, and adjust mTabControl's
2317 * current tab to a valid value.
2318 */
2319 @Override
2320 public void closeTab(Tab tab) {
Michael Kolb2d59c322011-01-25 13:18:55 -08002321 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002322 }
2323
Michael Kolb8233fac2010-10-26 16:08:53 -07002324 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07002325 protected void loadUrlFromContext(String url) {
2326 Tab tab = getCurrentTab();
2327 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002328 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07002329 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002330 url = UrlUtils.smartUrlFilter(url);
2331 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07002332 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07002333 }
2334 }
2335 }
2336
2337 /**
2338 * Load the URL into the given WebView and update the title bar
2339 * to reflect the new load. Call this instead of WebView.loadUrl
2340 * directly.
2341 * @param view The WebView used to load url.
2342 * @param url The URL to load.
2343 */
John Reck71e51422011-07-01 16:49:28 -07002344 @Override
2345 public void loadUrl(Tab tab, String url) {
John Reck26b18322011-06-21 13:08:58 -07002346 loadUrl(tab, url, null);
2347 }
2348
2349 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
2350 if (tab != null) {
2351 dismissSubWindow(tab);
2352 tab.loadUrl(url, headers);
2353 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002354 }
2355
2356 /**
2357 * Load UrlData into a Tab and update the title bar to reflect the new
2358 * load. Call this instead of UrlData.loadIn directly.
2359 * @param t The Tab used to load.
2360 * @param data The UrlData being loaded.
2361 */
2362 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07002363 if (data != null) {
2364 if (data.mVoiceIntent != null) {
2365 t.activateVoiceSearchMode(data.mVoiceIntent);
Michael Kolb14612442011-06-24 13:06:29 -07002366 } else if (data.isPreloaded()) {
2367 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07002368 } else {
2369 loadUrl(t, data.mUrl, data.mHeaders);
2370 }
2371 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002372 }
2373
John Reck30c714c2010-12-16 17:30:34 -08002374 @Override
2375 public void onUserCanceledSsl(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08002376 // TODO: Figure out the "right" behavior
John Reckef654f12011-07-12 16:42:08 -07002377 if (tab.canGoBack()) {
2378 tab.goBack();
John Reck30c714c2010-12-16 17:30:34 -08002379 } else {
John Reckef654f12011-07-12 16:42:08 -07002380 tab.loadUrl(mSettings.getHomePage(), null);
John Reck30c714c2010-12-16 17:30:34 -08002381 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002382 }
2383
2384 void goBackOnePageOrQuit() {
2385 Tab current = mTabControl.getCurrentTab();
2386 if (current == null) {
2387 /*
2388 * Instead of finishing the activity, simply push this to the back
2389 * of the stack and let ActivityManager to choose the foreground
2390 * activity. As BrowserActivity is singleTask, it will be always the
2391 * root of the task. So we can use either true or false for
2392 * moveTaskToBack().
2393 */
2394 mActivity.moveTaskToBack(true);
2395 return;
2396 }
John Reckef654f12011-07-12 16:42:08 -07002397 if (current.canGoBack()) {
2398 current.goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07002399 } else {
2400 // Check to see if we are closing a window that was created by
2401 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002402 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002403 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002404 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002405 // Now we close the other tab
2406 closeTab(current);
2407 } else {
Michael Kolbe28b3472011-08-04 16:54:31 -07002408 if ((current.getAppId() != null) || current.closeOnBack()) {
2409 closeCurrentTab();
2410 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002411 /*
2412 * Instead of finishing the activity, simply push this to the back
2413 * of the stack and let ActivityManager to choose the foreground
2414 * activity. As BrowserActivity is singleTask, it will be always the
2415 * root of the task. So we can use either true or false for
2416 * moveTaskToBack().
2417 */
2418 mActivity.moveTaskToBack(true);
2419 }
2420 }
2421 }
2422
2423 /**
2424 * Feed the previously stored results strings to the BrowserProvider so that
2425 * the SearchDialog will show them instead of the standard searches.
2426 * @param result String to show on the editable line of the SearchDialog.
2427 */
2428 @Override
2429 public void showVoiceSearchResults(String result) {
2430 ContentProviderClient client = mActivity.getContentResolver()
2431 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2432 ContentProvider prov = client.getLocalContentProvider();
2433 BrowserProvider bp = (BrowserProvider) prov;
2434 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2435 client.release();
2436
2437 Bundle bundle = createGoogleSearchSourceBundle(
2438 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2439 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2440 startSearch(result, false, bundle, false);
2441 }
2442
2443 private void startSearch(String initialQuery, boolean selectInitialQuery,
2444 Bundle appSearchData, boolean globalSearch) {
2445 if (appSearchData == null) {
2446 appSearchData = createGoogleSearchSourceBundle(
2447 GOOGLE_SEARCH_SOURCE_TYPE);
2448 }
2449
2450 SearchEngine searchEngine = mSettings.getSearchEngine();
2451 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2452 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2453 }
2454 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2455 globalSearch);
2456 }
2457
2458 private Bundle createGoogleSearchSourceBundle(String source) {
2459 Bundle bundle = new Bundle();
2460 bundle.putString(Search.SOURCE, source);
2461 return bundle;
2462 }
2463
2464 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002465 * helper method for key handler
2466 * returns the current tab if it can't advance
2467 */
Michael Kolbc831b632011-05-11 09:30:34 -07002468 private Tab getNextTab() {
2469 return mTabControl.getTab(Math.min(mTabControl.getTabCount() - 1,
2470 mTabControl.getCurrentPosition() + 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002471 }
2472
2473 /**
2474 * helper method for key handler
2475 * returns the current tab if it can't advance
2476 */
Michael Kolbc831b632011-05-11 09:30:34 -07002477 private Tab getPrevTab() {
2478 return mTabControl.getTab(Math.max(0,
2479 mTabControl.getCurrentPosition() - 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002480 }
2481
2482 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002483 * handle key events in browser
2484 *
2485 * @param keyCode
2486 * @param event
2487 * @return true if handled, false to pass to super
2488 */
2489 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002490 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002491 // Even if MENU is already held down, we need to call to super to open
2492 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002493 if (!noModifiers
2494 && ((KeyEvent.KEYCODE_MENU == keyCode)
2495 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2496 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002497 mMenuIsDown = true;
2498 return false;
2499 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002500
Cary Clark8ff8c662010-12-29 15:03:05 -05002501 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07002502 Tab tab = getCurrentTab();
2503 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05002504
Cary Clark160bbb92011-01-10 11:17:07 -05002505 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2506 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002507
Michael Kolb8233fac2010-10-26 16:08:53 -07002508 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002509 case KeyEvent.KEYCODE_TAB:
2510 if (event.isCtrlPressed()) {
2511 if (event.isShiftPressed()) {
2512 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002513 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002514 } else {
2515 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002516 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002517 }
2518 return true;
2519 }
2520 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002521 case KeyEvent.KEYCODE_SPACE:
2522 // WebView/WebTextView handle the keys in the KeyDown. As
2523 // the Activity's shortcut keys are only handled when WebView
2524 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002525 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002526 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002527 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002528 pageDown();
2529 }
2530 return true;
2531 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002532 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002533 event.startTracking();
2534 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07002535 case KeyEvent.KEYCODE_FORWARD:
2536 if (!noModifiers) break;
2537 tab.goForward();
2538 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002539 case KeyEvent.KEYCODE_DPAD_LEFT:
2540 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002541 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05002542 return true;
2543 }
2544 break;
2545 case KeyEvent.KEYCODE_DPAD_RIGHT:
2546 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002547 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05002548 return true;
2549 }
2550 break;
2551 case KeyEvent.KEYCODE_A:
2552 if (ctrl) {
2553 webView.selectAll();
2554 return true;
2555 }
2556 break;
Michael Kolba4183062011-01-16 10:43:21 -08002557// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002558 case KeyEvent.KEYCODE_C:
2559 if (ctrl) {
2560 webView.copySelection();
2561 return true;
2562 }
2563 break;
Michael Kolba4183062011-01-16 10:43:21 -08002564// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002565// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002566// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002567// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002568// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002569// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002570// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002571// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002572// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002573// case KeyEvent.KEYCODE_M: // unused
2574// case KeyEvent.KEYCODE_N: // in Chrome: new window
2575// case KeyEvent.KEYCODE_O: // in Chrome: open file
2576// case KeyEvent.KEYCODE_P: // in Chrome: print page
2577// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002578// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002579// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2580 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002581 // we can't use the ctrl/shift flags, they check for
2582 // exclusive use of a modifier
2583 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002584 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002585 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002586 } else {
2587 openTabToHomePage();
2588 }
2589 return true;
2590 }
2591 break;
2592// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2593// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb5ae15bd2011-08-16 17:09:27 -07002594// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002595// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2596// case KeyEvent.KEYCODE_Y: // unused
2597// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002598 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002599 // it is a regular key and webview is not null
2600 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002601 }
2602
John Recke6bf4ab2011-02-24 15:48:05 -08002603 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2604 switch(keyCode) {
2605 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07002606 if (mUi.isWebShowing()) {
John Recke6bf4ab2011-02-24 15:48:05 -08002607 bookmarksOrHistoryPicker(true);
2608 return true;
2609 }
2610 break;
2611 }
2612 return false;
2613 }
2614
Michael Kolb8233fac2010-10-26 16:08:53 -07002615 boolean onKeyUp(int keyCode, KeyEvent event) {
Michael Kolb2814a362011-05-19 15:49:41 -07002616 if (KeyEvent.KEYCODE_MENU == keyCode) {
2617 mMenuIsDown = false;
2618 if (event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002619 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002620 }
2621 }
Cary Clark160bbb92011-01-10 11:17:07 -05002622 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002623 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002624 case KeyEvent.KEYCODE_BACK:
2625 if (event.isTracking() && !event.isCanceled()) {
2626 onBackKey();
2627 return true;
2628 }
2629 break;
2630 }
2631 return false;
2632 }
2633
2634 public boolean isMenuDown() {
2635 return mMenuIsDown;
2636 }
2637
Ben Murdoch8029a772010-11-16 11:58:21 +00002638 public void setupAutoFill(Message message) {
2639 // Open the settings activity at the AutoFill profile fragment so that
2640 // the user can create a new profile. When they return, we will dispatch
2641 // the message so that we can autofill the form using their new profile.
2642 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2643 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2644 AutoFillSettingsFragment.class.getName());
2645 mAutoFillSetupMessage = message;
2646 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2647 }
John Reckb3417f02011-01-14 11:01:05 -08002648
2649 @Override
Narayan Kamath5119edd2011-02-23 15:49:17 +00002650 public void registerDropdownChangeListener(DropdownChangeListener d) {
2651 mUi.registerDropdownChangeListener(d);
2652 }
Michael Kolbfbc579a2011-07-07 15:59:33 -07002653
2654 public boolean onSearchRequested() {
2655 mUi.editUrl(false);
2656 return true;
2657 }
2658
John Reck1cf4b792011-07-26 10:22:22 -07002659 @Override
2660 public boolean shouldCaptureThumbnails() {
2661 return mUi.shouldCaptureThumbnails();
2662 }
2663
Michael Kolbc3af0672011-08-09 10:24:41 -07002664 @Override
2665 public void setBlockEvents(boolean block) {
2666 mBlockEvents = block;
2667 }
2668
2669 public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb8a009492011-08-15 15:37:30 -07002670 return mBlockEvents || hasNoActiveTab();
Michael Kolbc3af0672011-08-09 10:24:41 -07002671 }
2672
2673 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb8a009492011-08-15 15:37:30 -07002674 return mBlockEvents || hasNoActiveTab();
Michael Kolbc3af0672011-08-09 10:24:41 -07002675 }
2676
2677 public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb8a009492011-08-15 15:37:30 -07002678 return mBlockEvents || hasNoActiveTab();
Michael Kolbc3af0672011-08-09 10:24:41 -07002679 }
2680
2681 public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb8a009492011-08-15 15:37:30 -07002682 return mBlockEvents || hasNoActiveTab();
Michael Kolbc3af0672011-08-09 10:24:41 -07002683 }
2684
2685 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb8a009492011-08-15 15:37:30 -07002686 return mBlockEvents || hasNoActiveTab();
2687 }
2688
2689 private boolean hasNoActiveTab() {
2690 Tab tab = getCurrentTab();
2691 if (tab == null) {
2692 Log.w(LOGTAG, "Received event with no active tab. Tab count: "
2693 + mTabControl.getTabCount());
2694 }
2695 return tab == null;
Michael Kolbc3af0672011-08-09 10:24:41 -07002696 }
2697
Michael Kolb8233fac2010-10-26 16:08:53 -07002698}