blob: 8d8a2be3353584ea3e3fb28fbd87f5b9fdb9828e [file] [log] [blame]
Michael Kolb8233fac2010-10-26 16:08:53 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
Michael Kolb8233fac2010-10-26 16:08:53 -070019import android.app.Activity;
20import android.app.DownloadManager;
21import android.app.SearchManager;
22import android.content.ClipboardManager;
23import android.content.ContentProvider;
24import android.content.ContentProviderClient;
25import android.content.ContentResolver;
John Reckd8c74522011-06-14 08:45:00 -070026import android.content.ContentUris;
Michael Kolb8233fac2010-10-26 16:08:53 -070027import android.content.ContentValues;
28import android.content.Context;
29import android.content.Intent;
30import android.content.pm.PackageManager;
31import android.content.pm.ResolveInfo;
32import android.content.res.Configuration;
John Reck30b065e2011-07-19 10:58:05 -070033import android.content.res.TypedArray;
Leon Scroggins1961ed22010-12-07 15:22:21 -050034import android.database.ContentObserver;
Michael Kolb8233fac2010-10-26 16:08:53 -070035import android.database.Cursor;
36import android.database.sqlite.SQLiteDatabase;
Michael Kolb8233fac2010-10-26 16:08:53 -070037import android.graphics.Bitmap;
38import android.graphics.Canvas;
39import android.graphics.Picture;
40import android.net.Uri;
41import android.net.http.SslError;
42import android.os.AsyncTask;
43import android.os.Bundle;
44import android.os.Handler;
45import android.os.Message;
46import android.os.PowerManager;
47import android.os.PowerManager.WakeLock;
Ben Murdoch8029a772010-11-16 11:58:21 +000048import android.preference.PreferenceActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -070049import android.provider.Browser;
50import android.provider.BrowserContract;
Michael Kolb8233fac2010-10-26 16:08:53 -070051import android.provider.BrowserContract.Images;
52import android.provider.ContactsContract;
53import android.provider.ContactsContract.Intents.Insert;
Michael Kolbcfa3af52010-12-14 10:36:11 -080054import android.speech.RecognizerIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070055import android.text.TextUtils;
56import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080057import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070058import android.view.ActionMode;
59import android.view.ContextMenu;
60import android.view.ContextMenu.ContextMenuInfo;
61import android.view.Gravity;
62import android.view.KeyEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070063import android.view.Menu;
64import android.view.MenuInflater;
65import android.view.MenuItem;
66import android.view.MenuItem.OnMenuItemClickListener;
67import android.view.View;
68import android.webkit.CookieManager;
69import android.webkit.CookieSyncManager;
70import android.webkit.HttpAuthHandler;
71import android.webkit.SslErrorHandler;
72import android.webkit.ValueCallback;
73import android.webkit.WebChromeClient;
74import android.webkit.WebIconDatabase;
75import android.webkit.WebSettings;
76import android.webkit.WebView;
Leon Scrogginsac993842011-02-02 12:54:07 -050077import android.widget.Toast;
Michael Kolb8233fac2010-10-26 16:08:53 -070078
Michael Kolb4bd767d2011-05-27 11:33:55 -070079import com.android.browser.IntentHandler.UrlData;
John Reck2bc80422011-06-30 15:11:49 -070080import com.android.browser.UI.ComboViews;
Michael Kolb4bd767d2011-05-27 11:33:55 -070081import com.android.browser.UI.DropdownChangeListener;
82import com.android.browser.provider.BrowserProvider;
John Reck1cf4b792011-07-26 10:22:22 -070083import com.android.browser.provider.BrowserProvider2.Thumbnails;
John Reck8cc92352011-07-06 17:41:52 -070084import com.android.browser.provider.SnapshotProvider.Snapshots;
Michael Kolb4bd767d2011-05-27 11:33:55 -070085import com.android.browser.search.SearchEngine;
86import com.android.common.Search;
87
Michael Kolb8233fac2010-10-26 16:08:53 -070088import java.io.ByteArrayOutputStream;
89import java.io.File;
90import java.net.URLEncoder;
John Reck1cf4b792011-07-26 10:22:22 -070091import java.util.ArrayList;
Michael Kolb8233fac2010-10-26 16:08:53 -070092import java.util.Calendar;
93import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -080094import java.util.List;
John Reck26b18322011-06-21 13:08:58 -070095import java.util.Map;
Michael Kolb8233fac2010-10-26 16:08:53 -070096
97/**
98 * Controller for browser
99 */
100public class Controller
101 implements WebViewController, UiController {
102
103 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800104 private static final String SEND_APP_ID_EXTRA =
105 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
Michael Kolba4261fd2011-05-05 11:27:37 -0700106 private static final String INCOGNITO_URI = "browser:incognito";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800107
Michael Kolb8233fac2010-10-26 16:08:53 -0700108
109 // public message ids
110 public final static int LOAD_URL = 1001;
111 public final static int STOP_LOAD = 1002;
112
113 // Message Ids
114 private static final int FOCUS_NODE_HREF = 102;
115 private static final int RELEASE_WAKELOCK = 107;
116
117 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
118
119 private static final int OPEN_BOOKMARKS = 201;
120
121 private static final int EMPTY_MENU = -1;
122
Michael Kolb8233fac2010-10-26 16:08:53 -0700123 // activity requestCode
John Reckd3e4d5b2011-07-13 15:48:43 -0700124 final static int COMBO_VIEW = 1;
Michael Kolb8233fac2010-10-26 16:08:53 -0700125 final static int PREFERENCES_PAGE = 3;
126 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000127 final static int AUTOFILL_SETUP = 5;
128
Michael Kolb8233fac2010-10-26 16:08:53 -0700129 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
130
131 // As the ids are dynamically created, we can't guarantee that they will
132 // be in sequence, so this static array maps ids to a window number.
133 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
134 { R.id.window_one_menu_id, R.id.window_two_menu_id,
135 R.id.window_three_menu_id, R.id.window_four_menu_id,
136 R.id.window_five_menu_id, R.id.window_six_menu_id,
137 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
138
139 // "source" parameter for Google search through search key
140 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
141 // "source" parameter for Google search through simplily type
142 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
143
Guang Zhu9e78f512011-05-04 11:45:11 -0700144 // "no-crash-recovery" parameter in intetnt to suppress crash recovery
145 final static String NO_CRASH_RECOVERY = "no-crash-recovery";
146
Michael Kolb8233fac2010-10-26 16:08:53 -0700147 private Activity mActivity;
148 private UI mUi;
149 private TabControl mTabControl;
150 private BrowserSettings mSettings;
151 private WebViewFactory mFactory;
152
153 private WakeLock mWakeLock;
154
155 private UrlHandler mUrlHandler;
156 private UploadHandler mUploadHandler;
157 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700158 private PageDialogsHandler mPageDialogsHandler;
159 private NetworkStateHandler mNetworkHandler;
Martijn Coenenb2f93552011-06-14 10:48:35 +0200160 private NfcHandler mNfcHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700161
Ben Murdoch8029a772010-11-16 11:58:21 +0000162 private Message mAutoFillSetupMessage;
163
Michael Kolb8233fac2010-10-26 16:08:53 -0700164 private boolean mShouldShowErrorConsole;
165
166 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
167
168 // FIXME, temp address onPrepareMenu performance problem.
169 // When we move everything out of view, we should rewrite this.
170 private int mCurrentMenuState = 0;
171 private int mMenuState = R.id.MAIN_MENU;
172 private int mOldMenuState = EMPTY_MENU;
173 private Menu mCachedMenu;
174
Michael Kolb8233fac2010-10-26 16:08:53 -0700175 private boolean mMenuIsDown;
176
177 // For select and find, we keep track of the ActionMode so that
178 // finish() can be called as desired.
179 private ActionMode mActionMode;
180
181 /**
182 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
183 * of whether the configuration has changed. The first onMenuOpened call
184 * after a configuration change is simply a reopening of the same menu
185 * (i.e. mIconView did not change).
186 */
187 private boolean mConfigChanged;
188
189 /**
190 * Keeps track of whether the options menu is open. This is important in
191 * determining whether to show or hide the title bar overlay
192 */
193 private boolean mOptionsMenuOpen;
194
195 /**
196 * Whether or not the options menu is in its bigger, popup menu form. When
197 * true, we want the title bar overlay to be gone. When false, we do not.
198 * Only meaningful if mOptionsMenuOpen is true.
199 */
200 private boolean mExtendedMenuOpen;
201
202 private boolean mInLoad;
203
204 private boolean mActivityPaused = true;
205 private boolean mLoadStopped;
206
207 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500208 // Checks to see when the bookmarks database has changed, and updates the
209 // Tabs' notion of whether they represent bookmarked sites.
210 private ContentObserver mBookmarksObserver;
John Reck847b5322011-04-14 17:02:18 -0700211 private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700212
John Reck30b065e2011-07-19 10:58:05 -0700213 private boolean mSimulateActionBarOverlayMode;
214
Michael Kolb8233fac2010-10-26 16:08:53 -0700215 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
216 @Override
217 public Void doInBackground(File... files) {
218 if (files != null) {
219 for (File f : files) {
220 if (!f.delete()) {
221 Log.e(LOGTAG, f.getPath() + " was not deleted");
222 }
223 }
224 }
225 return null;
226 }
227 }
228
John Reckbc490d22011-07-22 15:04:59 -0700229 public Controller(Activity browser, boolean preloadCrashState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700230 mActivity = browser;
231 mSettings = BrowserSettings.getInstance();
232 mTabControl = new TabControl(this);
233 mSettings.setController(this);
John Reck378a4102011-06-09 16:23:01 -0700234 mCrashRecoveryHandler = CrashRecoveryHandler.initialize(this);
John Reckbc490d22011-07-22 15:04:59 -0700235 if (preloadCrashState) {
236 mCrashRecoveryHandler.preloadCrashState();
237 }
Michael Kolb14612442011-06-24 13:06:29 -0700238 mFactory = new BrowserWebViewFactory(browser);
Michael Kolb8233fac2010-10-26 16:08:53 -0700239
240 mUrlHandler = new UrlHandler(this);
241 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700242 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
Martijn Coenenb2f93552011-06-14 10:48:35 +0200243 mNfcHandler = new NfcHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700244
Michael Kolb8233fac2010-10-26 16:08:53 -0700245 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500246 mBookmarksObserver = new ContentObserver(mHandler) {
247 @Override
248 public void onChange(boolean selfChange) {
249 int size = mTabControl.getTabCount();
250 for (int i = 0; i < size; i++) {
251 mTabControl.getTab(i).updateBookmarkedStatus();
252 }
253 }
254
255 };
256 browser.getContentResolver().registerContentObserver(
257 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700258
259 mNetworkHandler = new NetworkStateHandler(mActivity, this);
260 // Start watching the default geolocation permissions
261 mSystemAllowGeolocationOrigins =
262 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
263 mSystemAllowGeolocationOrigins.start();
264
John Reckaf262e72011-07-25 13:55:44 -0700265 openIconDatabase();
John Reck30b065e2011-07-19 10:58:05 -0700266 mSimulateActionBarOverlayMode = !BrowserActivity.isTablet(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700267 }
268
Patrick Scott7d50a932011-02-04 09:27:26 -0500269 void start(final Bundle icicle, final Intent intent) {
Guang Zhu9e78f512011-05-04 11:45:11 -0700270 boolean noCrashRecovery = intent.getBooleanExtra(NO_CRASH_RECOVERY, false);
271 if (icicle != null || noCrashRecovery) {
John Reck847b5322011-04-14 17:02:18 -0700272 doStart(icicle, intent);
273 } else {
274 mCrashRecoveryHandler.startRecovery(intent);
275 }
276 }
277
278 void doStart(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700279 // Unless the last browser usage was within 24 hours, destroy any
280 // remaining incognito tabs.
281
282 Calendar lastActiveDate = icicle != null ?
283 (Calendar) icicle.getSerializable("lastActiveDate") : null;
284 Calendar today = Calendar.getInstance();
285 Calendar yesterday = Calendar.getInstance();
286 yesterday.add(Calendar.DATE, -1);
287
Patrick Scott7d50a932011-02-04 09:27:26 -0500288 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700289 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800290 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700291
Patrick Scott7d50a932011-02-04 09:27:26 -0500292 // Find out if we will restore any state and remember the tab.
Michael Kolbc831b632011-05-11 09:30:34 -0700293 final long currentTabId =
Patrick Scott7d50a932011-02-04 09:27:26 -0500294 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000295
Michael Kolbc831b632011-05-11 09:30:34 -0700296 if (currentTabId == -1) {
Patrick Scott7d50a932011-02-04 09:27:26 -0500297 // Not able to restore so we go ahead and clear session cookies. We
298 // must do this before trying to login the user as we don't want to
299 // clear any session cookies set during login.
300 CookieManager.getInstance().removeSessionCookie();
301 }
302
Patrick Scottd43e75a2011-03-14 14:47:23 -0400303 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500304 new Runnable() {
305 @Override public void run() {
Michael Kolbc831b632011-05-11 09:30:34 -0700306 onPreloginFinished(icicle, intent, currentTabId, restoreIncognitoTabs);
Patrick Scott7d50a932011-02-04 09:27:26 -0500307 }
308 });
309 }
310
Michael Kolbc831b632011-05-11 09:30:34 -0700311 private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId,
Patrick Scott7d50a932011-02-04 09:27:26 -0500312 boolean restoreIncognitoTabs) {
Michael Kolbc831b632011-05-11 09:30:34 -0700313 if (currentTabId == -1) {
John Reck1cf4b792011-07-26 10:22:22 -0700314 BackgroundHandler.execute(new PruneThumbnails(mActivity, null));
Michael Kolb8233fac2010-10-26 16:08:53 -0700315 final Bundle extra = intent.getExtras();
316 // Create an initial tab.
317 // If the intent is ACTION_VIEW and data is not null, the Browser is
318 // invoked to view the content by another application. In this case,
319 // the tab will be close when exit.
Michael Kolb14612442011-06-24 13:06:29 -0700320 UrlData urlData = IntentHandler.getUrlDataFromIntent(intent);
Michael Kolb7bcafde2011-05-09 13:55:59 -0700321 Tab t = null;
322 if (urlData.isEmpty()) {
323 t = openTabToHomePage();
324 } else {
325 t = openTab(urlData);
326 }
327 if (t != null) {
328 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
329 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700330 WebView webView = t.getWebView();
331 if (extra != null) {
332 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
333 if (scale > 0 && scale <= 1000) {
334 webView.setInitialScale(scale);
335 }
336 }
John Reckd8c74522011-06-14 08:45:00 -0700337 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700338 } else {
Michael Kolbc831b632011-05-11 09:30:34 -0700339 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
Patrick Scott7d50a932011-02-04 09:27:26 -0500340 mUi.needsRestoreAllTabs());
John Reck1cf4b792011-07-26 10:22:22 -0700341 List<Tab> tabs = mTabControl.getTabs();
342 ArrayList<Long> restoredTabs = new ArrayList<Long>(tabs.size());
343 for (Tab t : tabs) {
344 restoredTabs.add(t.getId());
345 }
346 BackgroundHandler.execute(new PruneThumbnails(mActivity, restoredTabs));
347 mUi.updateTabs(tabs);
Michael Kolb8233fac2010-10-26 16:08:53 -0700348 // TabControl.restoreState() will create a new tab even if
349 // restoring the state fails.
350 setActiveTab(mTabControl.getCurrentTab());
John Reckdb22ec42011-06-29 11:31:24 -0700351 // Handle the intent
352 mIntentHandler.onNewIntent(intent);
Michael Kolb8233fac2010-10-26 16:08:53 -0700353 }
354 // clear up the thumbnail directory, which is no longer used;
355 // ideally this should only be run once after an upgrade from
356 // a previous version of the browser
357 new ClearThumbnails().execute(mTabControl.getThumbnailDir()
358 .listFiles());
359 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700360 String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb8233fac2010-10-26 16:08:53 -0700361 if (jsFlags.trim().length() != 0) {
362 getCurrentWebView().setJsFlags(jsFlags);
363 }
John Reck439c9a52010-12-14 10:04:39 -0800364 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
365 bookmarksOrHistoryPicker(false);
366 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700367 }
368
John Reck1cf4b792011-07-26 10:22:22 -0700369 private static class PruneThumbnails implements Runnable {
370 private Context mContext;
371 private List<Long> mIds;
372
373 PruneThumbnails(Context context, List<Long> preserveIds) {
374 mContext = context.getApplicationContext();
375 mIds = preserveIds;
376 }
377
378 @Override
379 public void run() {
380 ContentResolver cr = mContext.getContentResolver();
381 if (mIds == null || mIds.size() == 0) {
382 cr.delete(Thumbnails.CONTENT_URI, null, null);
383 } else {
384 int length = mIds.size();
385 StringBuilder where = new StringBuilder();
386 where.append(Thumbnails._ID);
387 where.append(" not in (");
388 for (int i = 0; i < length; i++) {
389 where.append(mIds.get(i));
390 if (i < (length - 1)) {
391 where.append(",");
392 }
393 }
394 where.append(")");
395 cr.delete(Thumbnails.CONTENT_URI, where.toString(), null);
396 }
397 }
398
399 }
400
Michael Kolb1514bb72010-11-22 09:11:48 -0800401 @Override
402 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700403 return mFactory;
404 }
405
406 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800407 public void onSetWebView(Tab tab, WebView view) {
408 mUi.onSetWebView(tab, view);
409 }
410
411 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800412 public void createSubWindow(Tab tab) {
413 endActionMode();
414 WebView mainView = tab.getWebView();
415 WebView subView = mFactory.createWebView((mainView == null)
416 ? false
417 : mainView.isPrivateBrowsingEnabled());
418 mUi.createSubWindow(tab, subView);
419 }
420
421 @Override
Michael Kolb14612442011-06-24 13:06:29 -0700422 public Context getContext() {
423 return mActivity;
424 }
425
426 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700427 public Activity getActivity() {
428 return mActivity;
429 }
430
431 void setUi(UI ui) {
432 mUi = ui;
433 }
434
435 BrowserSettings getSettings() {
436 return mSettings;
437 }
438
439 IntentHandler getIntentHandler() {
440 return mIntentHandler;
441 }
442
443 @Override
444 public UI getUi() {
445 return mUi;
446 }
447
448 int getMaxTabs() {
449 return mActivity.getResources().getInteger(R.integer.max_tabs);
450 }
451
452 @Override
453 public TabControl getTabControl() {
454 return mTabControl;
455 }
456
Michael Kolb1bf23132010-11-19 12:55:12 -0800457 @Override
458 public List<Tab> getTabs() {
459 return mTabControl.getTabs();
460 }
461
John Reckaf262e72011-07-25 13:55:44 -0700462 // Open the icon database.
463 private void openIconDatabase() {
464 // We have to call getInstance on the UI thread
465 final WebIconDatabase instance = WebIconDatabase.getInstance();
466 BackgroundHandler.execute(new Runnable() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000467
John Reckaf262e72011-07-25 13:55:44 -0700468 @Override
469 public void run() {
470 instance.open(mActivity.getDir("icons", 0).getPath());
Michael Kolb8233fac2010-10-26 16:08:53 -0700471 }
John Reckaf262e72011-07-25 13:55:44 -0700472 });
Michael Kolb8233fac2010-10-26 16:08:53 -0700473 }
474
475 private void startHandler() {
476 mHandler = new Handler() {
477
478 @Override
479 public void handleMessage(Message msg) {
480 switch (msg.what) {
481 case OPEN_BOOKMARKS:
482 bookmarksOrHistoryPicker(false);
483 break;
484 case FOCUS_NODE_HREF:
485 {
486 String url = (String) msg.getData().get("url");
487 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500488 String src = (String) msg.getData().get("src");
489 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700490 if (TextUtils.isEmpty(url)) {
491 break;
492 }
493 HashMap focusNodeMap = (HashMap) msg.obj;
494 WebView view = (WebView) focusNodeMap.get("webview");
495 // Only apply the action if the top window did not change.
496 if (getCurrentTopWebView() != view) {
497 break;
498 }
499 switch (msg.arg1) {
500 case R.id.open_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700501 loadUrlFromContext(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700502 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500503 case R.id.view_image_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700504 loadUrlFromContext(src);
Cary Clark043c2d62010-12-15 11:19:39 -0500505 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500506 case R.id.open_newtab_context_menu_id:
507 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -0700508 openTab(url, parent,
509 !mSettings.openInBackground(), true);
Leon Scroggins026f2542010-11-22 13:26:12 -0500510 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700511 case R.id.copy_link_context_menu_id:
512 copy(url);
513 break;
514 case R.id.save_link_context_menu_id:
515 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500516 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000517 mActivity, url, null, null, null,
518 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700519 break;
520 }
521 break;
522 }
523
524 case LOAD_URL:
John Reck26b18322011-06-21 13:08:58 -0700525 loadUrlFromContext((String) msg.obj);
Michael Kolb8233fac2010-10-26 16:08:53 -0700526 break;
527
528 case STOP_LOAD:
529 stopLoading();
530 break;
531
532 case RELEASE_WAKELOCK:
John Reckf57c0292011-07-21 18:15:39 -0700533 if (mWakeLock != null && mWakeLock.isHeld()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700534 mWakeLock.release();
535 // if we reach here, Browser should be still in the
536 // background loading after WAKELOCK_TIMEOUT (5-min).
537 // To avoid burning the battery, stop loading.
538 mTabControl.stopAllLoading();
539 }
540 break;
541
542 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800543 Tab tab = (Tab) msg.obj;
544 if (tab != null) {
545 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700546 }
547 break;
548 }
549 }
550 };
551
552 }
553
John Reckef654f12011-07-12 16:42:08 -0700554 @Override
Martijn Coenenb2f93552011-06-14 10:48:35 +0200555 public Tab getCurrentTab() {
556 return mTabControl.getCurrentTab();
557 }
558
Michael Kolbba99c5d2010-11-29 14:57:41 -0800559 @Override
560 public void shareCurrentPage() {
561 shareCurrentPage(mTabControl.getCurrentTab());
562 }
563
564 private void shareCurrentPage(Tab tab) {
565 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800566 sharePage(mActivity, tab.getTitle(),
567 tab.getUrl(), tab.getFavicon(),
568 createScreenshot(tab.getWebView(),
569 getDesiredThumbnailWidth(mActivity),
570 getDesiredThumbnailHeight(mActivity)));
571 }
572 }
573
Michael Kolb8233fac2010-10-26 16:08:53 -0700574 /**
575 * Share a page, providing the title, url, favicon, and a screenshot. Uses
576 * an {@link Intent} to launch the Activity chooser.
577 * @param c Context used to launch a new Activity.
578 * @param title Title of the page. Stored in the Intent with
579 * {@link Intent#EXTRA_SUBJECT}
580 * @param url URL of the page. Stored in the Intent with
581 * {@link Intent#EXTRA_TEXT}
582 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
583 * with {@link Browser#EXTRA_SHARE_FAVICON}
584 * @param screenshot Bitmap of a screenshot of the page. Stored in the
585 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
586 */
587 static final void sharePage(Context c, String title, String url,
588 Bitmap favicon, Bitmap screenshot) {
589 Intent send = new Intent(Intent.ACTION_SEND);
590 send.setType("text/plain");
591 send.putExtra(Intent.EXTRA_TEXT, url);
592 send.putExtra(Intent.EXTRA_SUBJECT, title);
593 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
594 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
595 try {
596 c.startActivity(Intent.createChooser(send, c.getString(
597 R.string.choosertitle_sharevia)));
598 } catch(android.content.ActivityNotFoundException ex) {
599 // if no app handles it, do nothing
600 }
601 }
602
603 private void copy(CharSequence text) {
604 ClipboardManager cm = (ClipboardManager) mActivity
605 .getSystemService(Context.CLIPBOARD_SERVICE);
606 cm.setText(text);
607 }
608
609 // lifecycle
610
611 protected void onConfgurationChanged(Configuration config) {
612 mConfigChanged = true;
613 if (mPageDialogsHandler != null) {
614 mPageDialogsHandler.onConfigurationChanged(config);
615 }
616 mUi.onConfigurationChanged(config);
617 }
618
619 @Override
620 public void handleNewIntent(Intent intent) {
621 mIntentHandler.onNewIntent(intent);
622 }
623
624 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800625 if (mUi.isCustomViewShowing()) {
626 hideCustomView();
627 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700628 if (mActivityPaused) {
629 Log.e(LOGTAG, "BrowserActivity is already paused.");
630 return;
631 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700632 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800633 Tab tab = mTabControl.getCurrentTab();
634 if (tab != null) {
635 tab.pause();
636 if (!pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700637 if (mWakeLock == null) {
638 PowerManager pm = (PowerManager) mActivity
639 .getSystemService(Context.POWER_SERVICE);
640 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
641 }
Michael Kolb70976932010-11-30 11:34:01 -0800642 mWakeLock.acquire();
643 mHandler.sendMessageDelayed(mHandler
644 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
645 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700646 }
647 mUi.onPause();
648 mNetworkHandler.onPause();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200649 mNfcHandler.onPause();
Michael Kolb8233fac2010-10-26 16:08:53 -0700650
651 WebView.disablePlatformNotifications();
John Reck378a4102011-06-09 16:23:01 -0700652 mCrashRecoveryHandler.backupState();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200653
Michael Kolb8233fac2010-10-26 16:08:53 -0700654 }
655
John Reck1cf4b792011-07-26 10:22:22 -0700656 void onSaveInstanceState(Bundle outState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700657 // the default implementation requires each view to have an id. As the
658 // browser handles the state itself and it doesn't use id for the views,
659 // don't call the default implementation. Otherwise it will trigger the
660 // warning like this, "couldn't save which view has focus because the
661 // focused view XXX has no id".
662
663 // Save all the tabs
John Reck1cf4b792011-07-26 10:22:22 -0700664 mTabControl.saveState(outState);
John Reck24f18262011-06-17 14:47:20 -0700665 if (!outState.isEmpty()) {
666 // Save time so that we know how old incognito tabs (if any) are.
667 outState.putSerializable("lastActiveDate", Calendar.getInstance());
668 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700669 }
670
671 void onResume() {
672 if (!mActivityPaused) {
673 Log.e(LOGTAG, "BrowserActivity is already resumed.");
674 return;
675 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700676 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800677 Tab current = mTabControl.getCurrentTab();
678 if (current != null) {
679 current.resume();
680 resumeWebViewTimers(current);
681 }
John Reckf57c0292011-07-21 18:15:39 -0700682 releaseWakeLock();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200683
Michael Kolb8233fac2010-10-26 16:08:53 -0700684 mUi.onResume();
685 mNetworkHandler.onResume();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200686 mNfcHandler.onResume();
Michael Kolb8233fac2010-10-26 16:08:53 -0700687 WebView.enablePlatformNotifications();
688 }
689
John Reckf57c0292011-07-21 18:15:39 -0700690 private void releaseWakeLock() {
691 if (mWakeLock != null && mWakeLock.isHeld()) {
692 mHandler.removeMessages(RELEASE_WAKELOCK);
693 mWakeLock.release();
694 }
695 }
696
Michael Kolb70976932010-11-30 11:34:01 -0800697 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800698 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800699 * @param tab guaranteed non-null
700 */
701 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700702 boolean inLoad = tab.inPageLoad();
703 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
704 CookieSyncManager.getInstance().startSync();
705 WebView w = tab.getWebView();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100706 WebViewTimersControl.getInstance().onBrowserActivityResume(w);
Michael Kolb8233fac2010-10-26 16:08:53 -0700707 }
708 }
709
Michael Kolb70976932010-11-30 11:34:01 -0800710 /**
711 * Pause all WebView timers using the WebView of the given tab
712 * @param tab
713 * @return true if the timers are paused or tab is null
714 */
715 private boolean pauseWebViewTimers(Tab tab) {
716 if (tab == null) {
717 return true;
718 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700719 CookieSyncManager.getInstance().stopSync();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100720 WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView());
Michael Kolb8233fac2010-10-26 16:08:53 -0700721 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700722 }
Michael Kolb70976932010-11-30 11:34:01 -0800723 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700724 }
725
726 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800727 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700728 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
729 mUploadHandler = null;
730 }
731 if (mTabControl == null) return;
732 mUi.onDestroy();
733 // Remove the current tab and sub window
734 Tab t = mTabControl.getCurrentTab();
735 if (t != null) {
736 dismissSubWindow(t);
737 removeTab(t);
738 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500739 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700740 // Destroy all the tabs
741 mTabControl.destroy();
742 WebIconDatabase.getInstance().close();
743 // Stop watching the default geolocation permissions
744 mSystemAllowGeolocationOrigins.stop();
745 mSystemAllowGeolocationOrigins = null;
746 }
747
748 protected boolean isActivityPaused() {
749 return mActivityPaused;
750 }
751
752 protected void onLowMemory() {
753 mTabControl.freeMemory();
754 }
755
756 @Override
757 public boolean shouldShowErrorConsole() {
758 return mShouldShowErrorConsole;
759 }
760
761 protected void setShouldShowErrorConsole(boolean show) {
762 if (show == mShouldShowErrorConsole) {
763 // Nothing to do.
764 return;
765 }
766 mShouldShowErrorConsole = show;
767 Tab t = mTabControl.getCurrentTab();
768 if (t == null) {
769 // There is no current tab so we cannot toggle the error console
770 return;
771 }
772 mUi.setShouldShowErrorConsole(t, show);
773 }
774
775 @Override
776 public void stopLoading() {
777 mLoadStopped = true;
778 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700779 WebView w = getCurrentTopWebView();
780 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700781 mUi.onPageStopped(tab);
782 }
783
784 boolean didUserStopLoading() {
785 return mLoadStopped;
786 }
787
788 // WebViewController
789
790 @Override
John Reck324d4402011-01-11 16:56:42 -0800791 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700792
793 // We've started to load a new page. If there was a pending message
794 // to save a screenshot then we will now take the new page and save
795 // an incorrect screenshot. Therefore, remove any pending thumbnail
796 // messages from the queue.
797 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800798 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700799
800 // reset sync timer to avoid sync starts during loading a page
801 CookieSyncManager.getInstance().resetSync();
802
803 if (!mNetworkHandler.isNetworkUp()) {
804 view.setNetworkAvailable(false);
805 }
806
807 // when BrowserActivity just starts, onPageStarted may be called before
808 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
809 // to start the timer. As we won't switch tabs while an activity is in
810 // pause state, we can ensure calling resume and pause in pair.
811 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800812 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700813 }
814 mLoadStopped = false;
815 if (!mNetworkHandler.isNetworkUp()) {
816 mNetworkHandler.createAndShowNetworkDialog();
817 }
818 endActionMode();
819
John Reck30c714c2010-12-16 17:30:34 -0800820 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700821
John Reck324d4402011-01-11 16:56:42 -0800822 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700823 // update the bookmark database for favicon
824 maybeUpdateFavicon(tab, null, url, favicon);
825
826 Performance.tracePageStart(url);
827
828 // Performance probe
829 if (false) {
830 Performance.onPageStarted();
831 }
832
833 }
834
835 @Override
John Reck324d4402011-01-11 16:56:42 -0800836 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800837 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800838 if (!tab.isPrivateBrowsingEnabled()
John Reckd8c74522011-06-14 08:45:00 -0700839 && !TextUtils.isEmpty(tab.getUrl())
840 && !tab.isSnapshot()) {
John Recka1696282011-07-08 14:10:37 -0700841 // Only update the bookmark screenshot if the user did not
842 // cancel the load early and there is not already
843 // a pending update for the tab.
Michael Kolb8233fac2010-10-26 16:08:53 -0700844 if (tab.inForeground() && !didUserStopLoading()
845 || !tab.inForeground()) {
John Recka1696282011-07-08 14:10:37 -0700846 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
847 mHandler.sendMessageDelayed(mHandler.obtainMessage(
848 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
849 500);
850 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700851 }
852 }
853 // pause the WebView timer and release the wake lock if it is finished
854 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800855 if (mActivityPaused && pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700856 releaseWakeLock();
Michael Kolb8233fac2010-10-26 16:08:53 -0700857 }
Martijn Coenenb2f93552011-06-14 10:48:35 +0200858
Michael Kolb8233fac2010-10-26 16:08:53 -0700859 // Performance probe
860 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800861 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700862 }
863
864 Performance.tracePageFinished();
865 }
866
867 @Override
John Reck30c714c2010-12-16 17:30:34 -0800868 public void onProgressChanged(Tab tab) {
869 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700870
871 if (newProgress == 100) {
872 CookieSyncManager.getInstance().sync();
873 // onProgressChanged() may continue to be called after the main
874 // frame has finished loading, as any remaining sub frames continue
875 // to load. We'll only get called once though with newProgress as
876 // 100 when everything is loaded. (onPageFinished is called once
877 // when the main frame completes loading regardless of the state of
878 // any sub frames so calls to onProgressChanges may continue after
879 // onPageFinished has executed)
880 if (mInLoad) {
881 mInLoad = false;
882 updateInLoadMenuItems(mCachedMenu);
883 }
884 } else {
885 if (!mInLoad) {
886 // onPageFinished may have already been called but a subframe is
887 // still loading and updating the progress. Reset mInLoad and
888 // update the menu items.
889 mInLoad = true;
890 updateInLoadMenuItems(mCachedMenu);
891 }
892 }
John Reck30c714c2010-12-16 17:30:34 -0800893 mUi.onProgressChanged(tab);
894 }
895
896 @Override
897 public void onUpdatedLockIcon(Tab tab) {
898 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700899 }
900
901 @Override
902 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800903 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800904 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800905 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700906 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
907 return;
908 }
909 // Update the title in the history database if not in private browsing mode
910 if (!tab.isPrivateBrowsingEnabled()) {
John Reckf57c0292011-07-21 18:15:39 -0700911 DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700912 }
913 }
914
915 @Override
916 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800917 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700918 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
919 }
920
921 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800922 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
923 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700924 }
925
926 @Override
927 public boolean shouldOverrideKeyEvent(KeyEvent event) {
928 if (mMenuIsDown) {
929 // only check shortcut key when MENU is held
930 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
931 event);
932 } else {
933 return false;
934 }
935 }
936
937 @Override
938 public void onUnhandledKeyEvent(KeyEvent event) {
939 if (!isActivityPaused()) {
940 if (event.getAction() == KeyEvent.ACTION_DOWN) {
941 mActivity.onKeyDown(event.getKeyCode(), event);
942 } else {
943 mActivity.onKeyUp(event.getKeyCode(), event);
944 }
945 }
946 }
947
948 @Override
John Reck324d4402011-01-11 16:56:42 -0800949 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700950 // Don't save anything in private browsing mode
951 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800952 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700953
John Reck324d4402011-01-11 16:56:42 -0800954 if (TextUtils.isEmpty(url)
955 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700956 return;
957 }
John Reckf57c0292011-07-21 18:15:39 -0700958 DataController.getInstance(mActivity).updateVisitedHistory(url);
John Reck847b5322011-04-14 17:02:18 -0700959 if (!mActivityPaused) {
960 // Since we clear the state in onPause, don't backup the current
961 // state if we are already paused
962 mCrashRecoveryHandler.backupState();
963 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700964 }
965
966 @Override
967 public void getVisitedHistory(final ValueCallback<String[]> callback) {
968 AsyncTask<Void, Void, String[]> task =
969 new AsyncTask<Void, Void, String[]>() {
970 @Override
971 public String[] doInBackground(Void... unused) {
972 return Browser.getVisitedHistory(mActivity.getContentResolver());
973 }
974 @Override
975 public void onPostExecute(String[] result) {
976 callback.onReceiveValue(result);
977 }
978 };
979 task.execute();
980 }
981
982 @Override
983 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
984 final HttpAuthHandler handler, final String host,
985 final String realm) {
986 String username = null;
987 String password = null;
988
989 boolean reuseHttpAuthUsernamePassword
990 = handler.useHttpAuthUsernamePassword();
991
992 if (reuseHttpAuthUsernamePassword && view != null) {
993 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
994 if (credentials != null && credentials.length == 2) {
995 username = credentials[0];
996 password = credentials[1];
997 }
998 }
999
1000 if (username != null && password != null) {
1001 handler.proceed(username, password);
1002 } else {
Ben Murdochfdd37112011-08-05 15:48:14 +01001003 if (tab.inForeground() && !handler.suppressDialog()) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001004 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
1005 } else {
1006 handler.cancel();
1007 }
1008 }
1009 }
1010
1011 @Override
1012 public void onDownloadStart(Tab tab, String url, String userAgent,
1013 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001014 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -05001015 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001016 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
1017 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001018 // This Tab was opened for the sole purpose of downloading a
1019 // file. Remove it.
1020 if (tab == mTabControl.getCurrentTab()) {
1021 // In this case, the Tab is still on top.
1022 goBackOnePageOrQuit();
1023 } else {
1024 // In this case, it is not.
1025 closeTab(tab);
1026 }
1027 }
1028 }
1029
1030 @Override
1031 public Bitmap getDefaultVideoPoster() {
1032 return mUi.getDefaultVideoPoster();
1033 }
1034
1035 @Override
1036 public View getVideoLoadingProgressView() {
1037 return mUi.getVideoLoadingProgressView();
1038 }
1039
1040 @Override
1041 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1042 SslError error) {
1043 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1044 }
1045
Patrick Scott92066772011-03-10 08:46:27 -05001046 @Override
1047 public void showAutoLogin(Tab tab) {
1048 assert tab.inForeground();
1049 // Update the title bar to show the auto-login request.
1050 mUi.showAutoLogin(tab);
1051 }
1052
1053 @Override
1054 public void hideAutoLogin(Tab tab) {
1055 assert tab.inForeground();
1056 mUi.hideAutoLogin(tab);
1057 }
1058
Michael Kolb8233fac2010-10-26 16:08:53 -07001059 // helper method
1060
1061 /*
1062 * Update the favorites icon if the private browsing isn't enabled and the
1063 * icon is valid.
1064 */
1065 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1066 final String url, Bitmap favicon) {
1067 if (favicon == null) {
1068 return;
1069 }
1070 if (!tab.isPrivateBrowsingEnabled()) {
1071 Bookmarks.updateFavicon(mActivity
1072 .getContentResolver(), originalUrl, url, favicon);
1073 }
1074 }
1075
Leon Scroggins4cd97792010-12-03 15:31:56 -05001076 @Override
1077 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001078 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001079 mUi.bookmarkedStatusHasChanged(tab);
1080 }
1081
Michael Kolb8233fac2010-10-26 16:08:53 -07001082 // end WebViewController
1083
1084 protected void pageUp() {
1085 getCurrentTopWebView().pageUp(false);
1086 }
1087
1088 protected void pageDown() {
1089 getCurrentTopWebView().pageDown(false);
1090 }
1091
1092 // callback from phone title bar
1093 public void editUrl() {
1094 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001095 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001096 }
1097
Michael Kolbcfa3af52010-12-14 10:36:11 -08001098 public void startVoiceSearch() {
1099 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1100 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1101 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1102 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1103 mActivity.getComponentName().flattenToString());
1104 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001105 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001106 mActivity.startActivity(intent);
1107 }
1108
Michael Kolb11d19782011-03-20 10:17:40 -07001109 @Override
1110 public void activateVoiceSearchMode(String title, List<String> results) {
1111 mUi.showVoiceTitleBar(title, results);
Michael Kolb8233fac2010-10-26 16:08:53 -07001112 }
1113
1114 public void revertVoiceSearchMode(Tab tab) {
1115 mUi.revertVoiceTitleBar(tab);
1116 }
1117
Michael Kolb736990c2011-03-20 10:01:20 -07001118 public boolean supportsVoiceSearch() {
John Reck35e9dd62011-04-25 09:01:54 -07001119 SearchEngine searchEngine = getSettings().getSearchEngine();
Michael Kolb736990c2011-03-20 10:01:20 -07001120 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1121 }
1122
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001123 public void showCustomView(Tab tab, View view, int requestedOrientation,
Michael Kolb8233fac2010-10-26 16:08:53 -07001124 WebChromeClient.CustomViewCallback callback) {
1125 if (tab.inForeground()) {
1126 if (mUi.isCustomViewShowing()) {
1127 callback.onCustomViewHidden();
1128 return;
1129 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001130 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001131 // Save the menu state and set it to empty while the custom
1132 // view is showing.
1133 mOldMenuState = mMenuState;
1134 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001135 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001136 }
1137 }
1138
1139 @Override
1140 public void hideCustomView() {
1141 if (mUi.isCustomViewShowing()) {
1142 mUi.onHideCustomView();
1143 // Reset the old menu state.
1144 mMenuState = mOldMenuState;
1145 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001146 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001147 }
1148 }
1149
1150 protected void onActivityResult(int requestCode, int resultCode,
1151 Intent intent) {
1152 if (getCurrentTopWebView() == null) return;
1153 switch (requestCode) {
1154 case PREFERENCES_PAGE:
1155 if (resultCode == Activity.RESULT_OK && intent != null) {
1156 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001157 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001158 mTabControl.removeParentChildRelationShips();
1159 }
1160 }
1161 break;
1162 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001163 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001164 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001165 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001166 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001167 case AUTOFILL_SETUP:
1168 // Determine whether a profile was actually set up or not
1169 // and if so, send the message back to the WebTextView to
1170 // fill the form with the new profile.
1171 if (getSettings().getAutoFillProfile() != null) {
1172 mAutoFillSetupMessage.sendToTarget();
1173 mAutoFillSetupMessage = null;
1174 }
1175 break;
John Reckd3e4d5b2011-07-13 15:48:43 -07001176 case COMBO_VIEW:
1177 if (intent == null || resultCode != Activity.RESULT_OK) {
1178 break;
1179 }
John Reck3ba45532011-08-11 16:26:53 -07001180 mUi.showWeb(false);
John Reckd3e4d5b2011-07-13 15:48:43 -07001181 if (Intent.ACTION_VIEW.equals(intent.getAction())) {
1182 Tab t = getCurrentTab();
1183 Uri uri = intent.getData();
1184 loadUrl(t, uri.toString());
1185 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
1186 String[] urls = intent.getStringArrayExtra(
1187 ComboViewActivity.EXTRA_OPEN_ALL);
1188 Tab parent = getCurrentTab();
1189 for (String url : urls) {
1190 parent = openTab(url, parent,
1191 !mSettings.openInBackground(), true);
1192 }
1193 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
1194 long id = intent.getLongExtra(
1195 ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
1196 if (id >= 0) {
1197 createNewSnapshotTab(id, true);
1198 }
1199 }
1200 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001201 default:
1202 break;
1203 }
1204 getCurrentTopWebView().requestFocus();
1205 }
1206
1207 /**
1208 * Open the Go page.
1209 * @param startWithHistory If true, open starting on the history tab.
1210 * Otherwise, start with the bookmarks tab.
1211 */
1212 @Override
1213 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1214 if (mTabControl.getCurrentWebView() == null) {
1215 return;
1216 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001217 // clear action mode
1218 if (isInCustomActionMode()) {
1219 endActionMode();
1220 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001221 Bundle extras = new Bundle();
1222 // Disable opening in a new window if we have maxed out the windows
1223 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1224 !mTabControl.canCreateNewTab());
John Reck2bc80422011-06-30 15:11:49 -07001225 mUi.showComboView(startWithHistory
1226 ? ComboViews.History : ComboViews.Bookmarks, extras);
Michael Kolb8233fac2010-10-26 16:08:53 -07001227 }
1228
1229 // combo view callbacks
1230
1231 /**
1232 * callback from ComboPage when clear history is requested
1233 */
1234 public void onRemoveParentChildRelationships() {
1235 mTabControl.removeParentChildRelationShips();
1236 }
1237
Michael Kolb8233fac2010-10-26 16:08:53 -07001238 // key handling
1239 protected void onBackKey() {
1240 if (!mUi.onBackKey()) {
1241 WebView subwindow = mTabControl.getCurrentSubWindow();
1242 if (subwindow != null) {
1243 if (subwindow.canGoBack()) {
1244 subwindow.goBack();
1245 } else {
1246 dismissSubWindow(mTabControl.getCurrentTab());
1247 }
1248 } else {
1249 goBackOnePageOrQuit();
1250 }
1251 }
1252 }
1253
Michael Kolb4bd767d2011-05-27 11:33:55 -07001254 protected boolean onMenuKey() {
1255 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001256 }
1257
Michael Kolb8233fac2010-10-26 16:08:53 -07001258 // menu handling and state
1259 // TODO: maybe put into separate handler
1260
1261 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckd73c5a22010-12-22 10:22:50 -08001262 if (mMenuState == EMPTY_MENU) {
1263 return false;
1264 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001265 MenuInflater inflater = mActivity.getMenuInflater();
1266 inflater.inflate(R.menu.browser, menu);
1267 updateInLoadMenuItems(menu);
1268 // hold on to the menu reference here; it is used by the page callbacks
1269 // to update the menu based on loading state
1270 mCachedMenu = menu;
1271 return true;
1272 }
1273
1274 protected void onCreateContextMenu(ContextMenu menu, View v,
1275 ContextMenuInfo menuInfo) {
John Reck0f602f32011-07-07 15:38:43 -07001276 if (v instanceof TitleBar) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001277 return;
1278 }
1279 if (!(v instanceof WebView)) {
1280 return;
1281 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001282 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001283 WebView.HitTestResult result = webview.getHitTestResult();
1284 if (result == null) {
1285 return;
1286 }
1287
1288 int type = result.getType();
1289 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1290 Log.w(LOGTAG,
1291 "We should not show context menu when nothing is touched");
1292 return;
1293 }
1294 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1295 // let TextView handles context menu
1296 return;
1297 }
1298
1299 // Note, http://b/issue?id=1106666 is requesting that
1300 // an inflated menu can be used again. This is not available
1301 // yet, so inflate each time (yuk!)
1302 MenuInflater inflater = mActivity.getMenuInflater();
1303 inflater.inflate(R.menu.browsercontext, menu);
1304
1305 // Show the correct menu group
1306 final String extra = result.getExtra();
1307 menu.setGroupVisible(R.id.PHONE_MENU,
1308 type == WebView.HitTestResult.PHONE_TYPE);
1309 menu.setGroupVisible(R.id.EMAIL_MENU,
1310 type == WebView.HitTestResult.EMAIL_TYPE);
1311 menu.setGroupVisible(R.id.GEO_MENU,
1312 type == WebView.HitTestResult.GEO_TYPE);
1313 menu.setGroupVisible(R.id.IMAGE_MENU,
1314 type == WebView.HitTestResult.IMAGE_TYPE
1315 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1316 menu.setGroupVisible(R.id.ANCHOR_MENU,
1317 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1318 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001319 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1320 || type == WebView.HitTestResult.PHONE_TYPE
1321 || type == WebView.HitTestResult.EMAIL_TYPE
1322 || type == WebView.HitTestResult.GEO_TYPE;
1323 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1324 if (hitText) {
1325 menu.findItem(R.id.select_text_menu_id)
1326 .setOnMenuItemClickListener(new SelectText(webview));
1327 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001328 // Setup custom handling depending on the type
1329 switch (type) {
1330 case WebView.HitTestResult.PHONE_TYPE:
1331 menu.setHeaderTitle(Uri.decode(extra));
1332 menu.findItem(R.id.dial_context_menu_id).setIntent(
1333 new Intent(Intent.ACTION_VIEW, Uri
1334 .parse(WebView.SCHEME_TEL + extra)));
1335 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1336 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1337 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1338 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1339 addIntent);
1340 menu.findItem(R.id.copy_phone_context_menu_id)
1341 .setOnMenuItemClickListener(
1342 new Copy(extra));
1343 break;
1344
1345 case WebView.HitTestResult.EMAIL_TYPE:
1346 menu.setHeaderTitle(extra);
1347 menu.findItem(R.id.email_context_menu_id).setIntent(
1348 new Intent(Intent.ACTION_VIEW, Uri
1349 .parse(WebView.SCHEME_MAILTO + extra)));
1350 menu.findItem(R.id.copy_mail_context_menu_id)
1351 .setOnMenuItemClickListener(
1352 new Copy(extra));
1353 break;
1354
1355 case WebView.HitTestResult.GEO_TYPE:
1356 menu.setHeaderTitle(extra);
1357 menu.findItem(R.id.map_context_menu_id).setIntent(
1358 new Intent(Intent.ACTION_VIEW, Uri
1359 .parse(WebView.SCHEME_GEO
1360 + URLEncoder.encode(extra))));
1361 menu.findItem(R.id.copy_geo_context_menu_id)
1362 .setOnMenuItemClickListener(
1363 new Copy(extra));
1364 break;
1365
1366 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1367 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001368 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001369 // decide whether to show the open link in new tab option
1370 boolean showNewTab = mTabControl.canCreateNewTab();
1371 MenuItem newTabItem
1372 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001373 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001374 ? R.string.contextmenu_openlink_newwindow_background
1375 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001376 newTabItem.setVisible(showNewTab);
1377 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001378 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1379 newTabItem.setOnMenuItemClickListener(
1380 new MenuItem.OnMenuItemClickListener() {
1381 @Override
1382 public boolean onMenuItemClick(MenuItem item) {
1383 final HashMap<String, WebView> hrefMap =
1384 new HashMap<String, WebView>();
1385 hrefMap.put("webview", webview);
1386 final Message msg = mHandler.obtainMessage(
1387 FOCUS_NODE_HREF,
1388 R.id.open_newtab_context_menu_id,
1389 0, hrefMap);
1390 webview.requestFocusNodeHref(msg);
1391 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001392 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001393 });
1394 } else {
1395 newTabItem.setOnMenuItemClickListener(
1396 new MenuItem.OnMenuItemClickListener() {
1397 @Override
1398 public boolean onMenuItemClick(MenuItem item) {
1399 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001400 openTab(extra, parent,
1401 !mSettings.openInBackground(),
1402 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001403 return true;
1404 }
1405 });
1406 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001407 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001408 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1409 break;
1410 }
1411 // otherwise fall through to handle image part
1412 case WebView.HitTestResult.IMAGE_TYPE:
1413 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1414 menu.setHeaderTitle(extra);
1415 }
1416 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1417 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1418 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001419 setOnMenuItemClickListener(
1420 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001421 menu.findItem(R.id.set_wallpaper_context_menu_id).
1422 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1423 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001424 break;
1425
1426 default:
1427 Log.w(LOGTAG, "We should not get here.");
1428 break;
1429 }
1430 //update the ui
1431 mUi.onContextMenuCreated(menu);
1432 }
1433
1434 /**
1435 * As the menu can be open when loading state changes
1436 * we must manually update the state of the stop/reload menu
1437 * item
1438 */
1439 private void updateInLoadMenuItems(Menu menu) {
1440 if (menu == null) {
1441 return;
1442 }
1443 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1444 MenuItem src = mInLoad ?
1445 menu.findItem(R.id.stop_menu_id):
1446 menu.findItem(R.id.reload_menu_id);
1447 if (src != null) {
1448 dest.setIcon(src.getIcon());
1449 dest.setTitle(src.getTitle());
1450 }
1451 }
1452
John Reckb3417f02011-01-14 11:01:05 -08001453 boolean onPrepareOptionsMenu(Menu menu) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001454 // Note: setVisible will decide whether an item is visible; while
1455 // setEnabled() will decide whether an item is enabled, which also means
1456 // whether the matching shortcut key will function.
1457 switch (mMenuState) {
1458 case EMPTY_MENU:
1459 if (mCurrentMenuState != mMenuState) {
1460 menu.setGroupVisible(R.id.MAIN_MENU, false);
1461 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1462 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1463 }
1464 break;
1465 default:
1466 if (mCurrentMenuState != mMenuState) {
1467 menu.setGroupVisible(R.id.MAIN_MENU, true);
1468 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1469 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1470 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001471 updateMenuState(getCurrentTab(), menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001472 break;
1473 }
1474 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001475 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001476 }
1477
Michael Kolb4bf79712011-07-14 14:18:12 -07001478 @Override
1479 public void updateMenuState(Tab tab, Menu menu) {
1480 boolean canGoBack = false;
1481 boolean canGoForward = false;
1482 boolean isHome = false;
1483 if (tab != null) {
1484 canGoBack = tab.canGoBack();
1485 canGoForward = tab.canGoForward();
1486 isHome = mSettings.getHomePage().equals(tab.getUrl());
1487 }
1488 final MenuItem back = menu.findItem(R.id.back_menu_id);
1489 back.setEnabled(canGoBack);
1490
1491 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1492 home.setEnabled(!isHome);
1493
1494 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1495 forward.setEnabled(canGoForward);
1496
1497 final MenuItem source = menu.findItem(mInLoad ? R.id.stop_menu_id : R.id.reload_menu_id);
1498 final MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolb7ab75ee2011-07-14 16:36:38 -07001499 if (source != null && dest != null) {
1500 dest.setTitle(source.getTitle());
1501 dest.setIcon(source.getIcon());
1502 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001503
1504 // decide whether to show the share link option
1505 PackageManager pm = mActivity.getPackageManager();
1506 Intent send = new Intent(Intent.ACTION_SEND);
1507 send.setType("text/plain");
1508 ResolveInfo ri = pm.resolveActivity(send,
1509 PackageManager.MATCH_DEFAULT_ONLY);
1510 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1511
1512 boolean isNavDump = mSettings.enableNavDump();
1513 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1514 nav.setVisible(isNavDump);
1515 nav.setEnabled(isNavDump);
1516
1517 boolean showDebugSettings = mSettings.isDebugEnabled();
1518 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1519 counter.setVisible(showDebugSettings);
1520 counter.setEnabled(showDebugSettings);
1521
1522 MenuItem saveSnapshot = menu.findItem(R.id.save_snapshot_menu_id);
1523 saveSnapshot.setVisible(tab != null && !tab.isSnapshot());
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001524 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001525 }
1526
Michael Kolb8233fac2010-10-26 16:08:53 -07001527 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001528 if (null == getCurrentTopWebView()) {
1529 return false;
1530 }
1531 if (mMenuIsDown) {
1532 // The shortcut action consumes the MENU. Even if it is still down,
1533 // it won't trigger the next shortcut action. In the case of the
1534 // shortcut action triggering a new activity, like Bookmarks, we
1535 // won't get onKeyUp for MENU. So it is important to reset it here.
1536 mMenuIsDown = false;
1537 }
Michael Kolb3ca12752011-07-20 13:52:25 -07001538 if (mUi.onOptionsItemSelected(item)) {
1539 // ui callback handled it
1540 return true;
1541 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001542 switch (item.getItemId()) {
1543 // -- Main menu
1544 case R.id.new_tab_menu_id:
1545 openTabToHomePage();
1546 break;
1547
1548 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001549 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001550 break;
1551
1552 case R.id.goto_menu_id:
1553 editUrl();
1554 break;
1555
1556 case R.id.bookmarks_menu_id:
1557 bookmarksOrHistoryPicker(false);
1558 break;
1559
Michael Kolb8233fac2010-10-26 16:08:53 -07001560 case R.id.add_bookmark_menu_id:
John Reckd3e4d5b2011-07-13 15:48:43 -07001561 mActivity.startActivity(createBookmarkCurrentPageIntent(false));
Michael Kolb8233fac2010-10-26 16:08:53 -07001562 break;
1563
1564 case R.id.stop_reload_menu_id:
1565 if (mInLoad) {
1566 stopLoading();
1567 } else {
1568 getCurrentTopWebView().reload();
1569 }
1570 break;
1571
1572 case R.id.back_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001573 getCurrentTab().goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07001574 break;
1575
1576 case R.id.forward_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001577 getCurrentTab().goForward();
Michael Kolb8233fac2010-10-26 16:08:53 -07001578 break;
1579
1580 case R.id.close_menu_id:
1581 // Close the subwindow if it exists.
1582 if (mTabControl.getCurrentSubWindow() != null) {
1583 dismissSubWindow(mTabControl.getCurrentTab());
1584 break;
1585 }
1586 closeCurrentTab();
1587 break;
1588
1589 case R.id.homepage_menu_id:
1590 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07001591 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07001592 break;
1593
1594 case R.id.preferences_menu_id:
1595 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1596 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1597 getCurrentTopWebView().getUrl());
1598 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1599 break;
1600
1601 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001602 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001603 break;
1604
John Reck2bc80422011-06-30 15:11:49 -07001605 case R.id.save_snapshot_menu_id:
1606 final Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07001607 if (source == null) break;
John Reckd8c74522011-06-14 08:45:00 -07001608 final ContentResolver cr = mActivity.getContentResolver();
1609 final ContentValues values = source.createSnapshotValues();
John Reck2bc80422011-06-30 15:11:49 -07001610 if (values != null) {
1611 new AsyncTask<Tab, Void, Long>() {
John Reckd8c74522011-06-14 08:45:00 -07001612
John Reck2bc80422011-06-30 15:11:49 -07001613 @Override
1614 protected Long doInBackground(Tab... params) {
1615 Uri result = cr.insert(Snapshots.CONTENT_URI, values);
1616 long id = ContentUris.parseId(result);
1617 return id;
John Reckd8c74522011-06-14 08:45:00 -07001618 }
John Reckf33b1632011-06-04 20:00:23 -07001619
John Reck2bc80422011-06-30 15:11:49 -07001620 @Override
1621 protected void onPostExecute(Long id) {
1622 Bundle b = new Bundle();
1623 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
1624 mUi.showComboView(ComboViews.Snapshots, b);
1625 };
1626 }.execute(source);
1627 } else {
1628 Toast.makeText(mActivity, R.string.snapshot_failed,
Leon Scrogginsac993842011-02-02 12:54:07 -05001629 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001630 }
Leon Scrogginsac993842011-02-02 12:54:07 -05001631 break;
1632
Michael Kolb8233fac2010-10-26 16:08:53 -07001633 case R.id.page_info_menu_id:
Huahui Wuae0c0412011-06-28 10:17:05 -07001634 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001635 break;
1636
1637 case R.id.classic_history_menu_id:
1638 bookmarksOrHistoryPicker(true);
1639 break;
1640
Michael Kolb8233fac2010-10-26 16:08:53 -07001641 case R.id.share_page_menu_id:
1642 Tab currentTab = mTabControl.getCurrentTab();
1643 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001644 return false;
1645 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001646 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001647 break;
1648
1649 case R.id.dump_nav_menu_id:
1650 getCurrentTopWebView().debugDump();
1651 break;
1652
1653 case R.id.dump_counters_menu_id:
1654 getCurrentTopWebView().dumpV8Counters();
1655 break;
1656
1657 case R.id.zoom_in_menu_id:
1658 getCurrentTopWebView().zoomIn();
1659 break;
1660
1661 case R.id.zoom_out_menu_id:
1662 getCurrentTopWebView().zoomOut();
1663 break;
1664
1665 case R.id.view_downloads_menu_id:
1666 viewDownloads();
1667 break;
1668
1669 case R.id.window_one_menu_id:
1670 case R.id.window_two_menu_id:
1671 case R.id.window_three_menu_id:
1672 case R.id.window_four_menu_id:
1673 case R.id.window_five_menu_id:
1674 case R.id.window_six_menu_id:
1675 case R.id.window_seven_menu_id:
1676 case R.id.window_eight_menu_id:
1677 {
1678 int menuid = item.getItemId();
1679 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1680 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1681 Tab desiredTab = mTabControl.getTab(id);
1682 if (desiredTab != null &&
1683 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001684 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001685 }
1686 break;
1687 }
1688 }
1689 }
1690 break;
1691
1692 default:
1693 return false;
1694 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001695 return true;
1696 }
1697
1698 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001699 // Let the History and Bookmark fragments handle menus they created.
1700 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1701 return false;
1702 }
1703
Michael Kolb8233fac2010-10-26 16:08:53 -07001704 int id = item.getItemId();
1705 boolean result = true;
1706 switch (id) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001707 // -- Browser context menu
1708 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001709 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001710 case R.id.copy_link_context_menu_id:
1711 final WebView webView = getCurrentTopWebView();
1712 if (null == webView) {
1713 result = false;
1714 break;
1715 }
1716 final HashMap<String, WebView> hrefMap =
1717 new HashMap<String, WebView>();
1718 hrefMap.put("webview", webView);
1719 final Message msg = mHandler.obtainMessage(
1720 FOCUS_NODE_HREF, id, 0, hrefMap);
1721 webView.requestFocusNodeHref(msg);
1722 break;
1723
1724 default:
1725 // For other context menus
1726 result = onOptionsItemSelected(item);
1727 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001728 return result;
1729 }
1730
1731 /**
1732 * support programmatically opening the context menu
1733 */
1734 public void openContextMenu(View view) {
1735 mActivity.openContextMenu(view);
1736 }
1737
1738 /**
1739 * programmatically open the options menu
1740 */
1741 public void openOptionsMenu() {
1742 mActivity.openOptionsMenu();
1743 }
1744
1745 public boolean onMenuOpened(int featureId, Menu menu) {
1746 if (mOptionsMenuOpen) {
1747 if (mConfigChanged) {
1748 // We do not need to make any changes to the state of the
1749 // title bar, since the only thing that happened was a
1750 // change in orientation
1751 mConfigChanged = false;
1752 } else {
1753 if (!mExtendedMenuOpen) {
1754 mExtendedMenuOpen = true;
1755 mUi.onExtendedMenuOpened();
1756 } else {
1757 // Switching the menu back to icon view, so show the
1758 // title bar once again.
1759 mExtendedMenuOpen = false;
1760 mUi.onExtendedMenuClosed(mInLoad);
Michael Kolb8233fac2010-10-26 16:08:53 -07001761 }
1762 }
1763 } else {
1764 // The options menu is closed, so open it, and show the title
1765 mOptionsMenuOpen = true;
1766 mConfigChanged = false;
1767 mExtendedMenuOpen = false;
1768 mUi.onOptionsMenuOpened();
1769 }
1770 return true;
1771 }
1772
1773 public void onOptionsMenuClosed(Menu menu) {
1774 mOptionsMenuOpen = false;
1775 mUi.onOptionsMenuClosed(mInLoad);
1776 }
1777
1778 public void onContextMenuClosed(Menu menu) {
1779 mUi.onContextMenuClosed(menu, mInLoad);
1780 }
1781
1782 // Helper method for getting the top window.
1783 @Override
1784 public WebView getCurrentTopWebView() {
1785 return mTabControl.getCurrentTopWebView();
1786 }
1787
1788 @Override
1789 public WebView getCurrentWebView() {
1790 return mTabControl.getCurrentWebView();
1791 }
1792
1793 /*
1794 * This method is called as a result of the user selecting the options
1795 * menu to see the download window. It shows the download window on top of
1796 * the current window.
1797 */
1798 void viewDownloads() {
1799 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1800 mActivity.startActivity(intent);
1801 }
1802
John Reck30b065e2011-07-19 10:58:05 -07001803 int getActionModeHeight() {
1804 TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
1805 new int[] { android.R.attr.actionBarSize });
1806 int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
1807 actionBarSizeTypedArray.recycle();
1808 return size;
1809 }
1810
Michael Kolb8233fac2010-10-26 16:08:53 -07001811 // action mode
1812
1813 void onActionModeStarted(ActionMode mode) {
1814 mUi.onActionModeStarted(mode);
1815 mActionMode = mode;
Michael Kolb42c0c062011-08-02 12:56:06 -07001816 if (mSimulateActionBarOverlayMode && !mUi.isEditingUrl()) {
John Reck30b065e2011-07-19 10:58:05 -07001817 WebView web = getCurrentWebView();
1818 // Simulate overlay mode by scrolling the webview the amount it will be
1819 // pushed down. Actual overlay mode doesn't work for us as otherwise
1820 // the CAB will, well, overlay the content, which breaks things like
1821 // find on page.
1822 int scrollBy = getActionModeHeight();
1823 web.scrollBy(0, scrollBy);
1824 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001825 }
1826
1827 /*
1828 * True if a custom ActionMode (i.e. find or select) is in use.
1829 */
1830 @Override
1831 public boolean isInCustomActionMode() {
1832 return mActionMode != null;
1833 }
1834
1835 /*
1836 * End the current ActionMode.
1837 */
1838 @Override
1839 public void endActionMode() {
1840 if (mActionMode != null) {
1841 mActionMode.finish();
1842 }
1843 }
1844
1845 /*
1846 * Called by find and select when they are finished. Replace title bars
1847 * as necessary.
1848 */
1849 public void onActionModeFinished(ActionMode mode) {
1850 if (!isInCustomActionMode()) return;
1851 mUi.onActionModeFinished(mInLoad);
1852 mActionMode = null;
John Reck30b065e2011-07-19 10:58:05 -07001853 if (mSimulateActionBarOverlayMode) {
1854 WebView web = getCurrentWebView();
1855 int scrollBy = getActionModeHeight();
1856 web.scrollBy(0, -scrollBy);
1857 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001858 }
1859
1860 boolean isInLoad() {
1861 return mInLoad;
1862 }
1863
1864 // bookmark handling
1865
1866 /**
1867 * add the current page as a bookmark to the given folder id
1868 * @param folderId use -1 for the default folder
John Reckd3e4d5b2011-07-13 15:48:43 -07001869 * @param editExisting If true, check to see whether the site is already
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001870 * bookmarked, and if it is, edit that bookmark. If false, and
1871 * the site is already bookmarked, do not attempt to edit the
1872 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001873 */
1874 @Override
John Reckd3e4d5b2011-07-13 15:48:43 -07001875 public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001876 Intent i = new Intent(mActivity,
1877 AddBookmarkPage.class);
1878 WebView w = getCurrentTopWebView();
1879 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1880 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1881 String touchIconUrl = w.getTouchIconUrl();
1882 if (touchIconUrl != null) {
1883 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1884 WebSettings settings = w.getSettings();
1885 if (settings != null) {
1886 i.putExtra(AddBookmarkPage.USER_AGENT,
1887 settings.getUserAgentString());
1888 }
1889 }
1890 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1891 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1892 getDesiredThumbnailHeight(mActivity)));
1893 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07001894 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001895 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1896 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001897 // Put the dialog at the upper right of the screen, covering the
1898 // star on the title bar.
1899 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07001900 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07001901 }
1902
1903 // file chooser
1904 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1905 mUploadHandler = new UploadHandler(this);
1906 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1907 }
1908
1909 // thumbnails
1910
1911 /**
1912 * Return the desired width for thumbnail screenshots, which are stored in
1913 * the database, and used on the bookmarks screen.
1914 * @param context Context for finding out the density of the screen.
1915 * @return desired width for thumbnail screenshot.
1916 */
1917 static int getDesiredThumbnailWidth(Context context) {
1918 return context.getResources().getDimensionPixelOffset(
1919 R.dimen.bookmarkThumbnailWidth);
1920 }
1921
1922 /**
1923 * Return the desired height for thumbnail screenshots, which are stored in
1924 * the database, and used on the bookmarks screen.
1925 * @param context Context for finding out the density of the screen.
1926 * @return desired height for thumbnail screenshot.
1927 */
1928 static int getDesiredThumbnailHeight(Context context) {
1929 return context.getResources().getDimensionPixelOffset(
1930 R.dimen.bookmarkThumbnailHeight);
1931 }
1932
John Reck8cc92352011-07-06 17:41:52 -07001933 static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001934 // We render to a bitmap 2x the desired size so that we can then
1935 // re-scale it with filtering since canvas.scale doesn't filter
1936 // This helps reduce aliasing at the cost of being slightly blurry
1937 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001938 Picture thumbnail = view.capturePicture();
1939 if (thumbnail == null) {
1940 return null;
1941 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001942 width *= filter_scale;
1943 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001944 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1945 Canvas canvas = new Canvas(bm);
1946 // May need to tweak these values to determine what is the
1947 // best scale factor
1948 int thumbnailWidth = thumbnail.getWidth();
1949 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001950 float scaleFactor = 1.0f;
Michael Kolbeb95db42011-03-03 10:38:40 -08001951 if (thumbnailWidth > 0 && thumbnailHeight > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001952 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001953 } else {
1954 return null;
1955 }
John Reckfe49ab42010-11-16 17:09:37 -08001956
Michael Kolbeb95db42011-03-03 10:38:40 -08001957 float scaleFactorY = (float) height / (float)thumbnailHeight;
1958 if (scaleFactorY > scaleFactor) {
1959 // The picture is narrower than the requested AR
1960 // Center the thumnail and crop the sides
1961 scaleFactor = scaleFactorY;
John Reckfe49ab42010-11-16 17:09:37 -08001962 float wx = (thumbnailWidth * scaleFactor) - width;
1963 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001964 }
1965
John Reckfe49ab42010-11-16 17:09:37 -08001966 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001967
1968 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001969 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
1970 height / filter_scale, true);
Dianne Hackborn43cfe8a2011-08-02 16:59:35 -07001971 canvas.setBitmap(null);
John Reck5c6ac2f2011-01-05 10:18:03 -08001972 bm.recycle();
1973 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001974 }
1975
John Reck34ef2672011-02-10 11:30:55 -08001976 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001977 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07001978 // FIXME: Would like to make sure there is actually something to
1979 // draw, but the API for that (WebViewCore.pictureReady()) is not
1980 // currently accessible here.
1981
John Reck34ef2672011-02-10 11:30:55 -08001982 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08001983 if (view == null) {
1984 // Tab was destroyed
1985 return;
1986 }
John Reck34ef2672011-02-10 11:30:55 -08001987 final String url = tab.getUrl();
1988 final String originalUrl = view.getOriginalUrl();
1989
1990 if (TextUtils.isEmpty(url)) {
1991 return;
1992 }
1993
1994 // Only update thumbnails for web urls (http(s)://), not for
1995 // about:, javascript:, data:, etc...
1996 // Unless it is a bookmarked site, then always update
1997 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
1998 return;
1999 }
2000
Michael Kolb8233fac2010-10-26 16:08:53 -07002001 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2002 getDesiredThumbnailHeight(mActivity));
2003 if (bm == null) {
2004 return;
2005 }
2006
2007 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002008 new AsyncTask<Void, Void, Void>() {
2009 @Override
2010 protected Void doInBackground(Void... unused) {
2011 Cursor cursor = null;
2012 try {
2013 // TODO: Clean this up
2014 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2015 if (cursor != null && cursor.moveToFirst()) {
2016 final ByteArrayOutputStream os =
2017 new ByteArrayOutputStream();
2018 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002019
John Reck34ef2672011-02-10 11:30:55 -08002020 ContentValues values = new ContentValues();
2021 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002022
John Reck34ef2672011-02-10 11:30:55 -08002023 do {
John Reck617fd832011-02-16 14:35:59 -08002024 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002025 cr.update(Images.CONTENT_URI, values, null, null);
2026 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002027 }
John Reck34ef2672011-02-10 11:30:55 -08002028 } catch (IllegalStateException e) {
2029 // Ignore
2030 } finally {
2031 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002032 }
John Reck34ef2672011-02-10 11:30:55 -08002033 return null;
2034 }
2035 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002036 }
2037
2038 private class Copy implements OnMenuItemClickListener {
2039 private CharSequence mText;
2040
2041 public boolean onMenuItemClick(MenuItem item) {
2042 copy(mText);
2043 return true;
2044 }
2045
2046 public Copy(CharSequence toCopy) {
2047 mText = toCopy;
2048 }
2049 }
2050
Leon Scroggins63c02662010-11-18 15:16:27 -05002051 private static class Download implements OnMenuItemClickListener {
2052 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002053 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002054 private boolean mPrivateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002055
2056 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002057 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002058 null, null, mPrivateBrowsing);
Michael Kolb8233fac2010-10-26 16:08:53 -07002059 return true;
2060 }
2061
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002062 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002063 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002064 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002065 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002066 }
2067 }
2068
Cary Clark8974d282010-11-22 10:46:05 -05002069 private static class SelectText implements OnMenuItemClickListener {
2070 private WebView mWebView;
2071
2072 public boolean onMenuItemClick(MenuItem item) {
2073 if (mWebView != null) {
2074 return mWebView.selectText();
2075 }
2076 return false;
2077 }
2078
2079 public SelectText(WebView webView) {
2080 mWebView = webView;
2081 }
2082
2083 }
2084
Michael Kolb8233fac2010-10-26 16:08:53 -07002085 /********************** TODO: UI stuff *****************************/
2086
2087 // these methods have been copied, they still need to be cleaned up
2088
2089 /****************** tabs ***************************************************/
2090
2091 // basic tab interactions:
2092
2093 // it is assumed that tabcontrol already knows about the tab
2094 protected void addTab(Tab tab) {
2095 mUi.addTab(tab);
2096 }
2097
2098 protected void removeTab(Tab tab) {
2099 mUi.removeTab(tab);
2100 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002101 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002102 }
2103
Michael Kolbf2055602011-04-09 17:20:03 -07002104 @Override
2105 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002106 // monkey protection against delayed start
2107 if (tab != null) {
2108 mTabControl.setCurrentTab(tab);
2109 // the tab is guaranteed to have a webview after setCurrentTab
2110 mUi.setActiveTab(tab);
2111 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002112 }
2113
2114 protected void closeEmptyChildTab() {
2115 Tab current = mTabControl.getCurrentTab();
2116 if (current != null
2117 && current.getWebView().copyBackForwardList().getSize() == 0) {
Michael Kolbc831b632011-05-11 09:30:34 -07002118 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002119 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002120 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002121 closeTab(current);
2122 }
2123 }
2124 }
2125
John Reck26b18322011-06-21 13:08:58 -07002126 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002127 // Dismiss the subwindow if applicable.
2128 dismissSubWindow(appTab);
2129 // Since we might kill the WebView, remove it from the
2130 // content view first.
2131 mUi.detachTab(appTab);
2132 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002133 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002134 // TODO: analyze why the remove and add are necessary
2135 mUi.attachTab(appTab);
2136 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002137 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002138 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002139 } else {
2140 // If the tab was the current tab, we have to attach
2141 // it to the view system again.
2142 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002143 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002144 }
2145 }
2146
2147 // Remove the sub window if it exists. Also called by TabControl when the
2148 // user clicks the 'X' to dismiss a sub window.
2149 public void dismissSubWindow(Tab tab) {
2150 removeSubWindow(tab);
2151 // dismiss the subwindow. This will destroy the WebView.
2152 tab.dismissSubWindow();
2153 getCurrentTopWebView().requestFocus();
2154 }
2155
2156 @Override
2157 public void removeSubWindow(Tab t) {
2158 if (t.getSubWebView() != null) {
2159 mUi.removeSubWindow(t.getSubViewContainer());
2160 }
2161 }
2162
2163 @Override
2164 public void attachSubWindow(Tab tab) {
2165 if (tab.getSubWebView() != null) {
2166 mUi.attachSubWindow(tab.getSubViewContainer());
2167 getCurrentTopWebView().requestFocus();
2168 }
2169 }
2170
Mathew Inwood29721c22011-06-29 17:55:24 +01002171 private Tab showPreloadedTab(final UrlData urlData) {
2172 if (!urlData.isPreloaded()) {
2173 return null;
2174 }
2175 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2176 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2177 if (sbQuery != null) {
2178 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
2179 // Could not submit query. Fallback to regular tab creation
2180 tabControl.destroy();
2181 return null;
2182 }
2183 }
Michael Kolbff6a7482011-07-26 16:37:15 -07002184 // check tab count and make room for new tab
2185 if (!mTabControl.canCreateNewTab()) {
2186 Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
2187 if (leastUsed != null) {
2188 closeTab(leastUsed);
2189 }
2190 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002191 Tab t = tabControl.getTab();
2192 mTabControl.addPreloadedTab(t);
2193 addTab(t);
2194 setActiveTab(t);
2195 return t;
2196 }
2197
Michael Kolb7bcafde2011-05-09 13:55:59 -07002198 // open a non inconito tab with the given url data
2199 // and set as active tab
2200 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002201 Tab tab = showPreloadedTab(urlData);
2202 if (tab == null) {
2203 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002204 if ((tab != null) && !urlData.isEmpty()) {
2205 loadUrlDataIn(tab, urlData);
2206 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002207 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002208 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002209 }
2210
Michael Kolb843510f2010-12-09 10:51:49 -08002211 @Override
2212 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002213 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002214 }
2215
Michael Kolb8233fac2010-10-26 16:08:53 -07002216 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002217 public Tab openIncognitoTab() {
2218 return openTab(INCOGNITO_URI, true, true, false);
2219 }
2220
2221 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002222 public Tab openTab(String url, boolean incognito, boolean setActive,
2223 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002224 return openTab(url, incognito, setActive, useCurrent, null);
2225 }
2226
2227 @Override
2228 public Tab openTab(String url, Tab parent, boolean setActive,
2229 boolean useCurrent) {
2230 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2231 setActive, useCurrent, parent);
2232 }
2233
2234 public Tab openTab(String url, boolean incognito, boolean setActive,
2235 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002236 Tab tab = createNewTab(incognito, setActive, useCurrent);
2237 if (tab != null) {
John Reck5949c662011-05-27 09:52:29 -07002238 if (parent != null && parent != tab) {
2239 parent.addChildTab(tab);
2240 }
Michael Kolb519d2282011-05-09 17:03:19 -07002241 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002242 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002243 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002244 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002245 return tab;
2246 }
2247
2248 // this method will attempt to create a new tab
2249 // incognito: private browsing tab
2250 // setActive: ste tab as current tab
2251 // useCurrent: if no new tab can be created, return current tab
2252 private Tab createNewTab(boolean incognito, boolean setActive,
2253 boolean useCurrent) {
2254 Tab tab = null;
2255 if (mTabControl.canCreateNewTab()) {
2256 tab = mTabControl.createNewTab(incognito);
2257 addTab(tab);
2258 if (setActive) {
2259 setActiveTab(tab);
2260 }
2261 } else {
2262 if (useCurrent) {
2263 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002264 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002265 } else {
2266 mUi.showMaxTabsWarning();
2267 }
2268 }
2269 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002270 }
2271
John Reck2bc80422011-06-30 15:11:49 -07002272 @Override
2273 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2274 SnapshotTab tab = null;
2275 if (mTabControl.canCreateNewTab()) {
2276 tab = mTabControl.createSnapshotTab(snapshotId);
2277 addTab(tab);
2278 if (setActive) {
2279 setActiveTab(tab);
2280 }
2281 } else {
2282 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07002283 }
2284 return tab;
2285 }
2286
Michael Kolb8233fac2010-10-26 16:08:53 -07002287 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002288 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002289 * @return boolean True if we successfully switched to a different tab. If
2290 * the indexth tab is null, or if that tab is the same as
2291 * the current one, return false.
2292 */
2293 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002294 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002295 Tab currentTab = mTabControl.getCurrentTab();
2296 if (tab == null || tab == currentTab) {
2297 return false;
2298 }
2299 setActiveTab(tab);
2300 return true;
2301 }
2302
2303 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002304 public void closeCurrentTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002305 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07002306 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07002307 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08002308 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002309 return;
2310 }
Michael Kolbc831b632011-05-11 09:30:34 -07002311 final Tab current = mTabControl.getCurrentTab();
2312 final int pos = mTabControl.getCurrentPosition();
2313 Tab newTab = current.getParent();
2314 if (newTab == null) {
2315 newTab = mTabControl.getTab(pos + 1);
2316 if (newTab == null) {
2317 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002318 }
2319 }
Michael Kolbc831b632011-05-11 09:30:34 -07002320 if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002321 // Close window
2322 closeTab(current);
2323 }
2324 }
2325
2326 /**
2327 * Close the tab, remove its associated title bar, and adjust mTabControl's
2328 * current tab to a valid value.
2329 */
2330 @Override
2331 public void closeTab(Tab tab) {
Michael Kolb2d59c322011-01-25 13:18:55 -08002332 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002333 }
2334
Michael Kolb8233fac2010-10-26 16:08:53 -07002335 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07002336 protected void loadUrlFromContext(String url) {
2337 Tab tab = getCurrentTab();
2338 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002339 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07002340 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002341 url = UrlUtils.smartUrlFilter(url);
2342 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07002343 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07002344 }
2345 }
2346 }
2347
2348 /**
2349 * Load the URL into the given WebView and update the title bar
2350 * to reflect the new load. Call this instead of WebView.loadUrl
2351 * directly.
2352 * @param view The WebView used to load url.
2353 * @param url The URL to load.
2354 */
John Reck71e51422011-07-01 16:49:28 -07002355 @Override
2356 public void loadUrl(Tab tab, String url) {
John Reck26b18322011-06-21 13:08:58 -07002357 loadUrl(tab, url, null);
2358 }
2359
2360 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
2361 if (tab != null) {
2362 dismissSubWindow(tab);
2363 tab.loadUrl(url, headers);
2364 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002365 }
2366
2367 /**
2368 * Load UrlData into a Tab and update the title bar to reflect the new
2369 * load. Call this instead of UrlData.loadIn directly.
2370 * @param t The Tab used to load.
2371 * @param data The UrlData being loaded.
2372 */
2373 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07002374 if (data != null) {
2375 if (data.mVoiceIntent != null) {
2376 t.activateVoiceSearchMode(data.mVoiceIntent);
Michael Kolb14612442011-06-24 13:06:29 -07002377 } else if (data.isPreloaded()) {
2378 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07002379 } else {
2380 loadUrl(t, data.mUrl, data.mHeaders);
2381 }
2382 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002383 }
2384
John Reck30c714c2010-12-16 17:30:34 -08002385 @Override
2386 public void onUserCanceledSsl(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08002387 // TODO: Figure out the "right" behavior
John Reckef654f12011-07-12 16:42:08 -07002388 if (tab.canGoBack()) {
2389 tab.goBack();
John Reck30c714c2010-12-16 17:30:34 -08002390 } else {
John Reckef654f12011-07-12 16:42:08 -07002391 tab.loadUrl(mSettings.getHomePage(), null);
John Reck30c714c2010-12-16 17:30:34 -08002392 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002393 }
2394
2395 void goBackOnePageOrQuit() {
2396 Tab current = mTabControl.getCurrentTab();
2397 if (current == null) {
2398 /*
2399 * Instead of finishing the activity, simply push this to the back
2400 * of the stack and let ActivityManager to choose the foreground
2401 * activity. As BrowserActivity is singleTask, it will be always the
2402 * root of the task. So we can use either true or false for
2403 * moveTaskToBack().
2404 */
2405 mActivity.moveTaskToBack(true);
2406 return;
2407 }
John Reckef654f12011-07-12 16:42:08 -07002408 if (current.canGoBack()) {
2409 current.goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07002410 } else {
2411 // Check to see if we are closing a window that was created by
2412 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002413 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002414 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002415 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002416 // Now we close the other tab
2417 closeTab(current);
2418 } else {
Michael Kolbe28b3472011-08-04 16:54:31 -07002419 if ((current.getAppId() != null) || current.closeOnBack()) {
2420 closeCurrentTab();
2421 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002422 /*
2423 * Instead of finishing the activity, simply push this to the back
2424 * of the stack and let ActivityManager to choose the foreground
2425 * activity. As BrowserActivity is singleTask, it will be always the
2426 * root of the task. So we can use either true or false for
2427 * moveTaskToBack().
2428 */
2429 mActivity.moveTaskToBack(true);
2430 }
2431 }
2432 }
2433
2434 /**
2435 * Feed the previously stored results strings to the BrowserProvider so that
2436 * the SearchDialog will show them instead of the standard searches.
2437 * @param result String to show on the editable line of the SearchDialog.
2438 */
2439 @Override
2440 public void showVoiceSearchResults(String result) {
2441 ContentProviderClient client = mActivity.getContentResolver()
2442 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2443 ContentProvider prov = client.getLocalContentProvider();
2444 BrowserProvider bp = (BrowserProvider) prov;
2445 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2446 client.release();
2447
2448 Bundle bundle = createGoogleSearchSourceBundle(
2449 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2450 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2451 startSearch(result, false, bundle, false);
2452 }
2453
2454 private void startSearch(String initialQuery, boolean selectInitialQuery,
2455 Bundle appSearchData, boolean globalSearch) {
2456 if (appSearchData == null) {
2457 appSearchData = createGoogleSearchSourceBundle(
2458 GOOGLE_SEARCH_SOURCE_TYPE);
2459 }
2460
2461 SearchEngine searchEngine = mSettings.getSearchEngine();
2462 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2463 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2464 }
2465 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2466 globalSearch);
2467 }
2468
2469 private Bundle createGoogleSearchSourceBundle(String source) {
2470 Bundle bundle = new Bundle();
2471 bundle.putString(Search.SOURCE, source);
2472 return bundle;
2473 }
2474
2475 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002476 * helper method for key handler
2477 * returns the current tab if it can't advance
2478 */
Michael Kolbc831b632011-05-11 09:30:34 -07002479 private Tab getNextTab() {
2480 return mTabControl.getTab(Math.min(mTabControl.getTabCount() - 1,
2481 mTabControl.getCurrentPosition() + 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002482 }
2483
2484 /**
2485 * helper method for key handler
2486 * returns the current tab if it can't advance
2487 */
Michael Kolbc831b632011-05-11 09:30:34 -07002488 private Tab getPrevTab() {
2489 return mTabControl.getTab(Math.max(0,
2490 mTabControl.getCurrentPosition() - 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002491 }
2492
2493 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002494 * handle key events in browser
2495 *
2496 * @param keyCode
2497 * @param event
2498 * @return true if handled, false to pass to super
2499 */
2500 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002501 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002502 // Even if MENU is already held down, we need to call to super to open
2503 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002504 if (!noModifiers
2505 && ((KeyEvent.KEYCODE_MENU == keyCode)
2506 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2507 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002508 mMenuIsDown = true;
2509 return false;
2510 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002511
Cary Clark8ff8c662010-12-29 15:03:05 -05002512 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07002513 Tab tab = getCurrentTab();
2514 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05002515
Cary Clark160bbb92011-01-10 11:17:07 -05002516 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2517 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002518
Michael Kolb8233fac2010-10-26 16:08:53 -07002519 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002520 case KeyEvent.KEYCODE_TAB:
2521 if (event.isCtrlPressed()) {
2522 if (event.isShiftPressed()) {
2523 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002524 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002525 } else {
2526 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002527 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002528 }
2529 return true;
2530 }
2531 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002532 case KeyEvent.KEYCODE_SPACE:
2533 // WebView/WebTextView handle the keys in the KeyDown. As
2534 // the Activity's shortcut keys are only handled when WebView
2535 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002536 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002537 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002538 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002539 pageDown();
2540 }
2541 return true;
2542 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002543 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002544 event.startTracking();
2545 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07002546 case KeyEvent.KEYCODE_FORWARD:
2547 if (!noModifiers) break;
2548 tab.goForward();
2549 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002550 case KeyEvent.KEYCODE_DPAD_LEFT:
2551 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002552 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05002553 return true;
2554 }
2555 break;
2556 case KeyEvent.KEYCODE_DPAD_RIGHT:
2557 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002558 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05002559 return true;
2560 }
2561 break;
2562 case KeyEvent.KEYCODE_A:
2563 if (ctrl) {
2564 webView.selectAll();
2565 return true;
2566 }
2567 break;
Michael Kolba4183062011-01-16 10:43:21 -08002568// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002569 case KeyEvent.KEYCODE_C:
2570 if (ctrl) {
2571 webView.copySelection();
2572 return true;
2573 }
2574 break;
Michael Kolba4183062011-01-16 10:43:21 -08002575// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002576// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002577// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002578// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002579// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002580// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002581// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002582// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002583// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002584// case KeyEvent.KEYCODE_M: // unused
2585// case KeyEvent.KEYCODE_N: // in Chrome: new window
2586// case KeyEvent.KEYCODE_O: // in Chrome: open file
2587// case KeyEvent.KEYCODE_P: // in Chrome: print page
2588// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002589// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002590// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2591 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002592 // we can't use the ctrl/shift flags, they check for
2593 // exclusive use of a modifier
2594 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002595 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002596 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002597 } else {
2598 openTabToHomePage();
2599 }
2600 return true;
2601 }
2602 break;
2603// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2604// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb1a2eba42011-03-16 16:42:49 -07002605 case KeyEvent.KEYCODE_W: // in Chrome: close tab
2606 if (ctrl) {
2607 closeCurrentTab();
2608 return true;
2609 }
2610 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002611// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2612// case KeyEvent.KEYCODE_Y: // unused
2613// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002614 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002615 // it is a regular key and webview is not null
2616 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002617 }
2618
John Recke6bf4ab2011-02-24 15:48:05 -08002619 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2620 switch(keyCode) {
2621 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07002622 if (mUi.isWebShowing()) {
John Recke6bf4ab2011-02-24 15:48:05 -08002623 bookmarksOrHistoryPicker(true);
2624 return true;
2625 }
2626 break;
2627 }
2628 return false;
2629 }
2630
Michael Kolb8233fac2010-10-26 16:08:53 -07002631 boolean onKeyUp(int keyCode, KeyEvent event) {
Michael Kolb2814a362011-05-19 15:49:41 -07002632 if (KeyEvent.KEYCODE_MENU == keyCode) {
2633 mMenuIsDown = false;
2634 if (event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002635 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002636 }
2637 }
Cary Clark160bbb92011-01-10 11:17:07 -05002638 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002639 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002640 case KeyEvent.KEYCODE_BACK:
2641 if (event.isTracking() && !event.isCanceled()) {
2642 onBackKey();
2643 return true;
2644 }
2645 break;
2646 }
2647 return false;
2648 }
2649
2650 public boolean isMenuDown() {
2651 return mMenuIsDown;
2652 }
2653
Ben Murdoch8029a772010-11-16 11:58:21 +00002654 public void setupAutoFill(Message message) {
2655 // Open the settings activity at the AutoFill profile fragment so that
2656 // the user can create a new profile. When they return, we will dispatch
2657 // the message so that we can autofill the form using their new profile.
2658 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2659 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2660 AutoFillSettingsFragment.class.getName());
2661 mAutoFillSetupMessage = message;
2662 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2663 }
John Reckb3417f02011-01-14 11:01:05 -08002664
2665 @Override
Narayan Kamath5119edd2011-02-23 15:49:17 +00002666 public void registerDropdownChangeListener(DropdownChangeListener d) {
2667 mUi.registerDropdownChangeListener(d);
2668 }
Michael Kolbfbc579a2011-07-07 15:59:33 -07002669
2670 public boolean onSearchRequested() {
2671 mUi.editUrl(false);
2672 return true;
2673 }
2674
John Reck1cf4b792011-07-26 10:22:22 -07002675 @Override
2676 public boolean shouldCaptureThumbnails() {
2677 return mUi.shouldCaptureThumbnails();
2678 }
2679
Michael Kolb8233fac2010-10-26 16:08:53 -07002680}