blob: a3887f53debaf6143c89630e2af61d6723539123 [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;
Mathew Inwoodb4e831b2011-09-05 18:58:48 +010021import android.app.PendingIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070022import android.app.SearchManager;
23import android.content.ClipboardManager;
24import android.content.ContentProvider;
25import android.content.ContentProviderClient;
26import android.content.ContentResolver;
John Reckd8c74522011-06-14 08:45:00 -070027import android.content.ContentUris;
Michael Kolb8233fac2010-10-26 16:08:53 -070028import android.content.ContentValues;
29import android.content.Context;
30import android.content.Intent;
31import android.content.pm.PackageManager;
32import android.content.pm.ResolveInfo;
33import android.content.res.Configuration;
John Reck30b065e2011-07-19 10:58:05 -070034import android.content.res.TypedArray;
Leon Scroggins1961ed22010-12-07 15:22:21 -050035import android.database.ContentObserver;
Michael Kolb8233fac2010-10-26 16:08:53 -070036import android.database.Cursor;
37import android.database.sqlite.SQLiteDatabase;
Michael Kolb8233fac2010-10-26 16:08:53 -070038import android.graphics.Bitmap;
39import android.graphics.Canvas;
40import android.graphics.Picture;
41import android.net.Uri;
42import android.net.http.SslError;
43import android.os.AsyncTask;
44import android.os.Bundle;
45import android.os.Handler;
46import android.os.Message;
47import android.os.PowerManager;
48import android.os.PowerManager.WakeLock;
Ben Murdoch8029a772010-11-16 11:58:21 +000049import android.preference.PreferenceActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -070050import android.provider.Browser;
51import android.provider.BrowserContract;
Michael Kolb8233fac2010-10-26 16:08:53 -070052import android.provider.BrowserContract.Images;
53import android.provider.ContactsContract;
54import android.provider.ContactsContract.Intents.Insert;
Michael Kolbcfa3af52010-12-14 10:36:11 -080055import android.speech.RecognizerIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070056import android.text.TextUtils;
57import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080058import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070059import android.view.ActionMode;
60import android.view.ContextMenu;
61import android.view.ContextMenu.ContextMenuInfo;
62import android.view.Gravity;
63import android.view.KeyEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070064import android.view.Menu;
65import android.view.MenuInflater;
66import android.view.MenuItem;
67import android.view.MenuItem.OnMenuItemClickListener;
Michael Kolbc3af0672011-08-09 10:24:41 -070068import android.view.MotionEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070069import android.view.View;
70import android.webkit.CookieManager;
71import android.webkit.CookieSyncManager;
72import android.webkit.HttpAuthHandler;
73import android.webkit.SslErrorHandler;
74import android.webkit.ValueCallback;
75import android.webkit.WebChromeClient;
76import android.webkit.WebIconDatabase;
77import android.webkit.WebSettings;
78import android.webkit.WebView;
Leon Scrogginsac993842011-02-02 12:54:07 -050079import android.widget.Toast;
Michael Kolb8233fac2010-10-26 16:08:53 -070080
Michael Kolb4bd767d2011-05-27 11:33:55 -070081import com.android.browser.IntentHandler.UrlData;
John Reck2bc80422011-06-30 15:11:49 -070082import com.android.browser.UI.ComboViews;
Michael Kolb4bd767d2011-05-27 11:33:55 -070083import com.android.browser.UI.DropdownChangeListener;
84import com.android.browser.provider.BrowserProvider;
John Reck1cf4b792011-07-26 10:22:22 -070085import com.android.browser.provider.BrowserProvider2.Thumbnails;
John Reck8cc92352011-07-06 17:41:52 -070086import com.android.browser.provider.SnapshotProvider.Snapshots;
Michael Kolb4bd767d2011-05-27 11:33:55 -070087import com.android.browser.search.SearchEngine;
88import com.android.common.Search;
89
Michael Kolb8233fac2010-10-26 16:08:53 -070090import java.io.ByteArrayOutputStream;
Michael Kolb8233fac2010-10-26 16:08:53 -070091import java.net.URLEncoder;
John Reck1cf4b792011-07-26 10:22:22 -070092import java.util.ArrayList;
Michael Kolb8233fac2010-10-26 16:08:53 -070093import java.util.Calendar;
94import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -080095import java.util.List;
John Reck26b18322011-06-21 13:08:58 -070096import java.util.Map;
Mathew Inwoodb4e831b2011-09-05 18:58:48 +010097import java.util.regex.Pattern;
Michael Kolb8233fac2010-10-26 16:08:53 -070098
99/**
100 * Controller for browser
101 */
102public class Controller
103 implements WebViewController, UiController {
104
105 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800106 private static final String SEND_APP_ID_EXTRA =
107 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
Michael Kolba4261fd2011-05-05 11:27:37 -0700108 private static final String INCOGNITO_URI = "browser:incognito";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800109
Michael Kolb8233fac2010-10-26 16:08:53 -0700110
111 // public message ids
112 public final static int LOAD_URL = 1001;
113 public final static int STOP_LOAD = 1002;
114
115 // Message Ids
116 private static final int FOCUS_NODE_HREF = 102;
117 private static final int RELEASE_WAKELOCK = 107;
118
119 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
120
121 private static final int OPEN_BOOKMARKS = 201;
122
123 private static final int EMPTY_MENU = -1;
124
Michael Kolb8233fac2010-10-26 16:08:53 -0700125 // activity requestCode
John Reckd3e4d5b2011-07-13 15:48:43 -0700126 final static int COMBO_VIEW = 1;
Michael Kolb8233fac2010-10-26 16:08:53 -0700127 final static int PREFERENCES_PAGE = 3;
128 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000129 final static int AUTOFILL_SETUP = 5;
130
Michael Kolb8233fac2010-10-26 16:08:53 -0700131 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
132
133 // As the ids are dynamically created, we can't guarantee that they will
134 // be in sequence, so this static array maps ids to a window number.
135 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
136 { R.id.window_one_menu_id, R.id.window_two_menu_id,
137 R.id.window_three_menu_id, R.id.window_four_menu_id,
138 R.id.window_five_menu_id, R.id.window_six_menu_id,
139 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
140
141 // "source" parameter for Google search through search key
142 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
143 // "source" parameter for Google search through simplily type
144 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
145
Guang Zhu9e78f512011-05-04 11:45:11 -0700146 // "no-crash-recovery" parameter in intetnt to suppress crash recovery
147 final static String NO_CRASH_RECOVERY = "no-crash-recovery";
148
Michael Kolb8233fac2010-10-26 16:08:53 -0700149 private Activity mActivity;
150 private UI mUi;
151 private TabControl mTabControl;
152 private BrowserSettings mSettings;
153 private WebViewFactory mFactory;
154
155 private WakeLock mWakeLock;
156
157 private UrlHandler mUrlHandler;
158 private UploadHandler mUploadHandler;
159 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700160 private PageDialogsHandler mPageDialogsHandler;
161 private NetworkStateHandler mNetworkHandler;
162
Ben Murdoch8029a772010-11-16 11:58:21 +0000163 private Message mAutoFillSetupMessage;
164
Michael Kolb8233fac2010-10-26 16:08:53 -0700165 private boolean mShouldShowErrorConsole;
166
167 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
168
169 // FIXME, temp address onPrepareMenu performance problem.
170 // When we move everything out of view, we should rewrite this.
171 private int mCurrentMenuState = 0;
172 private int mMenuState = R.id.MAIN_MENU;
173 private int mOldMenuState = EMPTY_MENU;
174 private Menu mCachedMenu;
175
Michael Kolb8233fac2010-10-26 16:08:53 -0700176 private boolean mMenuIsDown;
177
178 // For select and find, we keep track of the ActionMode so that
179 // finish() can be called as desired.
180 private ActionMode mActionMode;
181
182 /**
183 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
184 * of whether the configuration has changed. The first onMenuOpened call
185 * after a configuration change is simply a reopening of the same menu
186 * (i.e. mIconView did not change).
187 */
188 private boolean mConfigChanged;
189
190 /**
191 * Keeps track of whether the options menu is open. This is important in
192 * determining whether to show or hide the title bar overlay
193 */
194 private boolean mOptionsMenuOpen;
195
196 /**
197 * Whether or not the options menu is in its bigger, popup menu form. When
198 * true, we want the title bar overlay to be gone. When false, we do not.
199 * Only meaningful if mOptionsMenuOpen is true.
200 */
201 private boolean mExtendedMenuOpen;
202
203 private boolean mInLoad;
204
205 private boolean mActivityPaused = true;
206 private boolean mLoadStopped;
207
208 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500209 // Checks to see when the bookmarks database has changed, and updates the
210 // Tabs' notion of whether they represent bookmarked sites.
211 private ContentObserver mBookmarksObserver;
John Reck847b5322011-04-14 17:02:18 -0700212 private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700213
John Reck30b065e2011-07-19 10:58:05 -0700214 private boolean mSimulateActionBarOverlayMode;
215
Michael Kolbc3af0672011-08-09 10:24:41 -0700216 private boolean mBlockEvents;
217
John Reckbc490d22011-07-22 15:04:59 -0700218 public Controller(Activity browser, boolean preloadCrashState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700219 mActivity = browser;
220 mSettings = BrowserSettings.getInstance();
221 mTabControl = new TabControl(this);
222 mSettings.setController(this);
John Reck378a4102011-06-09 16:23:01 -0700223 mCrashRecoveryHandler = CrashRecoveryHandler.initialize(this);
John Reckbc490d22011-07-22 15:04:59 -0700224 if (preloadCrashState) {
225 mCrashRecoveryHandler.preloadCrashState();
226 }
Michael Kolb14612442011-06-24 13:06:29 -0700227 mFactory = new BrowserWebViewFactory(browser);
Michael Kolb8233fac2010-10-26 16:08:53 -0700228
229 mUrlHandler = new UrlHandler(this);
230 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700231 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
232
Michael Kolb8233fac2010-10-26 16:08:53 -0700233 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500234 mBookmarksObserver = new ContentObserver(mHandler) {
235 @Override
236 public void onChange(boolean selfChange) {
237 int size = mTabControl.getTabCount();
238 for (int i = 0; i < size; i++) {
239 mTabControl.getTab(i).updateBookmarkedStatus();
240 }
241 }
242
243 };
244 browser.getContentResolver().registerContentObserver(
245 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700246
247 mNetworkHandler = new NetworkStateHandler(mActivity, this);
248 // Start watching the default geolocation permissions
249 mSystemAllowGeolocationOrigins =
250 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
251 mSystemAllowGeolocationOrigins.start();
252
John Reckaf262e72011-07-25 13:55:44 -0700253 openIconDatabase();
John Reck30b065e2011-07-19 10:58:05 -0700254 mSimulateActionBarOverlayMode = !BrowserActivity.isTablet(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700255 }
256
Patrick Scott7d50a932011-02-04 09:27:26 -0500257 void start(final Bundle icicle, final Intent intent) {
Guang Zhu9e78f512011-05-04 11:45:11 -0700258 boolean noCrashRecovery = intent.getBooleanExtra(NO_CRASH_RECOVERY, false);
259 if (icicle != null || noCrashRecovery) {
John Reck847b5322011-04-14 17:02:18 -0700260 doStart(icicle, intent);
261 } else {
262 mCrashRecoveryHandler.startRecovery(intent);
263 }
264 }
265
266 void doStart(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700267 // Unless the last browser usage was within 24 hours, destroy any
268 // remaining incognito tabs.
269
270 Calendar lastActiveDate = icicle != null ?
271 (Calendar) icicle.getSerializable("lastActiveDate") : null;
272 Calendar today = Calendar.getInstance();
273 Calendar yesterday = Calendar.getInstance();
274 yesterday.add(Calendar.DATE, -1);
275
Patrick Scott7d50a932011-02-04 09:27:26 -0500276 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700277 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800278 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700279
Patrick Scott7d50a932011-02-04 09:27:26 -0500280 // Find out if we will restore any state and remember the tab.
Michael Kolbc831b632011-05-11 09:30:34 -0700281 final long currentTabId =
Patrick Scott7d50a932011-02-04 09:27:26 -0500282 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000283
Michael Kolbc831b632011-05-11 09:30:34 -0700284 if (currentTabId == -1) {
Patrick Scott7d50a932011-02-04 09:27:26 -0500285 // Not able to restore so we go ahead and clear session cookies. We
286 // must do this before trying to login the user as we don't want to
287 // clear any session cookies set during login.
288 CookieManager.getInstance().removeSessionCookie();
289 }
290
Patrick Scottd43e75a2011-03-14 14:47:23 -0400291 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500292 new Runnable() {
293 @Override public void run() {
Michael Kolbc831b632011-05-11 09:30:34 -0700294 onPreloginFinished(icicle, intent, currentTabId, restoreIncognitoTabs);
Patrick Scott7d50a932011-02-04 09:27:26 -0500295 }
296 });
297 }
298
Michael Kolbc831b632011-05-11 09:30:34 -0700299 private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId,
Patrick Scott7d50a932011-02-04 09:27:26 -0500300 boolean restoreIncognitoTabs) {
Michael Kolbc831b632011-05-11 09:30:34 -0700301 if (currentTabId == -1) {
John Reck1cf4b792011-07-26 10:22:22 -0700302 BackgroundHandler.execute(new PruneThumbnails(mActivity, null));
Michael Kolb8233fac2010-10-26 16:08:53 -0700303 final Bundle extra = intent.getExtras();
304 // Create an initial tab.
305 // If the intent is ACTION_VIEW and data is not null, the Browser is
306 // invoked to view the content by another application. In this case,
307 // the tab will be close when exit.
Michael Kolb14612442011-06-24 13:06:29 -0700308 UrlData urlData = IntentHandler.getUrlDataFromIntent(intent);
Michael Kolb7bcafde2011-05-09 13:55:59 -0700309 Tab t = null;
310 if (urlData.isEmpty()) {
311 t = openTabToHomePage();
312 } else {
313 t = openTab(urlData);
314 }
315 if (t != null) {
316 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
317 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700318 WebView webView = t.getWebView();
319 if (extra != null) {
320 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
321 if (scale > 0 && scale <= 1000) {
322 webView.setInitialScale(scale);
323 }
324 }
John Reckd8c74522011-06-14 08:45:00 -0700325 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700326 } else {
Michael Kolbc831b632011-05-11 09:30:34 -0700327 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
Patrick Scott7d50a932011-02-04 09:27:26 -0500328 mUi.needsRestoreAllTabs());
John Reck1cf4b792011-07-26 10:22:22 -0700329 List<Tab> tabs = mTabControl.getTabs();
330 ArrayList<Long> restoredTabs = new ArrayList<Long>(tabs.size());
331 for (Tab t : tabs) {
332 restoredTabs.add(t.getId());
333 }
334 BackgroundHandler.execute(new PruneThumbnails(mActivity, restoredTabs));
John Reck52be4782011-08-26 15:37:29 -0700335 if (tabs.size() == 0) {
336 openTabToHomePage();
337 }
John Reck1cf4b792011-07-26 10:22:22 -0700338 mUi.updateTabs(tabs);
Michael Kolb8233fac2010-10-26 16:08:53 -0700339 // TabControl.restoreState() will create a new tab even if
340 // restoring the state fails.
341 setActiveTab(mTabControl.getCurrentTab());
John Reckdb22ec42011-06-29 11:31:24 -0700342 // Handle the intent
343 mIntentHandler.onNewIntent(intent);
Michael Kolb8233fac2010-10-26 16:08:53 -0700344 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700345 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700346 String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb8233fac2010-10-26 16:08:53 -0700347 if (jsFlags.trim().length() != 0) {
348 getCurrentWebView().setJsFlags(jsFlags);
349 }
John Reck439c9a52010-12-14 10:04:39 -0800350 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
351 bookmarksOrHistoryPicker(false);
352 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700353 }
354
John Reck1cf4b792011-07-26 10:22:22 -0700355 private static class PruneThumbnails implements Runnable {
356 private Context mContext;
357 private List<Long> mIds;
358
359 PruneThumbnails(Context context, List<Long> preserveIds) {
360 mContext = context.getApplicationContext();
361 mIds = preserveIds;
362 }
363
364 @Override
365 public void run() {
366 ContentResolver cr = mContext.getContentResolver();
367 if (mIds == null || mIds.size() == 0) {
368 cr.delete(Thumbnails.CONTENT_URI, null, null);
369 } else {
370 int length = mIds.size();
371 StringBuilder where = new StringBuilder();
372 where.append(Thumbnails._ID);
373 where.append(" not in (");
374 for (int i = 0; i < length; i++) {
375 where.append(mIds.get(i));
376 if (i < (length - 1)) {
377 where.append(",");
378 }
379 }
380 where.append(")");
381 cr.delete(Thumbnails.CONTENT_URI, where.toString(), null);
382 }
383 }
384
385 }
386
Michael Kolb1514bb72010-11-22 09:11:48 -0800387 @Override
388 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700389 return mFactory;
390 }
391
392 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800393 public void onSetWebView(Tab tab, WebView view) {
394 mUi.onSetWebView(tab, view);
395 }
396
397 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800398 public void createSubWindow(Tab tab) {
399 endActionMode();
400 WebView mainView = tab.getWebView();
401 WebView subView = mFactory.createWebView((mainView == null)
402 ? false
403 : mainView.isPrivateBrowsingEnabled());
404 mUi.createSubWindow(tab, subView);
405 }
406
407 @Override
Michael Kolb14612442011-06-24 13:06:29 -0700408 public Context getContext() {
409 return mActivity;
410 }
411
412 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700413 public Activity getActivity() {
414 return mActivity;
415 }
416
417 void setUi(UI ui) {
418 mUi = ui;
419 }
420
421 BrowserSettings getSettings() {
422 return mSettings;
423 }
424
425 IntentHandler getIntentHandler() {
426 return mIntentHandler;
427 }
428
429 @Override
430 public UI getUi() {
431 return mUi;
432 }
433
434 int getMaxTabs() {
435 return mActivity.getResources().getInteger(R.integer.max_tabs);
436 }
437
438 @Override
439 public TabControl getTabControl() {
440 return mTabControl;
441 }
442
Michael Kolb1bf23132010-11-19 12:55:12 -0800443 @Override
444 public List<Tab> getTabs() {
445 return mTabControl.getTabs();
446 }
447
John Reckaf262e72011-07-25 13:55:44 -0700448 // Open the icon database.
449 private void openIconDatabase() {
450 // We have to call getInstance on the UI thread
451 final WebIconDatabase instance = WebIconDatabase.getInstance();
452 BackgroundHandler.execute(new Runnable() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000453
John Reckaf262e72011-07-25 13:55:44 -0700454 @Override
455 public void run() {
456 instance.open(mActivity.getDir("icons", 0).getPath());
Michael Kolb8233fac2010-10-26 16:08:53 -0700457 }
John Reckaf262e72011-07-25 13:55:44 -0700458 });
Michael Kolb8233fac2010-10-26 16:08:53 -0700459 }
460
461 private void startHandler() {
462 mHandler = new Handler() {
463
464 @Override
465 public void handleMessage(Message msg) {
466 switch (msg.what) {
467 case OPEN_BOOKMARKS:
468 bookmarksOrHistoryPicker(false);
469 break;
470 case FOCUS_NODE_HREF:
471 {
472 String url = (String) msg.getData().get("url");
473 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500474 String src = (String) msg.getData().get("src");
475 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700476 if (TextUtils.isEmpty(url)) {
477 break;
478 }
479 HashMap focusNodeMap = (HashMap) msg.obj;
480 WebView view = (WebView) focusNodeMap.get("webview");
481 // Only apply the action if the top window did not change.
482 if (getCurrentTopWebView() != view) {
483 break;
484 }
485 switch (msg.arg1) {
486 case R.id.open_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700487 loadUrlFromContext(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700488 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500489 case R.id.view_image_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700490 loadUrlFromContext(src);
Cary Clark043c2d62010-12-15 11:19:39 -0500491 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500492 case R.id.open_newtab_context_menu_id:
493 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -0700494 openTab(url, parent,
495 !mSettings.openInBackground(), true);
Leon Scroggins026f2542010-11-22 13:26:12 -0500496 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700497 case R.id.copy_link_context_menu_id:
498 copy(url);
499 break;
500 case R.id.save_link_context_menu_id:
501 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500502 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000503 mActivity, url, null, null, null,
504 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700505 break;
506 }
507 break;
508 }
509
510 case LOAD_URL:
John Reck26b18322011-06-21 13:08:58 -0700511 loadUrlFromContext((String) msg.obj);
Michael Kolb8233fac2010-10-26 16:08:53 -0700512 break;
513
514 case STOP_LOAD:
515 stopLoading();
516 break;
517
518 case RELEASE_WAKELOCK:
John Reckf57c0292011-07-21 18:15:39 -0700519 if (mWakeLock != null && mWakeLock.isHeld()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700520 mWakeLock.release();
521 // if we reach here, Browser should be still in the
522 // background loading after WAKELOCK_TIMEOUT (5-min).
523 // To avoid burning the battery, stop loading.
524 mTabControl.stopAllLoading();
525 }
526 break;
527
528 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800529 Tab tab = (Tab) msg.obj;
530 if (tab != null) {
531 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700532 }
533 break;
534 }
535 }
536 };
537
538 }
539
John Reckef654f12011-07-12 16:42:08 -0700540 @Override
Martijn Coenenb2f93552011-06-14 10:48:35 +0200541 public Tab getCurrentTab() {
542 return mTabControl.getCurrentTab();
543 }
544
Michael Kolbba99c5d2010-11-29 14:57:41 -0800545 @Override
546 public void shareCurrentPage() {
547 shareCurrentPage(mTabControl.getCurrentTab());
548 }
549
550 private void shareCurrentPage(Tab tab) {
551 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800552 sharePage(mActivity, tab.getTitle(),
553 tab.getUrl(), tab.getFavicon(),
554 createScreenshot(tab.getWebView(),
555 getDesiredThumbnailWidth(mActivity),
556 getDesiredThumbnailHeight(mActivity)));
557 }
558 }
559
Michael Kolb8233fac2010-10-26 16:08:53 -0700560 /**
561 * Share a page, providing the title, url, favicon, and a screenshot. Uses
562 * an {@link Intent} to launch the Activity chooser.
563 * @param c Context used to launch a new Activity.
564 * @param title Title of the page. Stored in the Intent with
565 * {@link Intent#EXTRA_SUBJECT}
566 * @param url URL of the page. Stored in the Intent with
567 * {@link Intent#EXTRA_TEXT}
568 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
569 * with {@link Browser#EXTRA_SHARE_FAVICON}
570 * @param screenshot Bitmap of a screenshot of the page. Stored in the
571 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
572 */
573 static final void sharePage(Context c, String title, String url,
574 Bitmap favicon, Bitmap screenshot) {
575 Intent send = new Intent(Intent.ACTION_SEND);
576 send.setType("text/plain");
577 send.putExtra(Intent.EXTRA_TEXT, url);
578 send.putExtra(Intent.EXTRA_SUBJECT, title);
579 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
580 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
581 try {
582 c.startActivity(Intent.createChooser(send, c.getString(
583 R.string.choosertitle_sharevia)));
584 } catch(android.content.ActivityNotFoundException ex) {
585 // if no app handles it, do nothing
586 }
587 }
588
589 private void copy(CharSequence text) {
590 ClipboardManager cm = (ClipboardManager) mActivity
591 .getSystemService(Context.CLIPBOARD_SERVICE);
592 cm.setText(text);
593 }
594
595 // lifecycle
596
597 protected void onConfgurationChanged(Configuration config) {
598 mConfigChanged = true;
599 if (mPageDialogsHandler != null) {
600 mPageDialogsHandler.onConfigurationChanged(config);
601 }
602 mUi.onConfigurationChanged(config);
603 }
604
605 @Override
606 public void handleNewIntent(Intent intent) {
Michael Kolb59e232c2011-08-18 17:19:53 -0700607 if (!mUi.isWebShowing()) {
608 mUi.showWeb(false);
609 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700610 mIntentHandler.onNewIntent(intent);
611 }
612
613 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800614 if (mUi.isCustomViewShowing()) {
615 hideCustomView();
616 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700617 if (mActivityPaused) {
618 Log.e(LOGTAG, "BrowserActivity is already paused.");
619 return;
620 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700621 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800622 Tab tab = mTabControl.getCurrentTab();
623 if (tab != null) {
624 tab.pause();
625 if (!pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700626 if (mWakeLock == null) {
627 PowerManager pm = (PowerManager) mActivity
628 .getSystemService(Context.POWER_SERVICE);
629 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
630 }
Michael Kolb70976932010-11-30 11:34:01 -0800631 mWakeLock.acquire();
632 mHandler.sendMessageDelayed(mHandler
633 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
634 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700635 }
636 mUi.onPause();
637 mNetworkHandler.onPause();
638
639 WebView.disablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100640 NfcHandler.unregister(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700641 }
642
John Reck1cf4b792011-07-26 10:22:22 -0700643 void onSaveInstanceState(Bundle outState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700644 // the default implementation requires each view to have an id. As the
645 // browser handles the state itself and it doesn't use id for the views,
646 // don't call the default implementation. Otherwise it will trigger the
647 // warning like this, "couldn't save which view has focus because the
648 // focused view XXX has no id".
649
650 // Save all the tabs
John Reck1cf4b792011-07-26 10:22:22 -0700651 mTabControl.saveState(outState);
John Reck24f18262011-06-17 14:47:20 -0700652 if (!outState.isEmpty()) {
653 // Save time so that we know how old incognito tabs (if any) are.
654 outState.putSerializable("lastActiveDate", Calendar.getInstance());
655 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700656 }
657
658 void onResume() {
659 if (!mActivityPaused) {
660 Log.e(LOGTAG, "BrowserActivity is already resumed.");
661 return;
662 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700663 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800664 Tab current = mTabControl.getCurrentTab();
665 if (current != null) {
666 current.resume();
667 resumeWebViewTimers(current);
668 }
John Reckf57c0292011-07-21 18:15:39 -0700669 releaseWakeLock();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200670
Michael Kolb8233fac2010-10-26 16:08:53 -0700671 mUi.onResume();
672 mNetworkHandler.onResume();
673 WebView.enablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100674 NfcHandler.register(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700675 }
676
John Reckf57c0292011-07-21 18:15:39 -0700677 private void releaseWakeLock() {
678 if (mWakeLock != null && mWakeLock.isHeld()) {
679 mHandler.removeMessages(RELEASE_WAKELOCK);
680 mWakeLock.release();
681 }
682 }
683
Michael Kolb70976932010-11-30 11:34:01 -0800684 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800685 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800686 * @param tab guaranteed non-null
687 */
688 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700689 boolean inLoad = tab.inPageLoad();
690 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
691 CookieSyncManager.getInstance().startSync();
692 WebView w = tab.getWebView();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100693 WebViewTimersControl.getInstance().onBrowserActivityResume(w);
Michael Kolb8233fac2010-10-26 16:08:53 -0700694 }
695 }
696
Michael Kolb70976932010-11-30 11:34:01 -0800697 /**
698 * Pause all WebView timers using the WebView of the given tab
699 * @param tab
700 * @return true if the timers are paused or tab is null
701 */
702 private boolean pauseWebViewTimers(Tab tab) {
703 if (tab == null) {
704 return true;
705 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700706 CookieSyncManager.getInstance().stopSync();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100707 WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView());
Michael Kolb8233fac2010-10-26 16:08:53 -0700708 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700709 }
Michael Kolb70976932010-11-30 11:34:01 -0800710 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700711 }
712
713 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800714 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700715 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
716 mUploadHandler = null;
717 }
718 if (mTabControl == null) return;
719 mUi.onDestroy();
720 // Remove the current tab and sub window
721 Tab t = mTabControl.getCurrentTab();
722 if (t != null) {
723 dismissSubWindow(t);
724 removeTab(t);
725 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500726 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700727 // Destroy all the tabs
728 mTabControl.destroy();
729 WebIconDatabase.getInstance().close();
730 // Stop watching the default geolocation permissions
731 mSystemAllowGeolocationOrigins.stop();
732 mSystemAllowGeolocationOrigins = null;
733 }
734
735 protected boolean isActivityPaused() {
736 return mActivityPaused;
737 }
738
739 protected void onLowMemory() {
740 mTabControl.freeMemory();
741 }
742
743 @Override
744 public boolean shouldShowErrorConsole() {
745 return mShouldShowErrorConsole;
746 }
747
748 protected void setShouldShowErrorConsole(boolean show) {
749 if (show == mShouldShowErrorConsole) {
750 // Nothing to do.
751 return;
752 }
753 mShouldShowErrorConsole = show;
754 Tab t = mTabControl.getCurrentTab();
755 if (t == null) {
756 // There is no current tab so we cannot toggle the error console
757 return;
758 }
759 mUi.setShouldShowErrorConsole(t, show);
760 }
761
762 @Override
763 public void stopLoading() {
764 mLoadStopped = true;
765 Tab tab = mTabControl.getCurrentTab();
Mathew Inwoodb4e831b2011-09-05 18:58:48 +0100766 tab.clearPageLoadCompleteListener();
Michael Kolb8233fac2010-10-26 16:08:53 -0700767 WebView w = getCurrentTopWebView();
768 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700769 mUi.onPageStopped(tab);
770 }
771
772 boolean didUserStopLoading() {
773 return mLoadStopped;
774 }
775
776 // WebViewController
777
778 @Override
John Reck324d4402011-01-11 16:56:42 -0800779 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700780
781 // We've started to load a new page. If there was a pending message
782 // to save a screenshot then we will now take the new page and save
783 // an incorrect screenshot. Therefore, remove any pending thumbnail
784 // messages from the queue.
785 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800786 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700787
788 // reset sync timer to avoid sync starts during loading a page
789 CookieSyncManager.getInstance().resetSync();
790
791 if (!mNetworkHandler.isNetworkUp()) {
792 view.setNetworkAvailable(false);
793 }
794
795 // when BrowserActivity just starts, onPageStarted may be called before
796 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
797 // to start the timer. As we won't switch tabs while an activity is in
798 // pause state, we can ensure calling resume and pause in pair.
799 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800800 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700801 }
802 mLoadStopped = false;
803 if (!mNetworkHandler.isNetworkUp()) {
804 mNetworkHandler.createAndShowNetworkDialog();
805 }
806 endActionMode();
807
John Reck30c714c2010-12-16 17:30:34 -0800808 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700809
John Reck324d4402011-01-11 16:56:42 -0800810 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700811 // update the bookmark database for favicon
812 maybeUpdateFavicon(tab, null, url, favicon);
813
814 Performance.tracePageStart(url);
815
816 // Performance probe
817 if (false) {
818 Performance.onPageStarted();
819 }
820
821 }
822
823 @Override
John Reck324d4402011-01-11 16:56:42 -0800824 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800825 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800826 if (!tab.isPrivateBrowsingEnabled()
John Reckd8c74522011-06-14 08:45:00 -0700827 && !TextUtils.isEmpty(tab.getUrl())
828 && !tab.isSnapshot()) {
John Recka1696282011-07-08 14:10:37 -0700829 // Only update the bookmark screenshot if the user did not
830 // cancel the load early and there is not already
831 // a pending update for the tab.
Michael Kolb8233fac2010-10-26 16:08:53 -0700832 if (tab.inForeground() && !didUserStopLoading()
833 || !tab.inForeground()) {
John Recka1696282011-07-08 14:10:37 -0700834 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
835 mHandler.sendMessageDelayed(mHandler.obtainMessage(
836 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
837 500);
838 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700839 }
840 }
841 // pause the WebView timer and release the wake lock if it is finished
842 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800843 if (mActivityPaused && pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700844 releaseWakeLock();
Michael Kolb8233fac2010-10-26 16:08:53 -0700845 }
Martijn Coenenb2f93552011-06-14 10:48:35 +0200846
Michael Kolb8233fac2010-10-26 16:08:53 -0700847 // Performance probe
848 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800849 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700850 }
851
852 Performance.tracePageFinished();
853 }
854
855 @Override
John Reck30c714c2010-12-16 17:30:34 -0800856 public void onProgressChanged(Tab tab) {
John Reck6c2e2f32011-08-22 13:41:23 -0700857 mCrashRecoveryHandler.backupState();
John Reck30c714c2010-12-16 17:30:34 -0800858 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700859
860 if (newProgress == 100) {
861 CookieSyncManager.getInstance().sync();
862 // onProgressChanged() may continue to be called after the main
863 // frame has finished loading, as any remaining sub frames continue
864 // to load. We'll only get called once though with newProgress as
865 // 100 when everything is loaded. (onPageFinished is called once
866 // when the main frame completes loading regardless of the state of
867 // any sub frames so calls to onProgressChanges may continue after
868 // onPageFinished has executed)
869 if (mInLoad) {
870 mInLoad = false;
871 updateInLoadMenuItems(mCachedMenu);
872 }
873 } else {
874 if (!mInLoad) {
875 // onPageFinished may have already been called but a subframe is
876 // still loading and updating the progress. Reset mInLoad and
877 // update the menu items.
878 mInLoad = true;
879 updateInLoadMenuItems(mCachedMenu);
880 }
881 }
John Reck30c714c2010-12-16 17:30:34 -0800882 mUi.onProgressChanged(tab);
883 }
884
885 @Override
886 public void onUpdatedLockIcon(Tab tab) {
887 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700888 }
889
890 @Override
891 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800892 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800893 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800894 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700895 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
896 return;
897 }
898 // Update the title in the history database if not in private browsing mode
899 if (!tab.isPrivateBrowsingEnabled()) {
John Reckf57c0292011-07-21 18:15:39 -0700900 DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700901 }
902 }
903
904 @Override
905 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800906 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700907 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
908 }
909
910 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800911 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
912 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700913 }
914
915 @Override
916 public boolean shouldOverrideKeyEvent(KeyEvent event) {
917 if (mMenuIsDown) {
918 // only check shortcut key when MENU is held
919 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
920 event);
921 } else {
922 return false;
923 }
924 }
925
926 @Override
927 public void onUnhandledKeyEvent(KeyEvent event) {
928 if (!isActivityPaused()) {
929 if (event.getAction() == KeyEvent.ACTION_DOWN) {
930 mActivity.onKeyDown(event.getKeyCode(), event);
931 } else {
932 mActivity.onKeyUp(event.getKeyCode(), event);
933 }
934 }
935 }
936
937 @Override
John Reck324d4402011-01-11 16:56:42 -0800938 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700939 // Don't save anything in private browsing mode
940 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800941 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700942
John Reck324d4402011-01-11 16:56:42 -0800943 if (TextUtils.isEmpty(url)
944 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700945 return;
946 }
John Reckf57c0292011-07-21 18:15:39 -0700947 DataController.getInstance(mActivity).updateVisitedHistory(url);
John Reck6c2e2f32011-08-22 13:41:23 -0700948 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -0700949 }
950
951 @Override
952 public void getVisitedHistory(final ValueCallback<String[]> callback) {
953 AsyncTask<Void, Void, String[]> task =
954 new AsyncTask<Void, Void, String[]>() {
955 @Override
956 public String[] doInBackground(Void... unused) {
957 return Browser.getVisitedHistory(mActivity.getContentResolver());
958 }
959 @Override
960 public void onPostExecute(String[] result) {
961 callback.onReceiveValue(result);
962 }
963 };
964 task.execute();
965 }
966
967 @Override
968 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
969 final HttpAuthHandler handler, final String host,
970 final String realm) {
971 String username = null;
972 String password = null;
973
974 boolean reuseHttpAuthUsernamePassword
975 = handler.useHttpAuthUsernamePassword();
976
977 if (reuseHttpAuthUsernamePassword && view != null) {
978 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
979 if (credentials != null && credentials.length == 2) {
980 username = credentials[0];
981 password = credentials[1];
982 }
983 }
984
985 if (username != null && password != null) {
986 handler.proceed(username, password);
987 } else {
Ben Murdochfdd37112011-08-05 15:48:14 +0100988 if (tab.inForeground() && !handler.suppressDialog()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700989 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
990 } else {
991 handler.cancel();
992 }
993 }
994 }
995
996 @Override
997 public void onDownloadStart(Tab tab, String url, String userAgent,
998 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000999 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -05001000 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001001 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
1002 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001003 // This Tab was opened for the sole purpose of downloading a
1004 // file. Remove it.
1005 if (tab == mTabControl.getCurrentTab()) {
1006 // In this case, the Tab is still on top.
1007 goBackOnePageOrQuit();
1008 } else {
1009 // In this case, it is not.
1010 closeTab(tab);
1011 }
1012 }
1013 }
1014
1015 @Override
1016 public Bitmap getDefaultVideoPoster() {
1017 return mUi.getDefaultVideoPoster();
1018 }
1019
1020 @Override
1021 public View getVideoLoadingProgressView() {
1022 return mUi.getVideoLoadingProgressView();
1023 }
1024
1025 @Override
1026 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1027 SslError error) {
1028 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1029 }
1030
Patrick Scott92066772011-03-10 08:46:27 -05001031 @Override
1032 public void showAutoLogin(Tab tab) {
1033 assert tab.inForeground();
1034 // Update the title bar to show the auto-login request.
1035 mUi.showAutoLogin(tab);
1036 }
1037
1038 @Override
1039 public void hideAutoLogin(Tab tab) {
1040 assert tab.inForeground();
1041 mUi.hideAutoLogin(tab);
1042 }
1043
Michael Kolb8233fac2010-10-26 16:08:53 -07001044 // helper method
1045
1046 /*
1047 * Update the favorites icon if the private browsing isn't enabled and the
1048 * icon is valid.
1049 */
1050 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1051 final String url, Bitmap favicon) {
1052 if (favicon == null) {
1053 return;
1054 }
1055 if (!tab.isPrivateBrowsingEnabled()) {
1056 Bookmarks.updateFavicon(mActivity
1057 .getContentResolver(), originalUrl, url, favicon);
1058 }
1059 }
1060
Leon Scroggins4cd97792010-12-03 15:31:56 -05001061 @Override
1062 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001063 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001064 mUi.bookmarkedStatusHasChanged(tab);
1065 }
1066
Michael Kolb8233fac2010-10-26 16:08:53 -07001067 // end WebViewController
1068
1069 protected void pageUp() {
1070 getCurrentTopWebView().pageUp(false);
1071 }
1072
1073 protected void pageDown() {
1074 getCurrentTopWebView().pageDown(false);
1075 }
1076
1077 // callback from phone title bar
1078 public void editUrl() {
1079 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001080 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001081 }
1082
Michael Kolbcfa3af52010-12-14 10:36:11 -08001083 public void startVoiceSearch() {
1084 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1085 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1086 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1087 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1088 mActivity.getComponentName().flattenToString());
1089 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001090 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001091 mActivity.startActivity(intent);
1092 }
1093
Michael Kolb11d19782011-03-20 10:17:40 -07001094 @Override
1095 public void activateVoiceSearchMode(String title, List<String> results) {
1096 mUi.showVoiceTitleBar(title, results);
Michael Kolb8233fac2010-10-26 16:08:53 -07001097 }
1098
1099 public void revertVoiceSearchMode(Tab tab) {
1100 mUi.revertVoiceTitleBar(tab);
1101 }
1102
Michael Kolb736990c2011-03-20 10:01:20 -07001103 public boolean supportsVoiceSearch() {
John Reck35e9dd62011-04-25 09:01:54 -07001104 SearchEngine searchEngine = getSettings().getSearchEngine();
Michael Kolb736990c2011-03-20 10:01:20 -07001105 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1106 }
1107
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001108 public void showCustomView(Tab tab, View view, int requestedOrientation,
Michael Kolb8233fac2010-10-26 16:08:53 -07001109 WebChromeClient.CustomViewCallback callback) {
1110 if (tab.inForeground()) {
1111 if (mUi.isCustomViewShowing()) {
1112 callback.onCustomViewHidden();
1113 return;
1114 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001115 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001116 // Save the menu state and set it to empty while the custom
1117 // view is showing.
1118 mOldMenuState = mMenuState;
1119 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001120 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001121 }
1122 }
1123
1124 @Override
1125 public void hideCustomView() {
1126 if (mUi.isCustomViewShowing()) {
1127 mUi.onHideCustomView();
1128 // Reset the old menu state.
1129 mMenuState = mOldMenuState;
1130 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001131 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001132 }
1133 }
1134
1135 protected void onActivityResult(int requestCode, int resultCode,
1136 Intent intent) {
1137 if (getCurrentTopWebView() == null) return;
1138 switch (requestCode) {
1139 case PREFERENCES_PAGE:
1140 if (resultCode == Activity.RESULT_OK && intent != null) {
1141 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001142 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001143 mTabControl.removeParentChildRelationShips();
1144 }
1145 }
1146 break;
1147 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001148 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001149 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001150 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001151 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001152 case AUTOFILL_SETUP:
1153 // Determine whether a profile was actually set up or not
1154 // and if so, send the message back to the WebTextView to
1155 // fill the form with the new profile.
1156 if (getSettings().getAutoFillProfile() != null) {
1157 mAutoFillSetupMessage.sendToTarget();
1158 mAutoFillSetupMessage = null;
1159 }
1160 break;
John Reckd3e4d5b2011-07-13 15:48:43 -07001161 case COMBO_VIEW:
1162 if (intent == null || resultCode != Activity.RESULT_OK) {
1163 break;
1164 }
John Reck3ba45532011-08-11 16:26:53 -07001165 mUi.showWeb(false);
John Reckd3e4d5b2011-07-13 15:48:43 -07001166 if (Intent.ACTION_VIEW.equals(intent.getAction())) {
1167 Tab t = getCurrentTab();
1168 Uri uri = intent.getData();
1169 loadUrl(t, uri.toString());
1170 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
1171 String[] urls = intent.getStringArrayExtra(
1172 ComboViewActivity.EXTRA_OPEN_ALL);
1173 Tab parent = getCurrentTab();
1174 for (String url : urls) {
1175 parent = openTab(url, parent,
1176 !mSettings.openInBackground(), true);
1177 }
1178 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
1179 long id = intent.getLongExtra(
1180 ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
1181 if (id >= 0) {
1182 createNewSnapshotTab(id, true);
1183 }
1184 }
1185 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001186 default:
1187 break;
1188 }
1189 getCurrentTopWebView().requestFocus();
1190 }
1191
1192 /**
1193 * Open the Go page.
1194 * @param startWithHistory If true, open starting on the history tab.
1195 * Otherwise, start with the bookmarks tab.
1196 */
1197 @Override
1198 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1199 if (mTabControl.getCurrentWebView() == null) {
1200 return;
1201 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001202 // clear action mode
1203 if (isInCustomActionMode()) {
1204 endActionMode();
1205 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001206 Bundle extras = new Bundle();
1207 // Disable opening in a new window if we have maxed out the windows
1208 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1209 !mTabControl.canCreateNewTab());
John Reck2bc80422011-06-30 15:11:49 -07001210 mUi.showComboView(startWithHistory
1211 ? ComboViews.History : ComboViews.Bookmarks, extras);
Michael Kolb8233fac2010-10-26 16:08:53 -07001212 }
1213
1214 // combo view callbacks
1215
Michael Kolb8233fac2010-10-26 16:08:53 -07001216 // key handling
1217 protected void onBackKey() {
1218 if (!mUi.onBackKey()) {
1219 WebView subwindow = mTabControl.getCurrentSubWindow();
1220 if (subwindow != null) {
1221 if (subwindow.canGoBack()) {
1222 subwindow.goBack();
1223 } else {
1224 dismissSubWindow(mTabControl.getCurrentTab());
1225 }
1226 } else {
1227 goBackOnePageOrQuit();
1228 }
1229 }
1230 }
1231
Michael Kolb4bd767d2011-05-27 11:33:55 -07001232 protected boolean onMenuKey() {
1233 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001234 }
1235
Michael Kolb8233fac2010-10-26 16:08:53 -07001236 // menu handling and state
1237 // TODO: maybe put into separate handler
1238
1239 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckd73c5a22010-12-22 10:22:50 -08001240 if (mMenuState == EMPTY_MENU) {
1241 return false;
1242 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001243 MenuInflater inflater = mActivity.getMenuInflater();
1244 inflater.inflate(R.menu.browser, menu);
1245 updateInLoadMenuItems(menu);
1246 // hold on to the menu reference here; it is used by the page callbacks
1247 // to update the menu based on loading state
1248 mCachedMenu = menu;
1249 return true;
1250 }
1251
1252 protected void onCreateContextMenu(ContextMenu menu, View v,
1253 ContextMenuInfo menuInfo) {
John Reck0f602f32011-07-07 15:38:43 -07001254 if (v instanceof TitleBar) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001255 return;
1256 }
1257 if (!(v instanceof WebView)) {
1258 return;
1259 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001260 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001261 WebView.HitTestResult result = webview.getHitTestResult();
1262 if (result == null) {
1263 return;
1264 }
1265
1266 int type = result.getType();
1267 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1268 Log.w(LOGTAG,
1269 "We should not show context menu when nothing is touched");
1270 return;
1271 }
1272 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1273 // let TextView handles context menu
1274 return;
1275 }
1276
1277 // Note, http://b/issue?id=1106666 is requesting that
1278 // an inflated menu can be used again. This is not available
1279 // yet, so inflate each time (yuk!)
1280 MenuInflater inflater = mActivity.getMenuInflater();
1281 inflater.inflate(R.menu.browsercontext, menu);
1282
1283 // Show the correct menu group
1284 final String extra = result.getExtra();
1285 menu.setGroupVisible(R.id.PHONE_MENU,
1286 type == WebView.HitTestResult.PHONE_TYPE);
1287 menu.setGroupVisible(R.id.EMAIL_MENU,
1288 type == WebView.HitTestResult.EMAIL_TYPE);
1289 menu.setGroupVisible(R.id.GEO_MENU,
1290 type == WebView.HitTestResult.GEO_TYPE);
1291 menu.setGroupVisible(R.id.IMAGE_MENU,
1292 type == WebView.HitTestResult.IMAGE_TYPE
1293 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1294 menu.setGroupVisible(R.id.ANCHOR_MENU,
1295 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1296 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001297 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1298 || type == WebView.HitTestResult.PHONE_TYPE
1299 || type == WebView.HitTestResult.EMAIL_TYPE
1300 || type == WebView.HitTestResult.GEO_TYPE;
1301 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1302 if (hitText) {
1303 menu.findItem(R.id.select_text_menu_id)
1304 .setOnMenuItemClickListener(new SelectText(webview));
1305 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001306 // Setup custom handling depending on the type
1307 switch (type) {
1308 case WebView.HitTestResult.PHONE_TYPE:
1309 menu.setHeaderTitle(Uri.decode(extra));
1310 menu.findItem(R.id.dial_context_menu_id).setIntent(
1311 new Intent(Intent.ACTION_VIEW, Uri
1312 .parse(WebView.SCHEME_TEL + extra)));
1313 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1314 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1315 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1316 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1317 addIntent);
1318 menu.findItem(R.id.copy_phone_context_menu_id)
1319 .setOnMenuItemClickListener(
1320 new Copy(extra));
1321 break;
1322
1323 case WebView.HitTestResult.EMAIL_TYPE:
1324 menu.setHeaderTitle(extra);
1325 menu.findItem(R.id.email_context_menu_id).setIntent(
1326 new Intent(Intent.ACTION_VIEW, Uri
1327 .parse(WebView.SCHEME_MAILTO + extra)));
1328 menu.findItem(R.id.copy_mail_context_menu_id)
1329 .setOnMenuItemClickListener(
1330 new Copy(extra));
1331 break;
1332
1333 case WebView.HitTestResult.GEO_TYPE:
1334 menu.setHeaderTitle(extra);
1335 menu.findItem(R.id.map_context_menu_id).setIntent(
1336 new Intent(Intent.ACTION_VIEW, Uri
1337 .parse(WebView.SCHEME_GEO
1338 + URLEncoder.encode(extra))));
1339 menu.findItem(R.id.copy_geo_context_menu_id)
1340 .setOnMenuItemClickListener(
1341 new Copy(extra));
1342 break;
1343
1344 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1345 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001346 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001347 // decide whether to show the open link in new tab option
1348 boolean showNewTab = mTabControl.canCreateNewTab();
1349 MenuItem newTabItem
1350 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001351 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001352 ? R.string.contextmenu_openlink_newwindow_background
1353 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001354 newTabItem.setVisible(showNewTab);
1355 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001356 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1357 newTabItem.setOnMenuItemClickListener(
1358 new MenuItem.OnMenuItemClickListener() {
1359 @Override
1360 public boolean onMenuItemClick(MenuItem item) {
1361 final HashMap<String, WebView> hrefMap =
1362 new HashMap<String, WebView>();
1363 hrefMap.put("webview", webview);
1364 final Message msg = mHandler.obtainMessage(
1365 FOCUS_NODE_HREF,
1366 R.id.open_newtab_context_menu_id,
1367 0, hrefMap);
1368 webview.requestFocusNodeHref(msg);
1369 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001370 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001371 });
1372 } else {
1373 newTabItem.setOnMenuItemClickListener(
1374 new MenuItem.OnMenuItemClickListener() {
1375 @Override
1376 public boolean onMenuItemClick(MenuItem item) {
1377 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001378 openTab(extra, parent,
1379 !mSettings.openInBackground(),
1380 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001381 return true;
1382 }
1383 });
1384 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001385 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001386 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1387 break;
1388 }
1389 // otherwise fall through to handle image part
1390 case WebView.HitTestResult.IMAGE_TYPE:
1391 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1392 menu.setHeaderTitle(extra);
1393 }
1394 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1395 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1396 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001397 setOnMenuItemClickListener(
1398 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001399 menu.findItem(R.id.set_wallpaper_context_menu_id).
1400 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1401 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001402 break;
1403
1404 default:
1405 Log.w(LOGTAG, "We should not get here.");
1406 break;
1407 }
1408 //update the ui
1409 mUi.onContextMenuCreated(menu);
1410 }
1411
1412 /**
1413 * As the menu can be open when loading state changes
1414 * we must manually update the state of the stop/reload menu
1415 * item
1416 */
1417 private void updateInLoadMenuItems(Menu menu) {
1418 if (menu == null) {
1419 return;
1420 }
1421 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1422 MenuItem src = mInLoad ?
1423 menu.findItem(R.id.stop_menu_id):
1424 menu.findItem(R.id.reload_menu_id);
1425 if (src != null) {
1426 dest.setIcon(src.getIcon());
1427 dest.setTitle(src.getTitle());
1428 }
1429 }
1430
John Reckb3417f02011-01-14 11:01:05 -08001431 boolean onPrepareOptionsMenu(Menu menu) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001432 // Note: setVisible will decide whether an item is visible; while
1433 // setEnabled() will decide whether an item is enabled, which also means
1434 // whether the matching shortcut key will function.
1435 switch (mMenuState) {
1436 case EMPTY_MENU:
1437 if (mCurrentMenuState != mMenuState) {
1438 menu.setGroupVisible(R.id.MAIN_MENU, false);
1439 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1440 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1441 }
1442 break;
1443 default:
1444 if (mCurrentMenuState != mMenuState) {
1445 menu.setGroupVisible(R.id.MAIN_MENU, true);
1446 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1447 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1448 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001449 updateMenuState(getCurrentTab(), menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001450 break;
1451 }
1452 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001453 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001454 }
1455
Michael Kolb4bf79712011-07-14 14:18:12 -07001456 @Override
1457 public void updateMenuState(Tab tab, Menu menu) {
1458 boolean canGoBack = false;
1459 boolean canGoForward = false;
1460 boolean isHome = false;
John Reck42229bc2011-08-19 13:26:43 -07001461 boolean isDesktopUa = false;
Michael Kolb4bf79712011-07-14 14:18:12 -07001462 if (tab != null) {
1463 canGoBack = tab.canGoBack();
1464 canGoForward = tab.canGoForward();
1465 isHome = mSettings.getHomePage().equals(tab.getUrl());
John Reck42229bc2011-08-19 13:26:43 -07001466 isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
Michael Kolb4bf79712011-07-14 14:18:12 -07001467 }
1468 final MenuItem back = menu.findItem(R.id.back_menu_id);
1469 back.setEnabled(canGoBack);
1470
1471 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1472 home.setEnabled(!isHome);
1473
1474 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1475 forward.setEnabled(canGoForward);
1476
1477 final MenuItem source = menu.findItem(mInLoad ? R.id.stop_menu_id : R.id.reload_menu_id);
1478 final MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolb7ab75ee2011-07-14 16:36:38 -07001479 if (source != null && dest != null) {
1480 dest.setTitle(source.getTitle());
1481 dest.setIcon(source.getIcon());
1482 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001483
1484 // decide whether to show the share link option
1485 PackageManager pm = mActivity.getPackageManager();
1486 Intent send = new Intent(Intent.ACTION_SEND);
1487 send.setType("text/plain");
1488 ResolveInfo ri = pm.resolveActivity(send,
1489 PackageManager.MATCH_DEFAULT_ONLY);
1490 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1491
1492 boolean isNavDump = mSettings.enableNavDump();
1493 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1494 nav.setVisible(isNavDump);
1495 nav.setEnabled(isNavDump);
1496
1497 boolean showDebugSettings = mSettings.isDebugEnabled();
1498 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1499 counter.setVisible(showDebugSettings);
1500 counter.setEnabled(showDebugSettings);
John Reck42229bc2011-08-19 13:26:43 -07001501 final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
1502 uaSwitcher.setChecked(isDesktopUa);
Michael Kolb4bf79712011-07-14 14:18:12 -07001503
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001504 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001505 }
1506
Michael Kolb8233fac2010-10-26 16:08:53 -07001507 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001508 if (null == getCurrentTopWebView()) {
1509 return false;
1510 }
1511 if (mMenuIsDown) {
1512 // The shortcut action consumes the MENU. Even if it is still down,
1513 // it won't trigger the next shortcut action. In the case of the
1514 // shortcut action triggering a new activity, like Bookmarks, we
1515 // won't get onKeyUp for MENU. So it is important to reset it here.
1516 mMenuIsDown = false;
1517 }
Michael Kolb3ca12752011-07-20 13:52:25 -07001518 if (mUi.onOptionsItemSelected(item)) {
1519 // ui callback handled it
1520 return true;
1521 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001522 switch (item.getItemId()) {
1523 // -- Main menu
1524 case R.id.new_tab_menu_id:
1525 openTabToHomePage();
1526 break;
1527
1528 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001529 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001530 break;
1531
1532 case R.id.goto_menu_id:
1533 editUrl();
1534 break;
1535
1536 case R.id.bookmarks_menu_id:
1537 bookmarksOrHistoryPicker(false);
1538 break;
1539
Michael Kolb8233fac2010-10-26 16:08:53 -07001540 case R.id.add_bookmark_menu_id:
John Recka60fffa2011-09-06 16:30:29 -07001541 Intent bookmarkIntent = createBookmarkCurrentPageIntent(false);
1542 if (bookmarkIntent != null) {
1543 mActivity.startActivity(bookmarkIntent);
1544 }
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) {
John Recka60fffa2011-09-06 16:30:29 -07001865 WebView w = getCurrentTopWebView();
1866 if (w == null) {
1867 return null;
1868 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001869 Intent i = new Intent(mActivity,
1870 AddBookmarkPage.class);
Michael Kolb8233fac2010-10-26 16:08:53 -07001871 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1872 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1873 String touchIconUrl = w.getTouchIconUrl();
1874 if (touchIconUrl != null) {
1875 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1876 WebSettings settings = w.getSettings();
1877 if (settings != null) {
1878 i.putExtra(AddBookmarkPage.USER_AGENT,
1879 settings.getUserAgentString());
1880 }
1881 }
1882 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1883 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1884 getDesiredThumbnailHeight(mActivity)));
1885 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07001886 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001887 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1888 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001889 // Put the dialog at the upper right of the screen, covering the
1890 // star on the title bar.
1891 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07001892 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07001893 }
1894
1895 // file chooser
1896 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1897 mUploadHandler = new UploadHandler(this);
1898 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1899 }
1900
1901 // thumbnails
1902
1903 /**
1904 * Return the desired width for thumbnail screenshots, which are stored in
1905 * the database, and used on the bookmarks screen.
1906 * @param context Context for finding out the density of the screen.
1907 * @return desired width for thumbnail screenshot.
1908 */
1909 static int getDesiredThumbnailWidth(Context context) {
1910 return context.getResources().getDimensionPixelOffset(
1911 R.dimen.bookmarkThumbnailWidth);
1912 }
1913
1914 /**
1915 * Return the desired height for thumbnail screenshots, which are stored in
1916 * the database, and used on the bookmarks screen.
1917 * @param context Context for finding out the density of the screen.
1918 * @return desired height for thumbnail screenshot.
1919 */
1920 static int getDesiredThumbnailHeight(Context context) {
1921 return context.getResources().getDimensionPixelOffset(
1922 R.dimen.bookmarkThumbnailHeight);
1923 }
1924
John Reck8cc92352011-07-06 17:41:52 -07001925 static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001926 // We render to a bitmap 2x the desired size so that we can then
1927 // re-scale it with filtering since canvas.scale doesn't filter
1928 // This helps reduce aliasing at the cost of being slightly blurry
1929 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001930 Picture thumbnail = view.capturePicture();
1931 if (thumbnail == null) {
1932 return null;
1933 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001934 width *= filter_scale;
1935 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001936 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1937 Canvas canvas = new Canvas(bm);
1938 // May need to tweak these values to determine what is the
1939 // best scale factor
1940 int thumbnailWidth = thumbnail.getWidth();
1941 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001942 float scaleFactor = 1.0f;
Michael Kolbeb95db42011-03-03 10:38:40 -08001943 if (thumbnailWidth > 0 && thumbnailHeight > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001944 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001945 } else {
1946 return null;
1947 }
John Reckfe49ab42010-11-16 17:09:37 -08001948
Michael Kolbeb95db42011-03-03 10:38:40 -08001949 float scaleFactorY = (float) height / (float)thumbnailHeight;
1950 if (scaleFactorY > scaleFactor) {
1951 // The picture is narrower than the requested AR
1952 // Center the thumnail and crop the sides
1953 scaleFactor = scaleFactorY;
John Reckfe49ab42010-11-16 17:09:37 -08001954 float wx = (thumbnailWidth * scaleFactor) - width;
1955 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001956 }
1957
John Reckfe49ab42010-11-16 17:09:37 -08001958 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001959
1960 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001961 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
1962 height / filter_scale, true);
Dianne Hackborn43cfe8a2011-08-02 16:59:35 -07001963 canvas.setBitmap(null);
John Reck5c6ac2f2011-01-05 10:18:03 -08001964 bm.recycle();
1965 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001966 }
1967
John Reck34ef2672011-02-10 11:30:55 -08001968 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001969 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07001970 // FIXME: Would like to make sure there is actually something to
1971 // draw, but the API for that (WebViewCore.pictureReady()) is not
1972 // currently accessible here.
1973
John Reck34ef2672011-02-10 11:30:55 -08001974 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08001975 if (view == null) {
1976 // Tab was destroyed
1977 return;
1978 }
John Reck34ef2672011-02-10 11:30:55 -08001979 final String url = tab.getUrl();
1980 final String originalUrl = view.getOriginalUrl();
1981
1982 if (TextUtils.isEmpty(url)) {
1983 return;
1984 }
1985
1986 // Only update thumbnails for web urls (http(s)://), not for
1987 // about:, javascript:, data:, etc...
1988 // Unless it is a bookmarked site, then always update
1989 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
1990 return;
1991 }
1992
Michael Kolb8233fac2010-10-26 16:08:53 -07001993 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1994 getDesiredThumbnailHeight(mActivity));
1995 if (bm == null) {
1996 return;
1997 }
1998
1999 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002000 new AsyncTask<Void, Void, Void>() {
2001 @Override
2002 protected Void doInBackground(Void... unused) {
2003 Cursor cursor = null;
2004 try {
2005 // TODO: Clean this up
2006 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2007 if (cursor != null && cursor.moveToFirst()) {
2008 final ByteArrayOutputStream os =
2009 new ByteArrayOutputStream();
2010 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002011
John Reck34ef2672011-02-10 11:30:55 -08002012 ContentValues values = new ContentValues();
2013 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002014
John Reck34ef2672011-02-10 11:30:55 -08002015 do {
John Reck617fd832011-02-16 14:35:59 -08002016 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002017 cr.update(Images.CONTENT_URI, values, null, null);
2018 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002019 }
John Reck34ef2672011-02-10 11:30:55 -08002020 } catch (IllegalStateException e) {
2021 // Ignore
2022 } finally {
2023 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002024 }
John Reck34ef2672011-02-10 11:30:55 -08002025 return null;
2026 }
2027 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002028 }
2029
2030 private class Copy implements OnMenuItemClickListener {
2031 private CharSequence mText;
2032
2033 public boolean onMenuItemClick(MenuItem item) {
2034 copy(mText);
2035 return true;
2036 }
2037
2038 public Copy(CharSequence toCopy) {
2039 mText = toCopy;
2040 }
2041 }
2042
Leon Scroggins63c02662010-11-18 15:16:27 -05002043 private static class Download implements OnMenuItemClickListener {
2044 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002045 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002046 private boolean mPrivateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002047
2048 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002049 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002050 null, null, mPrivateBrowsing);
Michael Kolb8233fac2010-10-26 16:08:53 -07002051 return true;
2052 }
2053
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002054 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002055 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002056 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002057 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002058 }
2059 }
2060
Cary Clark8974d282010-11-22 10:46:05 -05002061 private static class SelectText implements OnMenuItemClickListener {
2062 private WebView mWebView;
2063
2064 public boolean onMenuItemClick(MenuItem item) {
2065 if (mWebView != null) {
2066 return mWebView.selectText();
2067 }
2068 return false;
2069 }
2070
2071 public SelectText(WebView webView) {
2072 mWebView = webView;
2073 }
2074
2075 }
2076
Michael Kolb8233fac2010-10-26 16:08:53 -07002077 /********************** TODO: UI stuff *****************************/
2078
2079 // these methods have been copied, they still need to be cleaned up
2080
2081 /****************** tabs ***************************************************/
2082
2083 // basic tab interactions:
2084
2085 // it is assumed that tabcontrol already knows about the tab
2086 protected void addTab(Tab tab) {
2087 mUi.addTab(tab);
2088 }
2089
2090 protected void removeTab(Tab tab) {
2091 mUi.removeTab(tab);
2092 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002093 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002094 }
2095
Michael Kolbf2055602011-04-09 17:20:03 -07002096 @Override
2097 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002098 // monkey protection against delayed start
2099 if (tab != null) {
2100 mTabControl.setCurrentTab(tab);
2101 // the tab is guaranteed to have a webview after setCurrentTab
2102 mUi.setActiveTab(tab);
2103 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002104 }
2105
John Reck8bcafc12011-08-29 16:43:02 -07002106 protected void closeEmptyTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002107 Tab current = mTabControl.getCurrentTab();
2108 if (current != null
2109 && current.getWebView().copyBackForwardList().getSize() == 0) {
John Reck8bcafc12011-08-29 16:43:02 -07002110 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002111 }
2112 }
2113
John Reck26b18322011-06-21 13:08:58 -07002114 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002115 // Dismiss the subwindow if applicable.
2116 dismissSubWindow(appTab);
2117 // Since we might kill the WebView, remove it from the
2118 // content view first.
2119 mUi.detachTab(appTab);
2120 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002121 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002122 // TODO: analyze why the remove and add are necessary
2123 mUi.attachTab(appTab);
2124 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002125 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002126 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002127 } else {
2128 // If the tab was the current tab, we have to attach
2129 // it to the view system again.
2130 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002131 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002132 }
2133 }
2134
2135 // Remove the sub window if it exists. Also called by TabControl when the
2136 // user clicks the 'X' to dismiss a sub window.
2137 public void dismissSubWindow(Tab tab) {
2138 removeSubWindow(tab);
2139 // dismiss the subwindow. This will destroy the WebView.
2140 tab.dismissSubWindow();
2141 getCurrentTopWebView().requestFocus();
2142 }
2143
2144 @Override
2145 public void removeSubWindow(Tab t) {
2146 if (t.getSubWebView() != null) {
2147 mUi.removeSubWindow(t.getSubViewContainer());
2148 }
2149 }
2150
2151 @Override
2152 public void attachSubWindow(Tab tab) {
2153 if (tab.getSubWebView() != null) {
2154 mUi.attachSubWindow(tab.getSubViewContainer());
2155 getCurrentTopWebView().requestFocus();
2156 }
2157 }
2158
Mathew Inwood29721c22011-06-29 17:55:24 +01002159 private Tab showPreloadedTab(final UrlData urlData) {
2160 if (!urlData.isPreloaded()) {
2161 return null;
2162 }
2163 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2164 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2165 if (sbQuery != null) {
Mathew Inwoodb4e831b2011-09-05 18:58:48 +01002166 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders,
2167 urlData.getOnLoadCompletePendingIntent())) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002168 // 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();
Mathew Inwoode09305e2011-09-02 12:03:26 +01002181 t.refreshIdAfterPreload();
Mathew Inwood29721c22011-06-29 17:55:24 +01002182 mTabControl.addPreloadedTab(t);
2183 addTab(t);
2184 setActiveTab(t);
Mathew Inwoodb4e831b2011-09-05 18:58:48 +01002185 if (sbQuery == null) {
2186 // if the searchbox query is set, the load complete notification is handled within
2187 // the preloaded tab controller.
2188 if (t.inPageLoad()) {
2189 requestLoadCompleteNotification(urlData.mOnLoadCompletePendingIntent, t,
2190 urlData.mUrl, true, true);
2191 } else {
2192 // the page is already fully loaded
2193 IntentHandler.sendPageLoadCompletePendingIntent(mActivity,
2194 urlData.mOnLoadCompletePendingIntent, true, true);
2195 }
2196 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002197 return t;
2198 }
2199
Michael Kolb7bcafde2011-05-09 13:55:59 -07002200 // open a non inconito tab with the given url data
2201 // and set as active tab
2202 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002203 Tab tab = showPreloadedTab(urlData);
2204 if (tab == null) {
2205 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002206 if ((tab != null) && !urlData.isEmpty()) {
2207 loadUrlDataIn(tab, urlData);
2208 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002209 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002210 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002211 }
2212
Michael Kolb843510f2010-12-09 10:51:49 -08002213 @Override
2214 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002215 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002216 }
2217
Michael Kolb8233fac2010-10-26 16:08:53 -07002218 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002219 public Tab openIncognitoTab() {
2220 return openTab(INCOGNITO_URI, true, true, false);
2221 }
2222
2223 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002224 public Tab openTab(String url, boolean incognito, boolean setActive,
2225 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002226 return openTab(url, incognito, setActive, useCurrent, null);
2227 }
2228
2229 @Override
2230 public Tab openTab(String url, Tab parent, boolean setActive,
2231 boolean useCurrent) {
2232 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2233 setActive, useCurrent, parent);
2234 }
2235
2236 public Tab openTab(String url, boolean incognito, boolean setActive,
2237 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002238 Tab tab = createNewTab(incognito, setActive, useCurrent);
2239 if (tab != null) {
John Reck5949c662011-05-27 09:52:29 -07002240 if (parent != null && parent != tab) {
2241 parent.addChildTab(tab);
2242 }
Michael Kolb519d2282011-05-09 17:03:19 -07002243 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002244 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002245 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002246 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002247 return tab;
2248 }
2249
2250 // this method will attempt to create a new tab
2251 // incognito: private browsing tab
2252 // setActive: ste tab as current tab
2253 // useCurrent: if no new tab can be created, return current tab
2254 private Tab createNewTab(boolean incognito, boolean setActive,
2255 boolean useCurrent) {
2256 Tab tab = null;
2257 if (mTabControl.canCreateNewTab()) {
2258 tab = mTabControl.createNewTab(incognito);
2259 addTab(tab);
2260 if (setActive) {
2261 setActiveTab(tab);
2262 }
2263 } else {
2264 if (useCurrent) {
2265 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002266 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002267 } else {
2268 mUi.showMaxTabsWarning();
2269 }
2270 }
2271 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002272 }
2273
John Reck2bc80422011-06-30 15:11:49 -07002274 @Override
2275 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2276 SnapshotTab tab = null;
2277 if (mTabControl.canCreateNewTab()) {
2278 tab = mTabControl.createSnapshotTab(snapshotId);
2279 addTab(tab);
2280 if (setActive) {
2281 setActiveTab(tab);
2282 }
2283 } else {
2284 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07002285 }
2286 return tab;
2287 }
2288
Michael Kolb8233fac2010-10-26 16:08:53 -07002289 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002290 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002291 * @return boolean True if we successfully switched to a different tab. If
2292 * the indexth tab is null, or if that tab is the same as
2293 * the current one, return false.
2294 */
2295 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002296 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002297 Tab currentTab = mTabControl.getCurrentTab();
2298 if (tab == null || tab == currentTab) {
2299 return false;
2300 }
2301 setActiveTab(tab);
2302 return true;
2303 }
2304
2305 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002306 public void closeCurrentTab() {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002307 closeCurrentTab(false);
2308 }
2309
2310 protected void closeCurrentTab(boolean andQuit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002311 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07002312 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07002313 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08002314 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002315 return;
2316 }
Michael Kolbc831b632011-05-11 09:30:34 -07002317 final Tab current = mTabControl.getCurrentTab();
2318 final int pos = mTabControl.getCurrentPosition();
2319 Tab newTab = current.getParent();
2320 if (newTab == null) {
2321 newTab = mTabControl.getTab(pos + 1);
2322 if (newTab == null) {
2323 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002324 }
2325 }
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002326 if (andQuit) {
2327 mTabControl.setCurrentTab(newTab);
2328 closeTab(current);
2329 } else if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002330 // Close window
2331 closeTab(current);
2332 }
2333 }
2334
2335 /**
2336 * Close the tab, remove its associated title bar, and adjust mTabControl's
2337 * current tab to a valid value.
2338 */
2339 @Override
2340 public void closeTab(Tab tab) {
Michael Kolb2d59c322011-01-25 13:18:55 -08002341 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002342 }
2343
Michael Kolb8233fac2010-10-26 16:08:53 -07002344 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07002345 protected void loadUrlFromContext(String url) {
2346 Tab tab = getCurrentTab();
2347 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002348 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07002349 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002350 url = UrlUtils.smartUrlFilter(url);
2351 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07002352 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07002353 }
2354 }
2355 }
2356
2357 /**
2358 * Load the URL into the given WebView and update the title bar
2359 * to reflect the new load. Call this instead of WebView.loadUrl
2360 * directly.
2361 * @param view The WebView used to load url.
2362 * @param url The URL to load.
2363 */
John Reck71e51422011-07-01 16:49:28 -07002364 @Override
2365 public void loadUrl(Tab tab, String url) {
John Reck26b18322011-06-21 13:08:58 -07002366 loadUrl(tab, url, null);
2367 }
2368
2369 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
2370 if (tab != null) {
2371 dismissSubWindow(tab);
2372 tab.loadUrl(url, headers);
2373 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002374 }
2375
2376 /**
2377 * Load UrlData into a Tab and update the title bar to reflect the new
2378 * load. Call this instead of UrlData.loadIn directly.
2379 * @param t The Tab used to load.
2380 * @param data The UrlData being loaded.
2381 */
2382 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07002383 if (data != null) {
2384 if (data.mVoiceIntent != null) {
2385 t.activateVoiceSearchMode(data.mVoiceIntent);
Michael Kolb14612442011-06-24 13:06:29 -07002386 } else if (data.isPreloaded()) {
2387 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07002388 } else {
2389 loadUrl(t, data.mUrl, data.mHeaders);
Mathew Inwoodb4e831b2011-09-05 18:58:48 +01002390 requestLoadCompleteNotification(data.mOnLoadCompletePendingIntent, t, data.mUrl,
2391 null, null);
John Reck26b18322011-06-21 13:08:58 -07002392 }
2393 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002394 }
2395
Mathew Inwoodb4e831b2011-09-05 18:58:48 +01002396 private void requestLoadCompleteNotification(final PendingIntent loadCompletePendingIntent,
2397 Tab t, String forUrl, final Boolean preloaded, final Boolean preloadSuccess) {
2398 if (loadCompletePendingIntent != null) {
2399 Pattern urlMatch = Pattern.compile(Pattern.quote(forUrl));
2400 t.setOnPageLoadCompleteListener(urlMatch, new Tab.OnPageLoadCompleteListener() {
2401 @Override
2402 public void onPageLoadComplete() {
2403 IntentHandler.sendPageLoadCompletePendingIntent(mActivity,
2404 loadCompletePendingIntent, preloaded, preloadSuccess);
2405 }
2406 });
2407 }
2408 }
2409
John Reck30c714c2010-12-16 17:30:34 -08002410 @Override
2411 public void onUserCanceledSsl(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08002412 // TODO: Figure out the "right" behavior
John Reckef654f12011-07-12 16:42:08 -07002413 if (tab.canGoBack()) {
2414 tab.goBack();
John Reck30c714c2010-12-16 17:30:34 -08002415 } else {
John Reckef654f12011-07-12 16:42:08 -07002416 tab.loadUrl(mSettings.getHomePage(), null);
John Reck30c714c2010-12-16 17:30:34 -08002417 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002418 }
2419
2420 void goBackOnePageOrQuit() {
2421 Tab current = mTabControl.getCurrentTab();
2422 if (current == null) {
2423 /*
2424 * Instead of finishing the activity, simply push this to the back
2425 * of the stack and let ActivityManager to choose the foreground
2426 * activity. As BrowserActivity is singleTask, it will be always the
2427 * root of the task. So we can use either true or false for
2428 * moveTaskToBack().
2429 */
2430 mActivity.moveTaskToBack(true);
2431 return;
2432 }
John Reckef654f12011-07-12 16:42:08 -07002433 if (current.canGoBack()) {
2434 current.goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07002435 } else {
2436 // Check to see if we are closing a window that was created by
2437 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002438 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002439 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002440 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002441 // Now we close the other tab
2442 closeTab(current);
2443 } else {
Michael Kolbe28b3472011-08-04 16:54:31 -07002444 if ((current.getAppId() != null) || current.closeOnBack()) {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002445 closeCurrentTab(true);
Michael Kolbe28b3472011-08-04 16:54:31 -07002446 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002447 /*
2448 * Instead of finishing the activity, simply push this to the back
2449 * of the stack and let ActivityManager to choose the foreground
2450 * activity. As BrowserActivity is singleTask, it will be always the
2451 * root of the task. So we can use either true or false for
2452 * moveTaskToBack().
2453 */
2454 mActivity.moveTaskToBack(true);
2455 }
2456 }
2457 }
2458
2459 /**
2460 * Feed the previously stored results strings to the BrowserProvider so that
2461 * the SearchDialog will show them instead of the standard searches.
2462 * @param result String to show on the editable line of the SearchDialog.
2463 */
2464 @Override
2465 public void showVoiceSearchResults(String result) {
2466 ContentProviderClient client = mActivity.getContentResolver()
2467 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2468 ContentProvider prov = client.getLocalContentProvider();
2469 BrowserProvider bp = (BrowserProvider) prov;
2470 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2471 client.release();
2472
2473 Bundle bundle = createGoogleSearchSourceBundle(
2474 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2475 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2476 startSearch(result, false, bundle, false);
2477 }
2478
2479 private void startSearch(String initialQuery, boolean selectInitialQuery,
2480 Bundle appSearchData, boolean globalSearch) {
2481 if (appSearchData == null) {
2482 appSearchData = createGoogleSearchSourceBundle(
2483 GOOGLE_SEARCH_SOURCE_TYPE);
2484 }
2485
2486 SearchEngine searchEngine = mSettings.getSearchEngine();
2487 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2488 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2489 }
2490 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2491 globalSearch);
2492 }
2493
2494 private Bundle createGoogleSearchSourceBundle(String source) {
2495 Bundle bundle = new Bundle();
2496 bundle.putString(Search.SOURCE, source);
2497 return bundle;
2498 }
2499
2500 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002501 * helper method for key handler
2502 * returns the current tab if it can't advance
2503 */
Michael Kolbc831b632011-05-11 09:30:34 -07002504 private Tab getNextTab() {
2505 return mTabControl.getTab(Math.min(mTabControl.getTabCount() - 1,
2506 mTabControl.getCurrentPosition() + 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002507 }
2508
2509 /**
2510 * helper method for key handler
2511 * returns the current tab if it can't advance
2512 */
Michael Kolbc831b632011-05-11 09:30:34 -07002513 private Tab getPrevTab() {
2514 return mTabControl.getTab(Math.max(0,
2515 mTabControl.getCurrentPosition() - 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002516 }
2517
2518 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002519 * handle key events in browser
2520 *
2521 * @param keyCode
2522 * @param event
2523 * @return true if handled, false to pass to super
2524 */
2525 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002526 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002527 // Even if MENU is already held down, we need to call to super to open
2528 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002529 if (!noModifiers
2530 && ((KeyEvent.KEYCODE_MENU == keyCode)
2531 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2532 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002533 mMenuIsDown = true;
2534 return false;
2535 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002536
Cary Clark8ff8c662010-12-29 15:03:05 -05002537 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07002538 Tab tab = getCurrentTab();
2539 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05002540
Cary Clark160bbb92011-01-10 11:17:07 -05002541 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2542 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002543
Michael Kolb8233fac2010-10-26 16:08:53 -07002544 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002545 case KeyEvent.KEYCODE_TAB:
2546 if (event.isCtrlPressed()) {
2547 if (event.isShiftPressed()) {
2548 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002549 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002550 } else {
2551 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002552 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002553 }
2554 return true;
2555 }
2556 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002557 case KeyEvent.KEYCODE_SPACE:
2558 // WebView/WebTextView handle the keys in the KeyDown. As
2559 // the Activity's shortcut keys are only handled when WebView
2560 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002561 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002562 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002563 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002564 pageDown();
2565 }
2566 return true;
2567 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002568 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002569 event.startTracking();
2570 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07002571 case KeyEvent.KEYCODE_FORWARD:
2572 if (!noModifiers) break;
2573 tab.goForward();
2574 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002575 case KeyEvent.KEYCODE_DPAD_LEFT:
2576 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002577 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05002578 return true;
2579 }
2580 break;
2581 case KeyEvent.KEYCODE_DPAD_RIGHT:
2582 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002583 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05002584 return true;
2585 }
2586 break;
2587 case KeyEvent.KEYCODE_A:
2588 if (ctrl) {
2589 webView.selectAll();
2590 return true;
2591 }
2592 break;
Michael Kolba4183062011-01-16 10:43:21 -08002593// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002594 case KeyEvent.KEYCODE_C:
2595 if (ctrl) {
2596 webView.copySelection();
2597 return true;
2598 }
2599 break;
Michael Kolba4183062011-01-16 10:43:21 -08002600// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002601// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002602// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002603// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002604// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002605// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002606// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002607// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002608// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002609// case KeyEvent.KEYCODE_M: // unused
2610// case KeyEvent.KEYCODE_N: // in Chrome: new window
2611// case KeyEvent.KEYCODE_O: // in Chrome: open file
2612// case KeyEvent.KEYCODE_P: // in Chrome: print page
2613// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002614// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002615// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2616 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002617 // we can't use the ctrl/shift flags, they check for
2618 // exclusive use of a modifier
2619 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002620 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002621 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002622 } else {
2623 openTabToHomePage();
2624 }
2625 return true;
2626 }
2627 break;
2628// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2629// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb5ae15bd2011-08-16 17:09:27 -07002630// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002631// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2632// case KeyEvent.KEYCODE_Y: // unused
2633// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002634 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002635 // it is a regular key and webview is not null
2636 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002637 }
2638
John Recke6bf4ab2011-02-24 15:48:05 -08002639 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2640 switch(keyCode) {
2641 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07002642 if (mUi.isWebShowing()) {
John Recke6bf4ab2011-02-24 15:48:05 -08002643 bookmarksOrHistoryPicker(true);
2644 return true;
2645 }
2646 break;
2647 }
2648 return false;
2649 }
2650
Michael Kolb8233fac2010-10-26 16:08:53 -07002651 boolean onKeyUp(int keyCode, KeyEvent event) {
Michael Kolb2814a362011-05-19 15:49:41 -07002652 if (KeyEvent.KEYCODE_MENU == keyCode) {
2653 mMenuIsDown = false;
2654 if (event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002655 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002656 }
2657 }
Cary Clark160bbb92011-01-10 11:17:07 -05002658 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002659 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002660 case KeyEvent.KEYCODE_BACK:
2661 if (event.isTracking() && !event.isCanceled()) {
2662 onBackKey();
2663 return true;
2664 }
2665 break;
2666 }
2667 return false;
2668 }
2669
2670 public boolean isMenuDown() {
2671 return mMenuIsDown;
2672 }
2673
Ben Murdoch8029a772010-11-16 11:58:21 +00002674 public void setupAutoFill(Message message) {
2675 // Open the settings activity at the AutoFill profile fragment so that
2676 // the user can create a new profile. When they return, we will dispatch
2677 // the message so that we can autofill the form using their new profile.
2678 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2679 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2680 AutoFillSettingsFragment.class.getName());
2681 mAutoFillSetupMessage = message;
2682 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2683 }
John Reckb3417f02011-01-14 11:01:05 -08002684
2685 @Override
Narayan Kamath5119edd2011-02-23 15:49:17 +00002686 public void registerDropdownChangeListener(DropdownChangeListener d) {
2687 mUi.registerDropdownChangeListener(d);
2688 }
Michael Kolbfbc579a2011-07-07 15:59:33 -07002689
2690 public boolean onSearchRequested() {
2691 mUi.editUrl(false);
2692 return true;
2693 }
2694
John Reck1cf4b792011-07-26 10:22:22 -07002695 @Override
2696 public boolean shouldCaptureThumbnails() {
2697 return mUi.shouldCaptureThumbnails();
2698 }
2699
Michael Kolbc3af0672011-08-09 10:24:41 -07002700 @Override
2701 public void setBlockEvents(boolean block) {
2702 mBlockEvents = block;
2703 }
2704
2705 public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002706 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002707 }
2708
2709 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002710 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002711 }
2712
2713 public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002714 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002715 }
2716
2717 public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002718 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002719 }
2720
2721 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002722 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002723 }
2724
Michael Kolb8233fac2010-10-26 16:08:53 -07002725}