blob: f6feb4a6170f60179f737e9de55cf3ac201c0f4c [file] [log] [blame]
Michael Kolb8233fac2010-10-26 16:08:53 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
Michael Kolb8233fac2010-10-26 16:08:53 -070019import android.app.Activity;
20import android.app.DownloadManager;
Mathew Inwoodb4e831b2011-09-05 18:58:48 +010021import android.app.PendingIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070022import android.app.SearchManager;
23import android.content.ClipboardManager;
24import android.content.ContentProvider;
25import android.content.ContentProviderClient;
26import android.content.ContentResolver;
John Reckd8c74522011-06-14 08:45:00 -070027import android.content.ContentUris;
Michael Kolb8233fac2010-10-26 16:08:53 -070028import android.content.ContentValues;
29import android.content.Context;
30import android.content.Intent;
31import android.content.pm.PackageManager;
32import android.content.pm.ResolveInfo;
33import android.content.res.Configuration;
John Reck30b065e2011-07-19 10:58:05 -070034import android.content.res.TypedArray;
Leon Scroggins1961ed22010-12-07 15:22:21 -050035import android.database.ContentObserver;
Michael Kolb8233fac2010-10-26 16:08:53 -070036import android.database.Cursor;
37import android.database.sqlite.SQLiteDatabase;
Michael Kolb8233fac2010-10-26 16:08:53 -070038import android.graphics.Bitmap;
39import android.graphics.Canvas;
Michael Kolb8233fac2010-10-26 16:08:53 -070040import android.net.Uri;
41import android.net.http.SslError;
42import android.os.AsyncTask;
43import android.os.Bundle;
44import android.os.Handler;
45import android.os.Message;
46import android.os.PowerManager;
47import android.os.PowerManager.WakeLock;
Ben Murdoch8029a772010-11-16 11:58:21 +000048import android.preference.PreferenceActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -070049import android.provider.Browser;
50import android.provider.BrowserContract;
Michael Kolb8233fac2010-10-26 16:08:53 -070051import android.provider.BrowserContract.Images;
52import android.provider.ContactsContract;
53import android.provider.ContactsContract.Intents.Insert;
Michael Kolbcfa3af52010-12-14 10:36:11 -080054import android.speech.RecognizerIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070055import android.text.TextUtils;
56import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080057import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070058import android.view.ActionMode;
59import android.view.ContextMenu;
60import android.view.ContextMenu.ContextMenuInfo;
61import android.view.Gravity;
62import android.view.KeyEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070063import android.view.Menu;
64import android.view.MenuInflater;
65import android.view.MenuItem;
66import android.view.MenuItem.OnMenuItemClickListener;
Michael Kolbc3af0672011-08-09 10:24:41 -070067import android.view.MotionEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070068import android.view.View;
69import android.webkit.CookieManager;
70import android.webkit.CookieSyncManager;
71import android.webkit.HttpAuthHandler;
72import android.webkit.SslErrorHandler;
73import android.webkit.ValueCallback;
74import android.webkit.WebChromeClient;
75import android.webkit.WebIconDatabase;
76import android.webkit.WebSettings;
77import android.webkit.WebView;
Leon Scrogginsac993842011-02-02 12:54:07 -050078import android.widget.Toast;
Michael Kolb8233fac2010-10-26 16:08:53 -070079
Michael Kolb4bd767d2011-05-27 11:33:55 -070080import com.android.browser.IntentHandler.UrlData;
John Reck2bc80422011-06-30 15:11:49 -070081import com.android.browser.UI.ComboViews;
Michael Kolb4bd767d2011-05-27 11:33:55 -070082import com.android.browser.UI.DropdownChangeListener;
83import com.android.browser.provider.BrowserProvider;
John Reck1cf4b792011-07-26 10:22:22 -070084import com.android.browser.provider.BrowserProvider2.Thumbnails;
John Reck8cc92352011-07-06 17:41:52 -070085import com.android.browser.provider.SnapshotProvider.Snapshots;
Michael Kolb4bd767d2011-05-27 11:33:55 -070086import com.android.browser.search.SearchEngine;
87import com.android.common.Search;
88
Michael Kolb8233fac2010-10-26 16:08:53 -070089import java.io.ByteArrayOutputStream;
Michael Kolb8233fac2010-10-26 16:08:53 -070090import java.net.URLEncoder;
John Reck1cf4b792011-07-26 10:22:22 -070091import java.util.ArrayList;
Michael Kolb8233fac2010-10-26 16:08:53 -070092import java.util.Calendar;
93import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -080094import java.util.List;
John Reck26b18322011-06-21 13:08:58 -070095import java.util.Map;
Mathew Inwoodb4e831b2011-09-05 18:58:48 +010096import java.util.regex.Pattern;
Michael Kolb8233fac2010-10-26 16:08:53 -070097
98/**
99 * Controller for browser
100 */
101public class Controller
102 implements WebViewController, UiController {
103
104 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800105 private static final String SEND_APP_ID_EXTRA =
106 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
Michael Kolba4261fd2011-05-05 11:27:37 -0700107 private static final String INCOGNITO_URI = "browser:incognito";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800108
Michael Kolb8233fac2010-10-26 16:08:53 -0700109
110 // public message ids
111 public final static int LOAD_URL = 1001;
112 public final static int STOP_LOAD = 1002;
113
114 // Message Ids
115 private static final int FOCUS_NODE_HREF = 102;
116 private static final int RELEASE_WAKELOCK = 107;
117
118 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
119
120 private static final int OPEN_BOOKMARKS = 201;
121
122 private static final int EMPTY_MENU = -1;
123
Michael Kolb8233fac2010-10-26 16:08:53 -0700124 // activity requestCode
John Reckd3e4d5b2011-07-13 15:48:43 -0700125 final static int COMBO_VIEW = 1;
Michael Kolb8233fac2010-10-26 16:08:53 -0700126 final static int PREFERENCES_PAGE = 3;
127 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000128 final static int AUTOFILL_SETUP = 5;
129
Michael Kolb8233fac2010-10-26 16:08:53 -0700130 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
131
132 // As the ids are dynamically created, we can't guarantee that they will
133 // be in sequence, so this static array maps ids to a window number.
134 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
135 { R.id.window_one_menu_id, R.id.window_two_menu_id,
136 R.id.window_three_menu_id, R.id.window_four_menu_id,
137 R.id.window_five_menu_id, R.id.window_six_menu_id,
138 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
139
140 // "source" parameter for Google search through search key
141 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
142 // "source" parameter for Google search through simplily type
143 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
144
Guang Zhu9e78f512011-05-04 11:45:11 -0700145 // "no-crash-recovery" parameter in intetnt to suppress crash recovery
146 final static String NO_CRASH_RECOVERY = "no-crash-recovery";
147
John Reckd7dd9b22011-08-30 09:18:29 -0700148 // A bitmap that is re-used in createScreenshot as scratch space
149 private static Bitmap sThumbnailBitmap;
150
Michael Kolb8233fac2010-10-26 16:08:53 -0700151 private Activity mActivity;
152 private UI mUi;
153 private TabControl mTabControl;
154 private BrowserSettings mSettings;
155 private WebViewFactory mFactory;
156
157 private WakeLock mWakeLock;
158
159 private UrlHandler mUrlHandler;
160 private UploadHandler mUploadHandler;
161 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700162 private PageDialogsHandler mPageDialogsHandler;
163 private NetworkStateHandler mNetworkHandler;
164
Ben Murdoch8029a772010-11-16 11:58:21 +0000165 private Message mAutoFillSetupMessage;
166
Michael Kolb8233fac2010-10-26 16:08:53 -0700167 private boolean mShouldShowErrorConsole;
168
169 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
170
171 // FIXME, temp address onPrepareMenu performance problem.
172 // When we move everything out of view, we should rewrite this.
173 private int mCurrentMenuState = 0;
174 private int mMenuState = R.id.MAIN_MENU;
175 private int mOldMenuState = EMPTY_MENU;
176 private Menu mCachedMenu;
177
Michael Kolb8233fac2010-10-26 16:08:53 -0700178 private boolean mMenuIsDown;
179
180 // For select and find, we keep track of the ActionMode so that
181 // finish() can be called as desired.
182 private ActionMode mActionMode;
183
184 /**
185 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
186 * of whether the configuration has changed. The first onMenuOpened call
187 * after a configuration change is simply a reopening of the same menu
188 * (i.e. mIconView did not change).
189 */
190 private boolean mConfigChanged;
191
192 /**
193 * Keeps track of whether the options menu is open. This is important in
194 * determining whether to show or hide the title bar overlay
195 */
196 private boolean mOptionsMenuOpen;
197
198 /**
199 * Whether or not the options menu is in its bigger, popup menu form. When
200 * true, we want the title bar overlay to be gone. When false, we do not.
201 * Only meaningful if mOptionsMenuOpen is true.
202 */
203 private boolean mExtendedMenuOpen;
204
205 private boolean mInLoad;
206
207 private boolean mActivityPaused = true;
208 private boolean mLoadStopped;
209
210 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500211 // Checks to see when the bookmarks database has changed, and updates the
212 // Tabs' notion of whether they represent bookmarked sites.
213 private ContentObserver mBookmarksObserver;
John Reck847b5322011-04-14 17:02:18 -0700214 private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700215
John Reck30b065e2011-07-19 10:58:05 -0700216 private boolean mSimulateActionBarOverlayMode;
217
Michael Kolbc3af0672011-08-09 10:24:41 -0700218 private boolean mBlockEvents;
219
John Reckbc490d22011-07-22 15:04:59 -0700220 public Controller(Activity browser, boolean preloadCrashState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700221 mActivity = browser;
222 mSettings = BrowserSettings.getInstance();
223 mTabControl = new TabControl(this);
224 mSettings.setController(this);
John Reck378a4102011-06-09 16:23:01 -0700225 mCrashRecoveryHandler = CrashRecoveryHandler.initialize(this);
John Reckbc490d22011-07-22 15:04:59 -0700226 if (preloadCrashState) {
227 mCrashRecoveryHandler.preloadCrashState();
228 }
Michael Kolb14612442011-06-24 13:06:29 -0700229 mFactory = new BrowserWebViewFactory(browser);
Michael Kolb8233fac2010-10-26 16:08:53 -0700230
231 mUrlHandler = new UrlHandler(this);
232 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700233 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
234
Michael Kolb8233fac2010-10-26 16:08:53 -0700235 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500236 mBookmarksObserver = new ContentObserver(mHandler) {
237 @Override
238 public void onChange(boolean selfChange) {
239 int size = mTabControl.getTabCount();
240 for (int i = 0; i < size; i++) {
241 mTabControl.getTab(i).updateBookmarkedStatus();
242 }
243 }
244
245 };
246 browser.getContentResolver().registerContentObserver(
247 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700248
249 mNetworkHandler = new NetworkStateHandler(mActivity, this);
250 // Start watching the default geolocation permissions
251 mSystemAllowGeolocationOrigins =
252 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
253 mSystemAllowGeolocationOrigins.start();
254
John Reckaf262e72011-07-25 13:55:44 -0700255 openIconDatabase();
John Reck30b065e2011-07-19 10:58:05 -0700256 mSimulateActionBarOverlayMode = !BrowserActivity.isTablet(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700257 }
258
Patrick Scott7d50a932011-02-04 09:27:26 -0500259 void start(final Bundle icicle, final Intent intent) {
Guang Zhu9e78f512011-05-04 11:45:11 -0700260 boolean noCrashRecovery = intent.getBooleanExtra(NO_CRASH_RECOVERY, false);
261 if (icicle != null || noCrashRecovery) {
John Reck847b5322011-04-14 17:02:18 -0700262 doStart(icicle, intent);
263 } else {
264 mCrashRecoveryHandler.startRecovery(intent);
265 }
266 }
267
268 void doStart(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700269 // Unless the last browser usage was within 24 hours, destroy any
270 // remaining incognito tabs.
271
272 Calendar lastActiveDate = icicle != null ?
273 (Calendar) icicle.getSerializable("lastActiveDate") : null;
274 Calendar today = Calendar.getInstance();
275 Calendar yesterday = Calendar.getInstance();
276 yesterday.add(Calendar.DATE, -1);
277
Patrick Scott7d50a932011-02-04 09:27:26 -0500278 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700279 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800280 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700281
Patrick Scott7d50a932011-02-04 09:27:26 -0500282 // Find out if we will restore any state and remember the tab.
Michael Kolbc831b632011-05-11 09:30:34 -0700283 final long currentTabId =
Patrick Scott7d50a932011-02-04 09:27:26 -0500284 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000285
Michael Kolbc831b632011-05-11 09:30:34 -0700286 if (currentTabId == -1) {
Patrick Scott7d50a932011-02-04 09:27:26 -0500287 // Not able to restore so we go ahead and clear session cookies. We
288 // must do this before trying to login the user as we don't want to
289 // clear any session cookies set during login.
290 CookieManager.getInstance().removeSessionCookie();
291 }
292
Patrick Scottd43e75a2011-03-14 14:47:23 -0400293 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500294 new Runnable() {
295 @Override public void run() {
Michael Kolbc831b632011-05-11 09:30:34 -0700296 onPreloginFinished(icicle, intent, currentTabId, restoreIncognitoTabs);
Patrick Scott7d50a932011-02-04 09:27:26 -0500297 }
298 });
299 }
300
Michael Kolbc831b632011-05-11 09:30:34 -0700301 private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId,
Patrick Scott7d50a932011-02-04 09:27:26 -0500302 boolean restoreIncognitoTabs) {
Michael Kolbc831b632011-05-11 09:30:34 -0700303 if (currentTabId == -1) {
John Reck1cf4b792011-07-26 10:22:22 -0700304 BackgroundHandler.execute(new PruneThumbnails(mActivity, null));
Michael Kolb8233fac2010-10-26 16:08:53 -0700305 final Bundle extra = intent.getExtras();
306 // Create an initial tab.
307 // If the intent is ACTION_VIEW and data is not null, the Browser is
308 // invoked to view the content by another application. In this case,
309 // the tab will be close when exit.
Michael Kolb14612442011-06-24 13:06:29 -0700310 UrlData urlData = IntentHandler.getUrlDataFromIntent(intent);
Michael Kolb7bcafde2011-05-09 13:55:59 -0700311 Tab t = null;
312 if (urlData.isEmpty()) {
313 t = openTabToHomePage();
314 } else {
315 t = openTab(urlData);
316 }
317 if (t != null) {
318 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
319 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700320 WebView webView = t.getWebView();
321 if (extra != null) {
322 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
323 if (scale > 0 && scale <= 1000) {
324 webView.setInitialScale(scale);
325 }
326 }
John Reckd8c74522011-06-14 08:45:00 -0700327 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700328 } else {
Michael Kolbc831b632011-05-11 09:30:34 -0700329 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
Patrick Scott7d50a932011-02-04 09:27:26 -0500330 mUi.needsRestoreAllTabs());
John Reck1cf4b792011-07-26 10:22:22 -0700331 List<Tab> tabs = mTabControl.getTabs();
332 ArrayList<Long> restoredTabs = new ArrayList<Long>(tabs.size());
333 for (Tab t : tabs) {
334 restoredTabs.add(t.getId());
335 }
336 BackgroundHandler.execute(new PruneThumbnails(mActivity, restoredTabs));
John Reck52be4782011-08-26 15:37:29 -0700337 if (tabs.size() == 0) {
338 openTabToHomePage();
339 }
John Reck1cf4b792011-07-26 10:22:22 -0700340 mUi.updateTabs(tabs);
Michael Kolb8233fac2010-10-26 16:08:53 -0700341 // TabControl.restoreState() will create a new tab even if
342 // restoring the state fails.
343 setActiveTab(mTabControl.getCurrentTab());
John Reckdb22ec42011-06-29 11:31:24 -0700344 // Handle the intent
345 mIntentHandler.onNewIntent(intent);
Michael Kolb8233fac2010-10-26 16:08:53 -0700346 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700347 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700348 String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb8233fac2010-10-26 16:08:53 -0700349 if (jsFlags.trim().length() != 0) {
350 getCurrentWebView().setJsFlags(jsFlags);
351 }
John Reck439c9a52010-12-14 10:04:39 -0800352 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
353 bookmarksOrHistoryPicker(false);
354 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700355 }
356
John Reck1cf4b792011-07-26 10:22:22 -0700357 private static class PruneThumbnails implements Runnable {
358 private Context mContext;
359 private List<Long> mIds;
360
361 PruneThumbnails(Context context, List<Long> preserveIds) {
362 mContext = context.getApplicationContext();
363 mIds = preserveIds;
364 }
365
366 @Override
367 public void run() {
368 ContentResolver cr = mContext.getContentResolver();
369 if (mIds == null || mIds.size() == 0) {
370 cr.delete(Thumbnails.CONTENT_URI, null, null);
371 } else {
372 int length = mIds.size();
373 StringBuilder where = new StringBuilder();
374 where.append(Thumbnails._ID);
375 where.append(" not in (");
376 for (int i = 0; i < length; i++) {
377 where.append(mIds.get(i));
378 if (i < (length - 1)) {
379 where.append(",");
380 }
381 }
382 where.append(")");
383 cr.delete(Thumbnails.CONTENT_URI, where.toString(), null);
384 }
385 }
386
387 }
388
Michael Kolb1514bb72010-11-22 09:11:48 -0800389 @Override
390 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700391 return mFactory;
392 }
393
394 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800395 public void onSetWebView(Tab tab, WebView view) {
396 mUi.onSetWebView(tab, view);
397 }
398
399 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800400 public void createSubWindow(Tab tab) {
401 endActionMode();
402 WebView mainView = tab.getWebView();
403 WebView subView = mFactory.createWebView((mainView == null)
404 ? false
405 : mainView.isPrivateBrowsingEnabled());
406 mUi.createSubWindow(tab, subView);
407 }
408
409 @Override
Michael Kolb14612442011-06-24 13:06:29 -0700410 public Context getContext() {
411 return mActivity;
412 }
413
414 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700415 public Activity getActivity() {
416 return mActivity;
417 }
418
419 void setUi(UI ui) {
420 mUi = ui;
421 }
422
423 BrowserSettings getSettings() {
424 return mSettings;
425 }
426
427 IntentHandler getIntentHandler() {
428 return mIntentHandler;
429 }
430
431 @Override
432 public UI getUi() {
433 return mUi;
434 }
435
436 int getMaxTabs() {
437 return mActivity.getResources().getInteger(R.integer.max_tabs);
438 }
439
440 @Override
441 public TabControl getTabControl() {
442 return mTabControl;
443 }
444
Michael Kolb1bf23132010-11-19 12:55:12 -0800445 @Override
446 public List<Tab> getTabs() {
447 return mTabControl.getTabs();
448 }
449
John Reckaf262e72011-07-25 13:55:44 -0700450 // Open the icon database.
451 private void openIconDatabase() {
452 // We have to call getInstance on the UI thread
453 final WebIconDatabase instance = WebIconDatabase.getInstance();
454 BackgroundHandler.execute(new Runnable() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000455
John Reckaf262e72011-07-25 13:55:44 -0700456 @Override
457 public void run() {
458 instance.open(mActivity.getDir("icons", 0).getPath());
Michael Kolb8233fac2010-10-26 16:08:53 -0700459 }
John Reckaf262e72011-07-25 13:55:44 -0700460 });
Michael Kolb8233fac2010-10-26 16:08:53 -0700461 }
462
463 private void startHandler() {
464 mHandler = new Handler() {
465
466 @Override
467 public void handleMessage(Message msg) {
468 switch (msg.what) {
469 case OPEN_BOOKMARKS:
470 bookmarksOrHistoryPicker(false);
471 break;
472 case FOCUS_NODE_HREF:
473 {
474 String url = (String) msg.getData().get("url");
475 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500476 String src = (String) msg.getData().get("src");
477 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700478 if (TextUtils.isEmpty(url)) {
479 break;
480 }
481 HashMap focusNodeMap = (HashMap) msg.obj;
482 WebView view = (WebView) focusNodeMap.get("webview");
483 // Only apply the action if the top window did not change.
484 if (getCurrentTopWebView() != view) {
485 break;
486 }
487 switch (msg.arg1) {
488 case R.id.open_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700489 loadUrlFromContext(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700490 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500491 case R.id.view_image_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700492 loadUrlFromContext(src);
Cary Clark043c2d62010-12-15 11:19:39 -0500493 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500494 case R.id.open_newtab_context_menu_id:
495 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -0700496 openTab(url, parent,
497 !mSettings.openInBackground(), true);
Leon Scroggins026f2542010-11-22 13:26:12 -0500498 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700499 case R.id.copy_link_context_menu_id:
500 copy(url);
501 break;
502 case R.id.save_link_context_menu_id:
503 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500504 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000505 mActivity, url, null, null, null,
506 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700507 break;
508 }
509 break;
510 }
511
512 case LOAD_URL:
John Reck26b18322011-06-21 13:08:58 -0700513 loadUrlFromContext((String) msg.obj);
Michael Kolb8233fac2010-10-26 16:08:53 -0700514 break;
515
516 case STOP_LOAD:
517 stopLoading();
518 break;
519
520 case RELEASE_WAKELOCK:
John Reckf57c0292011-07-21 18:15:39 -0700521 if (mWakeLock != null && mWakeLock.isHeld()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700522 mWakeLock.release();
523 // if we reach here, Browser should be still in the
524 // background loading after WAKELOCK_TIMEOUT (5-min).
525 // To avoid burning the battery, stop loading.
526 mTabControl.stopAllLoading();
527 }
528 break;
529
530 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800531 Tab tab = (Tab) msg.obj;
532 if (tab != null) {
533 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700534 }
535 break;
536 }
537 }
538 };
539
540 }
541
John Reckef654f12011-07-12 16:42:08 -0700542 @Override
Martijn Coenenb2f93552011-06-14 10:48:35 +0200543 public Tab getCurrentTab() {
544 return mTabControl.getCurrentTab();
545 }
546
Michael Kolbba99c5d2010-11-29 14:57:41 -0800547 @Override
548 public void shareCurrentPage() {
549 shareCurrentPage(mTabControl.getCurrentTab());
550 }
551
552 private void shareCurrentPage(Tab tab) {
553 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800554 sharePage(mActivity, tab.getTitle(),
555 tab.getUrl(), tab.getFavicon(),
556 createScreenshot(tab.getWebView(),
557 getDesiredThumbnailWidth(mActivity),
558 getDesiredThumbnailHeight(mActivity)));
559 }
560 }
561
Michael Kolb8233fac2010-10-26 16:08:53 -0700562 /**
563 * Share a page, providing the title, url, favicon, and a screenshot. Uses
564 * an {@link Intent} to launch the Activity chooser.
565 * @param c Context used to launch a new Activity.
566 * @param title Title of the page. Stored in the Intent with
567 * {@link Intent#EXTRA_SUBJECT}
568 * @param url URL of the page. Stored in the Intent with
569 * {@link Intent#EXTRA_TEXT}
570 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
571 * with {@link Browser#EXTRA_SHARE_FAVICON}
572 * @param screenshot Bitmap of a screenshot of the page. Stored in the
573 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
574 */
575 static final void sharePage(Context c, String title, String url,
576 Bitmap favicon, Bitmap screenshot) {
577 Intent send = new Intent(Intent.ACTION_SEND);
578 send.setType("text/plain");
579 send.putExtra(Intent.EXTRA_TEXT, url);
580 send.putExtra(Intent.EXTRA_SUBJECT, title);
581 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
582 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
583 try {
584 c.startActivity(Intent.createChooser(send, c.getString(
585 R.string.choosertitle_sharevia)));
586 } catch(android.content.ActivityNotFoundException ex) {
587 // if no app handles it, do nothing
588 }
589 }
590
591 private void copy(CharSequence text) {
592 ClipboardManager cm = (ClipboardManager) mActivity
593 .getSystemService(Context.CLIPBOARD_SERVICE);
594 cm.setText(text);
595 }
596
597 // lifecycle
598
599 protected void onConfgurationChanged(Configuration config) {
600 mConfigChanged = true;
601 if (mPageDialogsHandler != null) {
602 mPageDialogsHandler.onConfigurationChanged(config);
603 }
604 mUi.onConfigurationChanged(config);
605 }
606
607 @Override
608 public void handleNewIntent(Intent intent) {
Michael Kolb59e232c2011-08-18 17:19:53 -0700609 if (!mUi.isWebShowing()) {
610 mUi.showWeb(false);
611 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700612 mIntentHandler.onNewIntent(intent);
613 }
614
615 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800616 if (mUi.isCustomViewShowing()) {
617 hideCustomView();
618 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700619 if (mActivityPaused) {
620 Log.e(LOGTAG, "BrowserActivity is already paused.");
621 return;
622 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700623 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800624 Tab tab = mTabControl.getCurrentTab();
625 if (tab != null) {
626 tab.pause();
627 if (!pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700628 if (mWakeLock == null) {
629 PowerManager pm = (PowerManager) mActivity
630 .getSystemService(Context.POWER_SERVICE);
631 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
632 }
Michael Kolb70976932010-11-30 11:34:01 -0800633 mWakeLock.acquire();
634 mHandler.sendMessageDelayed(mHandler
635 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
636 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700637 }
638 mUi.onPause();
639 mNetworkHandler.onPause();
640
641 WebView.disablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100642 NfcHandler.unregister(mActivity);
John Reckd7dd9b22011-08-30 09:18:29 -0700643 if (sThumbnailBitmap != null) {
644 sThumbnailBitmap.recycle();
645 sThumbnailBitmap = null;
646 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700647 }
648
John Reck1cf4b792011-07-26 10:22:22 -0700649 void onSaveInstanceState(Bundle outState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700650 // the default implementation requires each view to have an id. As the
651 // browser handles the state itself and it doesn't use id for the views,
652 // don't call the default implementation. Otherwise it will trigger the
653 // warning like this, "couldn't save which view has focus because the
654 // focused view XXX has no id".
655
656 // Save all the tabs
John Reck1cf4b792011-07-26 10:22:22 -0700657 mTabControl.saveState(outState);
John Reck24f18262011-06-17 14:47:20 -0700658 if (!outState.isEmpty()) {
659 // Save time so that we know how old incognito tabs (if any) are.
660 outState.putSerializable("lastActiveDate", Calendar.getInstance());
661 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700662 }
663
664 void onResume() {
665 if (!mActivityPaused) {
666 Log.e(LOGTAG, "BrowserActivity is already resumed.");
667 return;
668 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700669 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800670 Tab current = mTabControl.getCurrentTab();
671 if (current != null) {
672 current.resume();
673 resumeWebViewTimers(current);
674 }
John Reckf57c0292011-07-21 18:15:39 -0700675 releaseWakeLock();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200676
Michael Kolb8233fac2010-10-26 16:08:53 -0700677 mUi.onResume();
678 mNetworkHandler.onResume();
679 WebView.enablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100680 NfcHandler.register(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700681 }
682
John Reckf57c0292011-07-21 18:15:39 -0700683 private void releaseWakeLock() {
684 if (mWakeLock != null && mWakeLock.isHeld()) {
685 mHandler.removeMessages(RELEASE_WAKELOCK);
686 mWakeLock.release();
687 }
688 }
689
Michael Kolb70976932010-11-30 11:34:01 -0800690 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800691 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800692 * @param tab guaranteed non-null
693 */
694 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700695 boolean inLoad = tab.inPageLoad();
696 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
697 CookieSyncManager.getInstance().startSync();
698 WebView w = tab.getWebView();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100699 WebViewTimersControl.getInstance().onBrowserActivityResume(w);
Michael Kolb8233fac2010-10-26 16:08:53 -0700700 }
701 }
702
Michael Kolb70976932010-11-30 11:34:01 -0800703 /**
704 * Pause all WebView timers using the WebView of the given tab
705 * @param tab
706 * @return true if the timers are paused or tab is null
707 */
708 private boolean pauseWebViewTimers(Tab tab) {
709 if (tab == null) {
710 return true;
711 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700712 CookieSyncManager.getInstance().stopSync();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100713 WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView());
Michael Kolb8233fac2010-10-26 16:08:53 -0700714 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700715 }
Michael Kolb70976932010-11-30 11:34:01 -0800716 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700717 }
718
719 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800720 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700721 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
722 mUploadHandler = null;
723 }
724 if (mTabControl == null) return;
725 mUi.onDestroy();
726 // Remove the current tab and sub window
727 Tab t = mTabControl.getCurrentTab();
728 if (t != null) {
729 dismissSubWindow(t);
730 removeTab(t);
731 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500732 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700733 // Destroy all the tabs
734 mTabControl.destroy();
735 WebIconDatabase.getInstance().close();
736 // Stop watching the default geolocation permissions
737 mSystemAllowGeolocationOrigins.stop();
738 mSystemAllowGeolocationOrigins = null;
739 }
740
741 protected boolean isActivityPaused() {
742 return mActivityPaused;
743 }
744
745 protected void onLowMemory() {
746 mTabControl.freeMemory();
747 }
748
749 @Override
750 public boolean shouldShowErrorConsole() {
751 return mShouldShowErrorConsole;
752 }
753
754 protected void setShouldShowErrorConsole(boolean show) {
755 if (show == mShouldShowErrorConsole) {
756 // Nothing to do.
757 return;
758 }
759 mShouldShowErrorConsole = show;
760 Tab t = mTabControl.getCurrentTab();
761 if (t == null) {
762 // There is no current tab so we cannot toggle the error console
763 return;
764 }
765 mUi.setShouldShowErrorConsole(t, show);
766 }
767
768 @Override
769 public void stopLoading() {
770 mLoadStopped = true;
771 Tab tab = mTabControl.getCurrentTab();
Mathew Inwoodb4e831b2011-09-05 18:58:48 +0100772 tab.clearPageLoadCompleteListener();
Michael Kolb8233fac2010-10-26 16:08:53 -0700773 WebView w = getCurrentTopWebView();
774 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700775 mUi.onPageStopped(tab);
776 }
777
778 boolean didUserStopLoading() {
779 return mLoadStopped;
780 }
781
782 // WebViewController
783
784 @Override
John Reck324d4402011-01-11 16:56:42 -0800785 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700786
787 // We've started to load a new page. If there was a pending message
788 // to save a screenshot then we will now take the new page and save
789 // an incorrect screenshot. Therefore, remove any pending thumbnail
790 // messages from the queue.
791 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800792 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700793
794 // reset sync timer to avoid sync starts during loading a page
795 CookieSyncManager.getInstance().resetSync();
796
797 if (!mNetworkHandler.isNetworkUp()) {
798 view.setNetworkAvailable(false);
799 }
800
801 // when BrowserActivity just starts, onPageStarted may be called before
802 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
803 // to start the timer. As we won't switch tabs while an activity is in
804 // pause state, we can ensure calling resume and pause in pair.
805 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800806 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700807 }
808 mLoadStopped = false;
809 if (!mNetworkHandler.isNetworkUp()) {
810 mNetworkHandler.createAndShowNetworkDialog();
811 }
812 endActionMode();
813
John Reck30c714c2010-12-16 17:30:34 -0800814 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700815
John Reck324d4402011-01-11 16:56:42 -0800816 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700817 // update the bookmark database for favicon
818 maybeUpdateFavicon(tab, null, url, favicon);
819
820 Performance.tracePageStart(url);
821
822 // Performance probe
823 if (false) {
824 Performance.onPageStarted();
825 }
826
827 }
828
829 @Override
John Reck324d4402011-01-11 16:56:42 -0800830 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800831 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800832 if (!tab.isPrivateBrowsingEnabled()
John Reckd8c74522011-06-14 08:45:00 -0700833 && !TextUtils.isEmpty(tab.getUrl())
834 && !tab.isSnapshot()) {
John Recka1696282011-07-08 14:10:37 -0700835 // Only update the bookmark screenshot if the user did not
836 // cancel the load early and there is not already
837 // a pending update for the tab.
Michael Kolb8233fac2010-10-26 16:08:53 -0700838 if (tab.inForeground() && !didUserStopLoading()
839 || !tab.inForeground()) {
John Recka1696282011-07-08 14:10:37 -0700840 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
841 mHandler.sendMessageDelayed(mHandler.obtainMessage(
842 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
843 500);
844 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700845 }
846 }
847 // pause the WebView timer and release the wake lock if it is finished
848 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800849 if (mActivityPaused && pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700850 releaseWakeLock();
Michael Kolb8233fac2010-10-26 16:08:53 -0700851 }
Martijn Coenenb2f93552011-06-14 10:48:35 +0200852
Michael Kolb8233fac2010-10-26 16:08:53 -0700853 // Performance probe
854 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800855 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700856 }
857
858 Performance.tracePageFinished();
859 }
860
861 @Override
John Reck30c714c2010-12-16 17:30:34 -0800862 public void onProgressChanged(Tab tab) {
John Reck6c2e2f32011-08-22 13:41:23 -0700863 mCrashRecoveryHandler.backupState();
John Reck30c714c2010-12-16 17:30:34 -0800864 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700865
866 if (newProgress == 100) {
867 CookieSyncManager.getInstance().sync();
868 // onProgressChanged() may continue to be called after the main
869 // frame has finished loading, as any remaining sub frames continue
870 // to load. We'll only get called once though with newProgress as
871 // 100 when everything is loaded. (onPageFinished is called once
872 // when the main frame completes loading regardless of the state of
873 // any sub frames so calls to onProgressChanges may continue after
874 // onPageFinished has executed)
875 if (mInLoad) {
876 mInLoad = false;
877 updateInLoadMenuItems(mCachedMenu);
878 }
879 } else {
880 if (!mInLoad) {
881 // onPageFinished may have already been called but a subframe is
882 // still loading and updating the progress. Reset mInLoad and
883 // update the menu items.
884 mInLoad = true;
885 updateInLoadMenuItems(mCachedMenu);
886 }
887 }
John Reck30c714c2010-12-16 17:30:34 -0800888 mUi.onProgressChanged(tab);
889 }
890
891 @Override
892 public void onUpdatedLockIcon(Tab tab) {
893 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700894 }
895
896 @Override
897 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800898 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800899 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800900 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700901 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
902 return;
903 }
904 // Update the title in the history database if not in private browsing mode
905 if (!tab.isPrivateBrowsingEnabled()) {
John Reckf57c0292011-07-21 18:15:39 -0700906 DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700907 }
908 }
909
910 @Override
911 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800912 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700913 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
914 }
915
916 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800917 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
918 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700919 }
920
921 @Override
922 public boolean shouldOverrideKeyEvent(KeyEvent event) {
923 if (mMenuIsDown) {
924 // only check shortcut key when MENU is held
925 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
926 event);
927 } else {
928 return false;
929 }
930 }
931
932 @Override
933 public void onUnhandledKeyEvent(KeyEvent event) {
934 if (!isActivityPaused()) {
935 if (event.getAction() == KeyEvent.ACTION_DOWN) {
936 mActivity.onKeyDown(event.getKeyCode(), event);
937 } else {
938 mActivity.onKeyUp(event.getKeyCode(), event);
939 }
940 }
941 }
942
943 @Override
John Reck324d4402011-01-11 16:56:42 -0800944 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700945 // Don't save anything in private browsing mode
946 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800947 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700948
John Reck324d4402011-01-11 16:56:42 -0800949 if (TextUtils.isEmpty(url)
950 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700951 return;
952 }
John Reckf57c0292011-07-21 18:15:39 -0700953 DataController.getInstance(mActivity).updateVisitedHistory(url);
John Reck6c2e2f32011-08-22 13:41:23 -0700954 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -0700955 }
956
957 @Override
958 public void getVisitedHistory(final ValueCallback<String[]> callback) {
959 AsyncTask<Void, Void, String[]> task =
960 new AsyncTask<Void, Void, String[]>() {
961 @Override
962 public String[] doInBackground(Void... unused) {
963 return Browser.getVisitedHistory(mActivity.getContentResolver());
964 }
965 @Override
966 public void onPostExecute(String[] result) {
967 callback.onReceiveValue(result);
968 }
969 };
970 task.execute();
971 }
972
973 @Override
974 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
975 final HttpAuthHandler handler, final String host,
976 final String realm) {
977 String username = null;
978 String password = null;
979
980 boolean reuseHttpAuthUsernamePassword
981 = handler.useHttpAuthUsernamePassword();
982
983 if (reuseHttpAuthUsernamePassword && view != null) {
984 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
985 if (credentials != null && credentials.length == 2) {
986 username = credentials[0];
987 password = credentials[1];
988 }
989 }
990
991 if (username != null && password != null) {
992 handler.proceed(username, password);
993 } else {
Ben Murdochfdd37112011-08-05 15:48:14 +0100994 if (tab.inForeground() && !handler.suppressDialog()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700995 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
996 } else {
997 handler.cancel();
998 }
999 }
1000 }
1001
1002 @Override
1003 public void onDownloadStart(Tab tab, String url, String userAgent,
1004 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001005 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -05001006 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001007 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
1008 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001009 // This Tab was opened for the sole purpose of downloading a
1010 // file. Remove it.
1011 if (tab == mTabControl.getCurrentTab()) {
1012 // In this case, the Tab is still on top.
1013 goBackOnePageOrQuit();
1014 } else {
1015 // In this case, it is not.
1016 closeTab(tab);
1017 }
1018 }
1019 }
1020
1021 @Override
1022 public Bitmap getDefaultVideoPoster() {
1023 return mUi.getDefaultVideoPoster();
1024 }
1025
1026 @Override
1027 public View getVideoLoadingProgressView() {
1028 return mUi.getVideoLoadingProgressView();
1029 }
1030
1031 @Override
1032 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1033 SslError error) {
1034 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1035 }
1036
Patrick Scott92066772011-03-10 08:46:27 -05001037 @Override
1038 public void showAutoLogin(Tab tab) {
1039 assert tab.inForeground();
1040 // Update the title bar to show the auto-login request.
1041 mUi.showAutoLogin(tab);
1042 }
1043
1044 @Override
1045 public void hideAutoLogin(Tab tab) {
1046 assert tab.inForeground();
1047 mUi.hideAutoLogin(tab);
1048 }
1049
Michael Kolb8233fac2010-10-26 16:08:53 -07001050 // helper method
1051
1052 /*
1053 * Update the favorites icon if the private browsing isn't enabled and the
1054 * icon is valid.
1055 */
1056 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1057 final String url, Bitmap favicon) {
1058 if (favicon == null) {
1059 return;
1060 }
1061 if (!tab.isPrivateBrowsingEnabled()) {
1062 Bookmarks.updateFavicon(mActivity
1063 .getContentResolver(), originalUrl, url, favicon);
1064 }
1065 }
1066
Leon Scroggins4cd97792010-12-03 15:31:56 -05001067 @Override
1068 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001069 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001070 mUi.bookmarkedStatusHasChanged(tab);
1071 }
1072
Michael Kolb8233fac2010-10-26 16:08:53 -07001073 // end WebViewController
1074
1075 protected void pageUp() {
1076 getCurrentTopWebView().pageUp(false);
1077 }
1078
1079 protected void pageDown() {
1080 getCurrentTopWebView().pageDown(false);
1081 }
1082
1083 // callback from phone title bar
1084 public void editUrl() {
1085 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001086 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001087 }
1088
Michael Kolbcfa3af52010-12-14 10:36:11 -08001089 public void startVoiceSearch() {
1090 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1091 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1092 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1093 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1094 mActivity.getComponentName().flattenToString());
1095 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001096 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001097 mActivity.startActivity(intent);
1098 }
1099
Michael Kolb11d19782011-03-20 10:17:40 -07001100 @Override
1101 public void activateVoiceSearchMode(String title, List<String> results) {
1102 mUi.showVoiceTitleBar(title, results);
Michael Kolb8233fac2010-10-26 16:08:53 -07001103 }
1104
1105 public void revertVoiceSearchMode(Tab tab) {
1106 mUi.revertVoiceTitleBar(tab);
1107 }
1108
Michael Kolb736990c2011-03-20 10:01:20 -07001109 public boolean supportsVoiceSearch() {
John Reck35e9dd62011-04-25 09:01:54 -07001110 SearchEngine searchEngine = getSettings().getSearchEngine();
Michael Kolb736990c2011-03-20 10:01:20 -07001111 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1112 }
1113
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001114 public void showCustomView(Tab tab, View view, int requestedOrientation,
Michael Kolb8233fac2010-10-26 16:08:53 -07001115 WebChromeClient.CustomViewCallback callback) {
1116 if (tab.inForeground()) {
1117 if (mUi.isCustomViewShowing()) {
1118 callback.onCustomViewHidden();
1119 return;
1120 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001121 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001122 // Save the menu state and set it to empty while the custom
1123 // view is showing.
1124 mOldMenuState = mMenuState;
1125 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001126 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001127 }
1128 }
1129
1130 @Override
1131 public void hideCustomView() {
1132 if (mUi.isCustomViewShowing()) {
1133 mUi.onHideCustomView();
1134 // Reset the old menu state.
1135 mMenuState = mOldMenuState;
1136 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001137 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001138 }
1139 }
1140
1141 protected void onActivityResult(int requestCode, int resultCode,
1142 Intent intent) {
1143 if (getCurrentTopWebView() == null) return;
1144 switch (requestCode) {
1145 case PREFERENCES_PAGE:
1146 if (resultCode == Activity.RESULT_OK && intent != null) {
1147 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001148 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001149 mTabControl.removeParentChildRelationShips();
1150 }
1151 }
1152 break;
1153 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001154 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001155 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001156 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001157 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001158 case AUTOFILL_SETUP:
1159 // Determine whether a profile was actually set up or not
1160 // and if so, send the message back to the WebTextView to
1161 // fill the form with the new profile.
1162 if (getSettings().getAutoFillProfile() != null) {
1163 mAutoFillSetupMessage.sendToTarget();
1164 mAutoFillSetupMessage = null;
1165 }
1166 break;
John Reckd3e4d5b2011-07-13 15:48:43 -07001167 case COMBO_VIEW:
1168 if (intent == null || resultCode != Activity.RESULT_OK) {
1169 break;
1170 }
John Reck3ba45532011-08-11 16:26:53 -07001171 mUi.showWeb(false);
John Reckd3e4d5b2011-07-13 15:48:43 -07001172 if (Intent.ACTION_VIEW.equals(intent.getAction())) {
1173 Tab t = getCurrentTab();
1174 Uri uri = intent.getData();
1175 loadUrl(t, uri.toString());
1176 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
1177 String[] urls = intent.getStringArrayExtra(
1178 ComboViewActivity.EXTRA_OPEN_ALL);
1179 Tab parent = getCurrentTab();
1180 for (String url : urls) {
1181 parent = openTab(url, parent,
1182 !mSettings.openInBackground(), true);
1183 }
1184 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
1185 long id = intent.getLongExtra(
1186 ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
1187 if (id >= 0) {
1188 createNewSnapshotTab(id, true);
1189 }
1190 }
1191 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001192 default:
1193 break;
1194 }
1195 getCurrentTopWebView().requestFocus();
1196 }
1197
1198 /**
1199 * Open the Go page.
1200 * @param startWithHistory If true, open starting on the history tab.
1201 * Otherwise, start with the bookmarks tab.
1202 */
1203 @Override
1204 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1205 if (mTabControl.getCurrentWebView() == null) {
1206 return;
1207 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001208 // clear action mode
1209 if (isInCustomActionMode()) {
1210 endActionMode();
1211 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001212 Bundle extras = new Bundle();
1213 // Disable opening in a new window if we have maxed out the windows
1214 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1215 !mTabControl.canCreateNewTab());
John Reck2bc80422011-06-30 15:11:49 -07001216 mUi.showComboView(startWithHistory
1217 ? ComboViews.History : ComboViews.Bookmarks, extras);
Michael Kolb8233fac2010-10-26 16:08:53 -07001218 }
1219
1220 // combo view callbacks
1221
Michael Kolb8233fac2010-10-26 16:08:53 -07001222 // key handling
1223 protected void onBackKey() {
1224 if (!mUi.onBackKey()) {
1225 WebView subwindow = mTabControl.getCurrentSubWindow();
1226 if (subwindow != null) {
1227 if (subwindow.canGoBack()) {
1228 subwindow.goBack();
1229 } else {
1230 dismissSubWindow(mTabControl.getCurrentTab());
1231 }
1232 } else {
1233 goBackOnePageOrQuit();
1234 }
1235 }
1236 }
1237
Michael Kolb4bd767d2011-05-27 11:33:55 -07001238 protected boolean onMenuKey() {
1239 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001240 }
1241
Michael Kolb8233fac2010-10-26 16:08:53 -07001242 // menu handling and state
1243 // TODO: maybe put into separate handler
1244
1245 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckd73c5a22010-12-22 10:22:50 -08001246 if (mMenuState == EMPTY_MENU) {
1247 return false;
1248 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001249 MenuInflater inflater = mActivity.getMenuInflater();
1250 inflater.inflate(R.menu.browser, menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001251 return true;
1252 }
1253
1254 protected void onCreateContextMenu(ContextMenu menu, View v,
1255 ContextMenuInfo menuInfo) {
John Reck0f602f32011-07-07 15:38:43 -07001256 if (v instanceof TitleBar) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001257 return;
1258 }
1259 if (!(v instanceof WebView)) {
1260 return;
1261 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001262 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001263 WebView.HitTestResult result = webview.getHitTestResult();
1264 if (result == null) {
1265 return;
1266 }
1267
1268 int type = result.getType();
1269 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1270 Log.w(LOGTAG,
1271 "We should not show context menu when nothing is touched");
1272 return;
1273 }
1274 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1275 // let TextView handles context menu
1276 return;
1277 }
1278
1279 // Note, http://b/issue?id=1106666 is requesting that
1280 // an inflated menu can be used again. This is not available
1281 // yet, so inflate each time (yuk!)
1282 MenuInflater inflater = mActivity.getMenuInflater();
1283 inflater.inflate(R.menu.browsercontext, menu);
1284
1285 // Show the correct menu group
1286 final String extra = result.getExtra();
1287 menu.setGroupVisible(R.id.PHONE_MENU,
1288 type == WebView.HitTestResult.PHONE_TYPE);
1289 menu.setGroupVisible(R.id.EMAIL_MENU,
1290 type == WebView.HitTestResult.EMAIL_TYPE);
1291 menu.setGroupVisible(R.id.GEO_MENU,
1292 type == WebView.HitTestResult.GEO_TYPE);
1293 menu.setGroupVisible(R.id.IMAGE_MENU,
1294 type == WebView.HitTestResult.IMAGE_TYPE
1295 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1296 menu.setGroupVisible(R.id.ANCHOR_MENU,
1297 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1298 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001299 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1300 || type == WebView.HitTestResult.PHONE_TYPE
1301 || type == WebView.HitTestResult.EMAIL_TYPE
1302 || type == WebView.HitTestResult.GEO_TYPE;
1303 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1304 if (hitText) {
1305 menu.findItem(R.id.select_text_menu_id)
1306 .setOnMenuItemClickListener(new SelectText(webview));
1307 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001308 // Setup custom handling depending on the type
1309 switch (type) {
1310 case WebView.HitTestResult.PHONE_TYPE:
1311 menu.setHeaderTitle(Uri.decode(extra));
1312 menu.findItem(R.id.dial_context_menu_id).setIntent(
1313 new Intent(Intent.ACTION_VIEW, Uri
1314 .parse(WebView.SCHEME_TEL + extra)));
1315 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1316 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1317 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1318 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1319 addIntent);
1320 menu.findItem(R.id.copy_phone_context_menu_id)
1321 .setOnMenuItemClickListener(
1322 new Copy(extra));
1323 break;
1324
1325 case WebView.HitTestResult.EMAIL_TYPE:
1326 menu.setHeaderTitle(extra);
1327 menu.findItem(R.id.email_context_menu_id).setIntent(
1328 new Intent(Intent.ACTION_VIEW, Uri
1329 .parse(WebView.SCHEME_MAILTO + extra)));
1330 menu.findItem(R.id.copy_mail_context_menu_id)
1331 .setOnMenuItemClickListener(
1332 new Copy(extra));
1333 break;
1334
1335 case WebView.HitTestResult.GEO_TYPE:
1336 menu.setHeaderTitle(extra);
1337 menu.findItem(R.id.map_context_menu_id).setIntent(
1338 new Intent(Intent.ACTION_VIEW, Uri
1339 .parse(WebView.SCHEME_GEO
1340 + URLEncoder.encode(extra))));
1341 menu.findItem(R.id.copy_geo_context_menu_id)
1342 .setOnMenuItemClickListener(
1343 new Copy(extra));
1344 break;
1345
1346 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1347 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001348 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001349 // decide whether to show the open link in new tab option
1350 boolean showNewTab = mTabControl.canCreateNewTab();
1351 MenuItem newTabItem
1352 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001353 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001354 ? R.string.contextmenu_openlink_newwindow_background
1355 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001356 newTabItem.setVisible(showNewTab);
1357 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001358 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1359 newTabItem.setOnMenuItemClickListener(
1360 new MenuItem.OnMenuItemClickListener() {
1361 @Override
1362 public boolean onMenuItemClick(MenuItem item) {
1363 final HashMap<String, WebView> hrefMap =
1364 new HashMap<String, WebView>();
1365 hrefMap.put("webview", webview);
1366 final Message msg = mHandler.obtainMessage(
1367 FOCUS_NODE_HREF,
1368 R.id.open_newtab_context_menu_id,
1369 0, hrefMap);
1370 webview.requestFocusNodeHref(msg);
1371 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001372 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001373 });
1374 } else {
1375 newTabItem.setOnMenuItemClickListener(
1376 new MenuItem.OnMenuItemClickListener() {
1377 @Override
1378 public boolean onMenuItemClick(MenuItem item) {
1379 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001380 openTab(extra, parent,
1381 !mSettings.openInBackground(),
1382 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001383 return true;
1384 }
1385 });
1386 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001387 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001388 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1389 break;
1390 }
1391 // otherwise fall through to handle image part
1392 case WebView.HitTestResult.IMAGE_TYPE:
1393 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1394 menu.setHeaderTitle(extra);
1395 }
1396 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1397 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1398 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001399 setOnMenuItemClickListener(
1400 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001401 menu.findItem(R.id.set_wallpaper_context_menu_id).
1402 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1403 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001404 break;
1405
1406 default:
1407 Log.w(LOGTAG, "We should not get here.");
1408 break;
1409 }
1410 //update the ui
1411 mUi.onContextMenuCreated(menu);
1412 }
1413
1414 /**
1415 * As the menu can be open when loading state changes
1416 * we must manually update the state of the stop/reload menu
1417 * item
1418 */
1419 private void updateInLoadMenuItems(Menu menu) {
1420 if (menu == null) {
1421 return;
1422 }
1423 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1424 MenuItem src = mInLoad ?
1425 menu.findItem(R.id.stop_menu_id):
1426 menu.findItem(R.id.reload_menu_id);
1427 if (src != null) {
1428 dest.setIcon(src.getIcon());
1429 dest.setTitle(src.getTitle());
1430 }
1431 }
1432
John Reckb3417f02011-01-14 11:01:05 -08001433 boolean onPrepareOptionsMenu(Menu menu) {
John Recke1a03a32011-09-14 17:04:16 -07001434 updateInLoadMenuItems(menu);
1435 // hold on to the menu reference here; it is used by the page callbacks
1436 // to update the menu based on loading state
1437 mCachedMenu = menu;
Michael Kolb8233fac2010-10-26 16:08:53 -07001438 // Note: setVisible will decide whether an item is visible; while
1439 // setEnabled() will decide whether an item is enabled, which also means
1440 // whether the matching shortcut key will function.
1441 switch (mMenuState) {
1442 case EMPTY_MENU:
1443 if (mCurrentMenuState != mMenuState) {
1444 menu.setGroupVisible(R.id.MAIN_MENU, false);
1445 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1446 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1447 }
1448 break;
1449 default:
1450 if (mCurrentMenuState != mMenuState) {
1451 menu.setGroupVisible(R.id.MAIN_MENU, true);
1452 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1453 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1454 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001455 updateMenuState(getCurrentTab(), menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001456 break;
1457 }
1458 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001459 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001460 }
1461
Michael Kolb4bf79712011-07-14 14:18:12 -07001462 @Override
1463 public void updateMenuState(Tab tab, Menu menu) {
1464 boolean canGoBack = false;
1465 boolean canGoForward = false;
1466 boolean isHome = false;
John Reck42229bc2011-08-19 13:26:43 -07001467 boolean isDesktopUa = false;
John Recke1a03a32011-09-14 17:04:16 -07001468 boolean isLive = false;
Michael Kolb4bf79712011-07-14 14:18:12 -07001469 if (tab != null) {
1470 canGoBack = tab.canGoBack();
1471 canGoForward = tab.canGoForward();
1472 isHome = mSettings.getHomePage().equals(tab.getUrl());
John Reck42229bc2011-08-19 13:26:43 -07001473 isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
John Recke1a03a32011-09-14 17:04:16 -07001474 isLive = !tab.isSnapshot();
Michael Kolb4bf79712011-07-14 14:18:12 -07001475 }
1476 final MenuItem back = menu.findItem(R.id.back_menu_id);
1477 back.setEnabled(canGoBack);
1478
1479 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1480 home.setEnabled(!isHome);
1481
1482 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1483 forward.setEnabled(canGoForward);
1484
1485 final MenuItem source = menu.findItem(mInLoad ? R.id.stop_menu_id : R.id.reload_menu_id);
1486 final MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolb7ab75ee2011-07-14 16:36:38 -07001487 if (source != null && dest != null) {
1488 dest.setTitle(source.getTitle());
1489 dest.setIcon(source.getIcon());
1490 }
John Recke1a03a32011-09-14 17:04:16 -07001491 menu.setGroupVisible(R.id.NAV_MENU, isLive);
Michael Kolb4bf79712011-07-14 14:18:12 -07001492
1493 // decide whether to show the share link option
1494 PackageManager pm = mActivity.getPackageManager();
1495 Intent send = new Intent(Intent.ACTION_SEND);
1496 send.setType("text/plain");
1497 ResolveInfo ri = pm.resolveActivity(send,
1498 PackageManager.MATCH_DEFAULT_ONLY);
1499 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1500
1501 boolean isNavDump = mSettings.enableNavDump();
1502 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1503 nav.setVisible(isNavDump);
1504 nav.setEnabled(isNavDump);
1505
1506 boolean showDebugSettings = mSettings.isDebugEnabled();
1507 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1508 counter.setVisible(showDebugSettings);
1509 counter.setEnabled(showDebugSettings);
John Reck42229bc2011-08-19 13:26:43 -07001510 final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
1511 uaSwitcher.setChecked(isDesktopUa);
John Recke1a03a32011-09-14 17:04:16 -07001512 menu.setGroupVisible(R.id.LIVE_MENU, isLive);
1513 menu.setGroupVisible(R.id.SNAPSHOT_MENU, !isLive);
Michael Kolb4bf79712011-07-14 14:18:12 -07001514
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001515 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001516 }
1517
Michael Kolb8233fac2010-10-26 16:08:53 -07001518 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001519 if (null == getCurrentTopWebView()) {
1520 return false;
1521 }
1522 if (mMenuIsDown) {
1523 // The shortcut action consumes the MENU. Even if it is still down,
1524 // it won't trigger the next shortcut action. In the case of the
1525 // shortcut action triggering a new activity, like Bookmarks, we
1526 // won't get onKeyUp for MENU. So it is important to reset it here.
1527 mMenuIsDown = false;
1528 }
Michael Kolb3ca12752011-07-20 13:52:25 -07001529 if (mUi.onOptionsItemSelected(item)) {
1530 // ui callback handled it
1531 return true;
1532 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001533 switch (item.getItemId()) {
1534 // -- Main menu
1535 case R.id.new_tab_menu_id:
1536 openTabToHomePage();
1537 break;
1538
1539 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001540 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001541 break;
1542
1543 case R.id.goto_menu_id:
1544 editUrl();
1545 break;
1546
1547 case R.id.bookmarks_menu_id:
1548 bookmarksOrHistoryPicker(false);
1549 break;
1550
Michael Kolb8233fac2010-10-26 16:08:53 -07001551 case R.id.add_bookmark_menu_id:
John Recka60fffa2011-09-06 16:30:29 -07001552 Intent bookmarkIntent = createBookmarkCurrentPageIntent(false);
1553 if (bookmarkIntent != null) {
1554 mActivity.startActivity(bookmarkIntent);
1555 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001556 break;
1557
1558 case R.id.stop_reload_menu_id:
1559 if (mInLoad) {
1560 stopLoading();
1561 } else {
1562 getCurrentTopWebView().reload();
1563 }
1564 break;
1565
1566 case R.id.back_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001567 getCurrentTab().goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07001568 break;
1569
1570 case R.id.forward_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001571 getCurrentTab().goForward();
Michael Kolb8233fac2010-10-26 16:08:53 -07001572 break;
1573
1574 case R.id.close_menu_id:
1575 // Close the subwindow if it exists.
1576 if (mTabControl.getCurrentSubWindow() != null) {
1577 dismissSubWindow(mTabControl.getCurrentTab());
1578 break;
1579 }
1580 closeCurrentTab();
1581 break;
1582
1583 case R.id.homepage_menu_id:
1584 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07001585 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07001586 break;
1587
1588 case R.id.preferences_menu_id:
1589 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1590 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1591 getCurrentTopWebView().getUrl());
1592 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1593 break;
1594
1595 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001596 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001597 break;
1598
John Reck2bc80422011-06-30 15:11:49 -07001599 case R.id.save_snapshot_menu_id:
1600 final Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07001601 if (source == null) break;
John Reckd8c74522011-06-14 08:45:00 -07001602 final ContentResolver cr = mActivity.getContentResolver();
1603 final ContentValues values = source.createSnapshotValues();
John Reck2bc80422011-06-30 15:11:49 -07001604 if (values != null) {
1605 new AsyncTask<Tab, Void, Long>() {
John Reckd8c74522011-06-14 08:45:00 -07001606
John Reck2bc80422011-06-30 15:11:49 -07001607 @Override
1608 protected Long doInBackground(Tab... params) {
1609 Uri result = cr.insert(Snapshots.CONTENT_URI, values);
1610 long id = ContentUris.parseId(result);
1611 return id;
John Reckd8c74522011-06-14 08:45:00 -07001612 }
John Reckf33b1632011-06-04 20:00:23 -07001613
John Reck2bc80422011-06-30 15:11:49 -07001614 @Override
1615 protected void onPostExecute(Long id) {
1616 Bundle b = new Bundle();
1617 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
1618 mUi.showComboView(ComboViews.Snapshots, b);
1619 };
1620 }.execute(source);
1621 } else {
1622 Toast.makeText(mActivity, R.string.snapshot_failed,
Leon Scrogginsac993842011-02-02 12:54:07 -05001623 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001624 }
Leon Scrogginsac993842011-02-02 12:54:07 -05001625 break;
1626
Michael Kolb8233fac2010-10-26 16:08:53 -07001627 case R.id.page_info_menu_id:
Huahui Wuae0c0412011-06-28 10:17:05 -07001628 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001629 break;
1630
John Recke1a03a32011-09-14 17:04:16 -07001631 case R.id.snapshot_go_live:
1632 goLive();
1633 return true;
1634
Michael Kolb8233fac2010-10-26 16:08:53 -07001635 case R.id.classic_history_menu_id:
1636 bookmarksOrHistoryPicker(true);
1637 break;
1638
Michael Kolb8233fac2010-10-26 16:08:53 -07001639 case R.id.share_page_menu_id:
1640 Tab currentTab = mTabControl.getCurrentTab();
1641 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001642 return false;
1643 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001644 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001645 break;
1646
1647 case R.id.dump_nav_menu_id:
1648 getCurrentTopWebView().debugDump();
1649 break;
1650
1651 case R.id.dump_counters_menu_id:
1652 getCurrentTopWebView().dumpV8Counters();
1653 break;
1654
1655 case R.id.zoom_in_menu_id:
1656 getCurrentTopWebView().zoomIn();
1657 break;
1658
1659 case R.id.zoom_out_menu_id:
1660 getCurrentTopWebView().zoomOut();
1661 break;
1662
1663 case R.id.view_downloads_menu_id:
1664 viewDownloads();
1665 break;
1666
John Reck42229bc2011-08-19 13:26:43 -07001667 case R.id.ua_desktop_menu_id:
1668 WebView web = getCurrentWebView();
1669 mSettings.toggleDesktopUseragent(web);
1670 web.loadUrl(web.getOriginalUrl());
1671 break;
1672
Michael Kolb8233fac2010-10-26 16:08:53 -07001673 case R.id.window_one_menu_id:
1674 case R.id.window_two_menu_id:
1675 case R.id.window_three_menu_id:
1676 case R.id.window_four_menu_id:
1677 case R.id.window_five_menu_id:
1678 case R.id.window_six_menu_id:
1679 case R.id.window_seven_menu_id:
1680 case R.id.window_eight_menu_id:
1681 {
1682 int menuid = item.getItemId();
1683 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1684 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1685 Tab desiredTab = mTabControl.getTab(id);
1686 if (desiredTab != null &&
1687 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001688 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001689 }
1690 break;
1691 }
1692 }
1693 }
1694 break;
1695
1696 default:
1697 return false;
1698 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001699 return true;
1700 }
1701
John Recke1a03a32011-09-14 17:04:16 -07001702 private void goLive() {
1703 Tab t = getCurrentTab();
1704 t.loadUrl(t.getUrl(), null);
1705 }
1706
Michael Kolb8233fac2010-10-26 16:08:53 -07001707 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001708 // Let the History and Bookmark fragments handle menus they created.
1709 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1710 return false;
1711 }
1712
Michael Kolb8233fac2010-10-26 16:08:53 -07001713 int id = item.getItemId();
1714 boolean result = true;
1715 switch (id) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001716 // -- Browser context menu
1717 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001718 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001719 case R.id.copy_link_context_menu_id:
1720 final WebView webView = getCurrentTopWebView();
1721 if (null == webView) {
1722 result = false;
1723 break;
1724 }
1725 final HashMap<String, WebView> hrefMap =
1726 new HashMap<String, WebView>();
1727 hrefMap.put("webview", webView);
1728 final Message msg = mHandler.obtainMessage(
1729 FOCUS_NODE_HREF, id, 0, hrefMap);
1730 webView.requestFocusNodeHref(msg);
1731 break;
1732
1733 default:
1734 // For other context menus
1735 result = onOptionsItemSelected(item);
1736 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001737 return result;
1738 }
1739
1740 /**
1741 * support programmatically opening the context menu
1742 */
1743 public void openContextMenu(View view) {
1744 mActivity.openContextMenu(view);
1745 }
1746
1747 /**
1748 * programmatically open the options menu
1749 */
1750 public void openOptionsMenu() {
1751 mActivity.openOptionsMenu();
1752 }
1753
1754 public boolean onMenuOpened(int featureId, Menu menu) {
1755 if (mOptionsMenuOpen) {
1756 if (mConfigChanged) {
1757 // We do not need to make any changes to the state of the
1758 // title bar, since the only thing that happened was a
1759 // change in orientation
1760 mConfigChanged = false;
1761 } else {
1762 if (!mExtendedMenuOpen) {
1763 mExtendedMenuOpen = true;
1764 mUi.onExtendedMenuOpened();
1765 } else {
1766 // Switching the menu back to icon view, so show the
1767 // title bar once again.
1768 mExtendedMenuOpen = false;
1769 mUi.onExtendedMenuClosed(mInLoad);
Michael Kolb8233fac2010-10-26 16:08:53 -07001770 }
1771 }
1772 } else {
1773 // The options menu is closed, so open it, and show the title
1774 mOptionsMenuOpen = true;
1775 mConfigChanged = false;
1776 mExtendedMenuOpen = false;
1777 mUi.onOptionsMenuOpened();
1778 }
1779 return true;
1780 }
1781
1782 public void onOptionsMenuClosed(Menu menu) {
1783 mOptionsMenuOpen = false;
1784 mUi.onOptionsMenuClosed(mInLoad);
1785 }
1786
1787 public void onContextMenuClosed(Menu menu) {
1788 mUi.onContextMenuClosed(menu, mInLoad);
1789 }
1790
1791 // Helper method for getting the top window.
1792 @Override
1793 public WebView getCurrentTopWebView() {
1794 return mTabControl.getCurrentTopWebView();
1795 }
1796
1797 @Override
1798 public WebView getCurrentWebView() {
1799 return mTabControl.getCurrentWebView();
1800 }
1801
1802 /*
1803 * This method is called as a result of the user selecting the options
1804 * menu to see the download window. It shows the download window on top of
1805 * the current window.
1806 */
1807 void viewDownloads() {
1808 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1809 mActivity.startActivity(intent);
1810 }
1811
John Reck30b065e2011-07-19 10:58:05 -07001812 int getActionModeHeight() {
1813 TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
1814 new int[] { android.R.attr.actionBarSize });
1815 int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
1816 actionBarSizeTypedArray.recycle();
1817 return size;
1818 }
1819
Michael Kolb8233fac2010-10-26 16:08:53 -07001820 // action mode
1821
1822 void onActionModeStarted(ActionMode mode) {
1823 mUi.onActionModeStarted(mode);
1824 mActionMode = mode;
Michael Kolb42c0c062011-08-02 12:56:06 -07001825 if (mSimulateActionBarOverlayMode && !mUi.isEditingUrl()) {
John Reck30b065e2011-07-19 10:58:05 -07001826 WebView web = getCurrentWebView();
1827 // Simulate overlay mode by scrolling the webview the amount it will be
1828 // pushed down. Actual overlay mode doesn't work for us as otherwise
1829 // the CAB will, well, overlay the content, which breaks things like
1830 // find on page.
1831 int scrollBy = getActionModeHeight();
1832 web.scrollBy(0, scrollBy);
1833 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001834 }
1835
1836 /*
1837 * True if a custom ActionMode (i.e. find or select) is in use.
1838 */
1839 @Override
1840 public boolean isInCustomActionMode() {
1841 return mActionMode != null;
1842 }
1843
1844 /*
1845 * End the current ActionMode.
1846 */
1847 @Override
1848 public void endActionMode() {
1849 if (mActionMode != null) {
1850 mActionMode.finish();
1851 }
1852 }
1853
1854 /*
1855 * Called by find and select when they are finished. Replace title bars
1856 * as necessary.
1857 */
1858 public void onActionModeFinished(ActionMode mode) {
1859 if (!isInCustomActionMode()) return;
1860 mUi.onActionModeFinished(mInLoad);
1861 mActionMode = null;
John Reck30b065e2011-07-19 10:58:05 -07001862 if (mSimulateActionBarOverlayMode) {
1863 WebView web = getCurrentWebView();
1864 int scrollBy = getActionModeHeight();
1865 web.scrollBy(0, -scrollBy);
1866 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001867 }
1868
1869 boolean isInLoad() {
1870 return mInLoad;
1871 }
1872
1873 // bookmark handling
1874
1875 /**
1876 * add the current page as a bookmark to the given folder id
1877 * @param folderId use -1 for the default folder
John Reckd3e4d5b2011-07-13 15:48:43 -07001878 * @param editExisting If true, check to see whether the site is already
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001879 * bookmarked, and if it is, edit that bookmark. If false, and
1880 * the site is already bookmarked, do not attempt to edit the
1881 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001882 */
1883 @Override
John Reckd3e4d5b2011-07-13 15:48:43 -07001884 public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
John Recka60fffa2011-09-06 16:30:29 -07001885 WebView w = getCurrentTopWebView();
1886 if (w == null) {
1887 return null;
1888 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001889 Intent i = new Intent(mActivity,
1890 AddBookmarkPage.class);
Michael Kolb8233fac2010-10-26 16:08:53 -07001891 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1892 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1893 String touchIconUrl = w.getTouchIconUrl();
1894 if (touchIconUrl != null) {
1895 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1896 WebSettings settings = w.getSettings();
1897 if (settings != null) {
1898 i.putExtra(AddBookmarkPage.USER_AGENT,
1899 settings.getUserAgentString());
1900 }
1901 }
1902 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1903 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1904 getDesiredThumbnailHeight(mActivity)));
1905 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07001906 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001907 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1908 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001909 // Put the dialog at the upper right of the screen, covering the
1910 // star on the title bar.
1911 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07001912 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07001913 }
1914
1915 // file chooser
1916 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1917 mUploadHandler = new UploadHandler(this);
1918 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1919 }
1920
1921 // thumbnails
1922
1923 /**
1924 * Return the desired width for thumbnail screenshots, which are stored in
1925 * the database, and used on the bookmarks screen.
1926 * @param context Context for finding out the density of the screen.
1927 * @return desired width for thumbnail screenshot.
1928 */
1929 static int getDesiredThumbnailWidth(Context context) {
1930 return context.getResources().getDimensionPixelOffset(
1931 R.dimen.bookmarkThumbnailWidth);
1932 }
1933
1934 /**
1935 * Return the desired height for thumbnail screenshots, which are stored in
1936 * the database, and used on the bookmarks screen.
1937 * @param context Context for finding out the density of the screen.
1938 * @return desired height for thumbnail screenshot.
1939 */
1940 static int getDesiredThumbnailHeight(Context context) {
1941 return context.getResources().getDimensionPixelOffset(
1942 R.dimen.bookmarkThumbnailHeight);
1943 }
1944
John Reck8cc92352011-07-06 17:41:52 -07001945 static Bitmap createScreenshot(WebView view, int width, int height) {
John Reckd7dd9b22011-08-30 09:18:29 -07001946 if (view == null || view.getContentHeight() == 0
1947 || view.getContentWidth() == 0) {
1948 return null;
1949 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001950 // We render to a bitmap 2x the desired size so that we can then
1951 // re-scale it with filtering since canvas.scale doesn't filter
1952 // This helps reduce aliasing at the cost of being slightly blurry
1953 final int filter_scale = 2;
John Reckd7dd9b22011-08-30 09:18:29 -07001954 int scaledWidth = width * filter_scale;
1955 int scaledHeight = height * filter_scale;
1956 if (sThumbnailBitmap == null || sThumbnailBitmap.getWidth() != scaledWidth
1957 || sThumbnailBitmap.getHeight() != scaledHeight) {
1958 if (sThumbnailBitmap != null) {
1959 sThumbnailBitmap.recycle();
1960 sThumbnailBitmap = null;
1961 }
1962 sThumbnailBitmap =
1963 Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.RGB_565);
Michael Kolb8233fac2010-10-26 16:08:53 -07001964 }
John Reckd7dd9b22011-08-30 09:18:29 -07001965 Canvas canvas = new Canvas(sThumbnailBitmap);
1966 int contentWidth = view.getContentWidth();
1967 float overviewScale = scaledWidth / (view.getScale() * contentWidth);
1968 if (view instanceof BrowserWebView) {
1969 int dy = -((BrowserWebView)view).getTitleHeight();
1970 canvas.translate(0, dy * overviewScale);
1971 }
1972
1973 canvas.scale(overviewScale, overviewScale);
1974
1975 if (view instanceof BrowserWebView) {
1976 ((BrowserWebView)view).drawContent(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07001977 } else {
John Reckd7dd9b22011-08-30 09:18:29 -07001978 view.draw(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07001979 }
John Reckd7dd9b22011-08-30 09:18:29 -07001980 Bitmap ret = Bitmap.createScaledBitmap(sThumbnailBitmap,
1981 width, height, true);
Dianne Hackborn43cfe8a2011-08-02 16:59:35 -07001982 canvas.setBitmap(null);
John Reck5c6ac2f2011-01-05 10:18:03 -08001983 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001984 }
1985
John Reck34ef2672011-02-10 11:30:55 -08001986 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001987 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07001988 // FIXME: Would like to make sure there is actually something to
1989 // draw, but the API for that (WebViewCore.pictureReady()) is not
1990 // currently accessible here.
1991
John Reck34ef2672011-02-10 11:30:55 -08001992 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08001993 if (view == null) {
1994 // Tab was destroyed
1995 return;
1996 }
John Reck34ef2672011-02-10 11:30:55 -08001997 final String url = tab.getUrl();
1998 final String originalUrl = view.getOriginalUrl();
1999
2000 if (TextUtils.isEmpty(url)) {
2001 return;
2002 }
2003
2004 // Only update thumbnails for web urls (http(s)://), not for
2005 // about:, javascript:, data:, etc...
2006 // Unless it is a bookmarked site, then always update
2007 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2008 return;
2009 }
2010
Michael Kolb8233fac2010-10-26 16:08:53 -07002011 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2012 getDesiredThumbnailHeight(mActivity));
2013 if (bm == null) {
2014 return;
2015 }
2016
2017 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002018 new AsyncTask<Void, Void, Void>() {
2019 @Override
2020 protected Void doInBackground(Void... unused) {
2021 Cursor cursor = null;
2022 try {
2023 // TODO: Clean this up
2024 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2025 if (cursor != null && cursor.moveToFirst()) {
2026 final ByteArrayOutputStream os =
2027 new ByteArrayOutputStream();
2028 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002029
John Reck34ef2672011-02-10 11:30:55 -08002030 ContentValues values = new ContentValues();
2031 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002032
John Reck34ef2672011-02-10 11:30:55 -08002033 do {
John Reck617fd832011-02-16 14:35:59 -08002034 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002035 cr.update(Images.CONTENT_URI, values, null, null);
2036 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002037 }
John Reck34ef2672011-02-10 11:30:55 -08002038 } catch (IllegalStateException e) {
2039 // Ignore
2040 } finally {
2041 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002042 }
John Reck34ef2672011-02-10 11:30:55 -08002043 return null;
2044 }
2045 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002046 }
2047
2048 private class Copy implements OnMenuItemClickListener {
2049 private CharSequence mText;
2050
2051 public boolean onMenuItemClick(MenuItem item) {
2052 copy(mText);
2053 return true;
2054 }
2055
2056 public Copy(CharSequence toCopy) {
2057 mText = toCopy;
2058 }
2059 }
2060
Leon Scroggins63c02662010-11-18 15:16:27 -05002061 private static class Download implements OnMenuItemClickListener {
2062 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002063 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002064 private boolean mPrivateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002065
2066 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002067 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002068 null, null, mPrivateBrowsing);
Michael Kolb8233fac2010-10-26 16:08:53 -07002069 return true;
2070 }
2071
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002072 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002073 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002074 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002075 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002076 }
2077 }
2078
Cary Clark8974d282010-11-22 10:46:05 -05002079 private static class SelectText implements OnMenuItemClickListener {
2080 private WebView mWebView;
2081
2082 public boolean onMenuItemClick(MenuItem item) {
2083 if (mWebView != null) {
2084 return mWebView.selectText();
2085 }
2086 return false;
2087 }
2088
2089 public SelectText(WebView webView) {
2090 mWebView = webView;
2091 }
2092
2093 }
2094
Michael Kolb8233fac2010-10-26 16:08:53 -07002095 /********************** TODO: UI stuff *****************************/
2096
2097 // these methods have been copied, they still need to be cleaned up
2098
2099 /****************** tabs ***************************************************/
2100
2101 // basic tab interactions:
2102
2103 // it is assumed that tabcontrol already knows about the tab
2104 protected void addTab(Tab tab) {
2105 mUi.addTab(tab);
2106 }
2107
2108 protected void removeTab(Tab tab) {
2109 mUi.removeTab(tab);
2110 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002111 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002112 }
2113
Michael Kolbf2055602011-04-09 17:20:03 -07002114 @Override
2115 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002116 // monkey protection against delayed start
2117 if (tab != null) {
2118 mTabControl.setCurrentTab(tab);
2119 // the tab is guaranteed to have a webview after setCurrentTab
2120 mUi.setActiveTab(tab);
2121 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002122 }
2123
John Reck8bcafc12011-08-29 16:43:02 -07002124 protected void closeEmptyTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002125 Tab current = mTabControl.getCurrentTab();
2126 if (current != null
2127 && current.getWebView().copyBackForwardList().getSize() == 0) {
John Reck8bcafc12011-08-29 16:43:02 -07002128 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002129 }
2130 }
2131
John Reck26b18322011-06-21 13:08:58 -07002132 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002133 // Dismiss the subwindow if applicable.
2134 dismissSubWindow(appTab);
2135 // Since we might kill the WebView, remove it from the
2136 // content view first.
2137 mUi.detachTab(appTab);
2138 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002139 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002140 // TODO: analyze why the remove and add are necessary
2141 mUi.attachTab(appTab);
2142 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002143 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002144 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002145 } else {
2146 // If the tab was the current tab, we have to attach
2147 // it to the view system again.
2148 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002149 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002150 }
2151 }
2152
2153 // Remove the sub window if it exists. Also called by TabControl when the
2154 // user clicks the 'X' to dismiss a sub window.
2155 public void dismissSubWindow(Tab tab) {
2156 removeSubWindow(tab);
2157 // dismiss the subwindow. This will destroy the WebView.
2158 tab.dismissSubWindow();
2159 getCurrentTopWebView().requestFocus();
2160 }
2161
2162 @Override
2163 public void removeSubWindow(Tab t) {
2164 if (t.getSubWebView() != null) {
2165 mUi.removeSubWindow(t.getSubViewContainer());
2166 }
2167 }
2168
2169 @Override
2170 public void attachSubWindow(Tab tab) {
2171 if (tab.getSubWebView() != null) {
2172 mUi.attachSubWindow(tab.getSubViewContainer());
2173 getCurrentTopWebView().requestFocus();
2174 }
2175 }
2176
Mathew Inwood29721c22011-06-29 17:55:24 +01002177 private Tab showPreloadedTab(final UrlData urlData) {
2178 if (!urlData.isPreloaded()) {
2179 return null;
2180 }
2181 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2182 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2183 if (sbQuery != null) {
Mathew Inwoodb4e831b2011-09-05 18:58:48 +01002184 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders,
2185 urlData.getOnLoadCompletePendingIntent())) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002186 // Could not submit query. Fallback to regular tab creation
2187 tabControl.destroy();
2188 return null;
2189 }
2190 }
Michael Kolbff6a7482011-07-26 16:37:15 -07002191 // check tab count and make room for new tab
2192 if (!mTabControl.canCreateNewTab()) {
2193 Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
2194 if (leastUsed != null) {
2195 closeTab(leastUsed);
2196 }
2197 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002198 Tab t = tabControl.getTab();
Mathew Inwoode09305e2011-09-02 12:03:26 +01002199 t.refreshIdAfterPreload();
Mathew Inwood29721c22011-06-29 17:55:24 +01002200 mTabControl.addPreloadedTab(t);
2201 addTab(t);
2202 setActiveTab(t);
Mathew Inwoodb4e831b2011-09-05 18:58:48 +01002203 if (sbQuery == null) {
2204 // if the searchbox query is set, the load complete notification is handled within
2205 // the preloaded tab controller.
2206 if (t.inPageLoad()) {
2207 requestLoadCompleteNotification(urlData.mOnLoadCompletePendingIntent, t,
2208 urlData.mUrl, true, true);
2209 } else {
2210 // the page is already fully loaded
2211 IntentHandler.sendPageLoadCompletePendingIntent(mActivity,
2212 urlData.mOnLoadCompletePendingIntent, true, true);
2213 }
2214 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002215 return t;
2216 }
2217
Michael Kolb7bcafde2011-05-09 13:55:59 -07002218 // open a non inconito tab with the given url data
2219 // and set as active tab
2220 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002221 Tab tab = showPreloadedTab(urlData);
2222 if (tab == null) {
2223 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002224 if ((tab != null) && !urlData.isEmpty()) {
2225 loadUrlDataIn(tab, urlData);
2226 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002227 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002228 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002229 }
2230
Michael Kolb843510f2010-12-09 10:51:49 -08002231 @Override
2232 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002233 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002234 }
2235
Michael Kolb8233fac2010-10-26 16:08:53 -07002236 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002237 public Tab openIncognitoTab() {
2238 return openTab(INCOGNITO_URI, true, true, false);
2239 }
2240
2241 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002242 public Tab openTab(String url, boolean incognito, boolean setActive,
2243 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002244 return openTab(url, incognito, setActive, useCurrent, null);
2245 }
2246
2247 @Override
2248 public Tab openTab(String url, Tab parent, boolean setActive,
2249 boolean useCurrent) {
2250 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2251 setActive, useCurrent, parent);
2252 }
2253
2254 public Tab openTab(String url, boolean incognito, boolean setActive,
2255 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002256 Tab tab = createNewTab(incognito, setActive, useCurrent);
2257 if (tab != null) {
John Reck5949c662011-05-27 09:52:29 -07002258 if (parent != null && parent != tab) {
2259 parent.addChildTab(tab);
2260 }
Michael Kolb519d2282011-05-09 17:03:19 -07002261 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002262 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002263 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002264 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002265 return tab;
2266 }
2267
2268 // this method will attempt to create a new tab
2269 // incognito: private browsing tab
2270 // setActive: ste tab as current tab
2271 // useCurrent: if no new tab can be created, return current tab
2272 private Tab createNewTab(boolean incognito, boolean setActive,
2273 boolean useCurrent) {
2274 Tab tab = null;
2275 if (mTabControl.canCreateNewTab()) {
2276 tab = mTabControl.createNewTab(incognito);
2277 addTab(tab);
2278 if (setActive) {
2279 setActiveTab(tab);
2280 }
2281 } else {
2282 if (useCurrent) {
2283 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002284 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002285 } else {
2286 mUi.showMaxTabsWarning();
2287 }
2288 }
2289 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002290 }
2291
John Reck2bc80422011-06-30 15:11:49 -07002292 @Override
2293 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2294 SnapshotTab tab = null;
2295 if (mTabControl.canCreateNewTab()) {
2296 tab = mTabControl.createSnapshotTab(snapshotId);
2297 addTab(tab);
2298 if (setActive) {
2299 setActiveTab(tab);
2300 }
2301 } else {
2302 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07002303 }
2304 return tab;
2305 }
2306
Michael Kolb8233fac2010-10-26 16:08:53 -07002307 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002308 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002309 * @return boolean True if we successfully switched to a different tab. If
2310 * the indexth tab is null, or if that tab is the same as
2311 * the current one, return false.
2312 */
2313 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002314 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002315 Tab currentTab = mTabControl.getCurrentTab();
2316 if (tab == null || tab == currentTab) {
2317 return false;
2318 }
2319 setActiveTab(tab);
2320 return true;
2321 }
2322
2323 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002324 public void closeCurrentTab() {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002325 closeCurrentTab(false);
2326 }
2327
2328 protected void closeCurrentTab(boolean andQuit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002329 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07002330 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07002331 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08002332 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002333 return;
2334 }
Michael Kolbc831b632011-05-11 09:30:34 -07002335 final Tab current = mTabControl.getCurrentTab();
2336 final int pos = mTabControl.getCurrentPosition();
2337 Tab newTab = current.getParent();
2338 if (newTab == null) {
2339 newTab = mTabControl.getTab(pos + 1);
2340 if (newTab == null) {
2341 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002342 }
2343 }
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002344 if (andQuit) {
2345 mTabControl.setCurrentTab(newTab);
2346 closeTab(current);
2347 } else if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002348 // Close window
2349 closeTab(current);
2350 }
2351 }
2352
2353 /**
2354 * Close the tab, remove its associated title bar, and adjust mTabControl's
2355 * current tab to a valid value.
2356 */
2357 @Override
2358 public void closeTab(Tab tab) {
Michael Kolb2d59c322011-01-25 13:18:55 -08002359 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002360 }
2361
Michael Kolb8233fac2010-10-26 16:08:53 -07002362 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07002363 protected void loadUrlFromContext(String url) {
2364 Tab tab = getCurrentTab();
2365 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002366 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07002367 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002368 url = UrlUtils.smartUrlFilter(url);
2369 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07002370 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07002371 }
2372 }
2373 }
2374
2375 /**
2376 * Load the URL into the given WebView and update the title bar
2377 * to reflect the new load. Call this instead of WebView.loadUrl
2378 * directly.
2379 * @param view The WebView used to load url.
2380 * @param url The URL to load.
2381 */
John Reck71e51422011-07-01 16:49:28 -07002382 @Override
2383 public void loadUrl(Tab tab, String url) {
John Reck26b18322011-06-21 13:08:58 -07002384 loadUrl(tab, url, null);
2385 }
2386
2387 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
2388 if (tab != null) {
2389 dismissSubWindow(tab);
2390 tab.loadUrl(url, headers);
2391 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002392 }
2393
2394 /**
2395 * Load UrlData into a Tab and update the title bar to reflect the new
2396 * load. Call this instead of UrlData.loadIn directly.
2397 * @param t The Tab used to load.
2398 * @param data The UrlData being loaded.
2399 */
2400 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07002401 if (data != null) {
2402 if (data.mVoiceIntent != null) {
2403 t.activateVoiceSearchMode(data.mVoiceIntent);
Michael Kolb14612442011-06-24 13:06:29 -07002404 } else if (data.isPreloaded()) {
2405 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07002406 } else {
2407 loadUrl(t, data.mUrl, data.mHeaders);
Mathew Inwoodb4e831b2011-09-05 18:58:48 +01002408 requestLoadCompleteNotification(data.mOnLoadCompletePendingIntent, t, data.mUrl,
2409 null, null);
John Reck26b18322011-06-21 13:08:58 -07002410 }
2411 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002412 }
2413
Mathew Inwoodb4e831b2011-09-05 18:58:48 +01002414 private void requestLoadCompleteNotification(final PendingIntent loadCompletePendingIntent,
2415 Tab t, String forUrl, final Boolean preloaded, final Boolean preloadSuccess) {
2416 if (loadCompletePendingIntent != null) {
2417 Pattern urlMatch = Pattern.compile(Pattern.quote(forUrl));
2418 t.setOnPageLoadCompleteListener(urlMatch, new Tab.OnPageLoadCompleteListener() {
2419 @Override
2420 public void onPageLoadComplete() {
2421 IntentHandler.sendPageLoadCompletePendingIntent(mActivity,
2422 loadCompletePendingIntent, preloaded, preloadSuccess);
2423 }
2424 });
2425 }
2426 }
2427
John Reck30c714c2010-12-16 17:30:34 -08002428 @Override
2429 public void onUserCanceledSsl(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08002430 // TODO: Figure out the "right" behavior
John Reckef654f12011-07-12 16:42:08 -07002431 if (tab.canGoBack()) {
2432 tab.goBack();
John Reck30c714c2010-12-16 17:30:34 -08002433 } else {
John Reckef654f12011-07-12 16:42:08 -07002434 tab.loadUrl(mSettings.getHomePage(), null);
John Reck30c714c2010-12-16 17:30:34 -08002435 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002436 }
2437
2438 void goBackOnePageOrQuit() {
2439 Tab current = mTabControl.getCurrentTab();
2440 if (current == null) {
2441 /*
2442 * Instead of finishing the activity, simply push this to the back
2443 * of the stack and let ActivityManager to choose the foreground
2444 * activity. As BrowserActivity is singleTask, it will be always the
2445 * root of the task. So we can use either true or false for
2446 * moveTaskToBack().
2447 */
2448 mActivity.moveTaskToBack(true);
2449 return;
2450 }
John Reckef654f12011-07-12 16:42:08 -07002451 if (current.canGoBack()) {
2452 current.goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07002453 } else {
2454 // Check to see if we are closing a window that was created by
2455 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002456 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002457 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002458 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002459 // Now we close the other tab
2460 closeTab(current);
2461 } else {
Michael Kolbe28b3472011-08-04 16:54:31 -07002462 if ((current.getAppId() != null) || current.closeOnBack()) {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002463 closeCurrentTab(true);
Michael Kolbe28b3472011-08-04 16:54:31 -07002464 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002465 /*
2466 * Instead of finishing the activity, simply push this to the back
2467 * of the stack and let ActivityManager to choose the foreground
2468 * activity. As BrowserActivity is singleTask, it will be always the
2469 * root of the task. So we can use either true or false for
2470 * moveTaskToBack().
2471 */
2472 mActivity.moveTaskToBack(true);
2473 }
2474 }
2475 }
2476
2477 /**
2478 * Feed the previously stored results strings to the BrowserProvider so that
2479 * the SearchDialog will show them instead of the standard searches.
2480 * @param result String to show on the editable line of the SearchDialog.
2481 */
2482 @Override
2483 public void showVoiceSearchResults(String result) {
2484 ContentProviderClient client = mActivity.getContentResolver()
2485 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2486 ContentProvider prov = client.getLocalContentProvider();
2487 BrowserProvider bp = (BrowserProvider) prov;
2488 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2489 client.release();
2490
2491 Bundle bundle = createGoogleSearchSourceBundle(
2492 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2493 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2494 startSearch(result, false, bundle, false);
2495 }
2496
2497 private void startSearch(String initialQuery, boolean selectInitialQuery,
2498 Bundle appSearchData, boolean globalSearch) {
2499 if (appSearchData == null) {
2500 appSearchData = createGoogleSearchSourceBundle(
2501 GOOGLE_SEARCH_SOURCE_TYPE);
2502 }
2503
2504 SearchEngine searchEngine = mSettings.getSearchEngine();
2505 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2506 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2507 }
2508 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2509 globalSearch);
2510 }
2511
2512 private Bundle createGoogleSearchSourceBundle(String source) {
2513 Bundle bundle = new Bundle();
2514 bundle.putString(Search.SOURCE, source);
2515 return bundle;
2516 }
2517
2518 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002519 * helper method for key handler
2520 * returns the current tab if it can't advance
2521 */
Michael Kolbc831b632011-05-11 09:30:34 -07002522 private Tab getNextTab() {
2523 return mTabControl.getTab(Math.min(mTabControl.getTabCount() - 1,
2524 mTabControl.getCurrentPosition() + 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002525 }
2526
2527 /**
2528 * helper method for key handler
2529 * returns the current tab if it can't advance
2530 */
Michael Kolbc831b632011-05-11 09:30:34 -07002531 private Tab getPrevTab() {
2532 return mTabControl.getTab(Math.max(0,
2533 mTabControl.getCurrentPosition() - 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002534 }
2535
2536 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002537 * handle key events in browser
2538 *
2539 * @param keyCode
2540 * @param event
2541 * @return true if handled, false to pass to super
2542 */
2543 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002544 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002545 // Even if MENU is already held down, we need to call to super to open
2546 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002547 if (!noModifiers
2548 && ((KeyEvent.KEYCODE_MENU == keyCode)
2549 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2550 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002551 mMenuIsDown = true;
2552 return false;
2553 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002554
Cary Clark8ff8c662010-12-29 15:03:05 -05002555 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07002556 Tab tab = getCurrentTab();
2557 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05002558
Cary Clark160bbb92011-01-10 11:17:07 -05002559 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2560 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002561
Michael Kolb8233fac2010-10-26 16:08:53 -07002562 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002563 case KeyEvent.KEYCODE_TAB:
2564 if (event.isCtrlPressed()) {
2565 if (event.isShiftPressed()) {
2566 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002567 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002568 } else {
2569 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002570 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002571 }
2572 return true;
2573 }
2574 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002575 case KeyEvent.KEYCODE_SPACE:
2576 // WebView/WebTextView handle the keys in the KeyDown. As
2577 // the Activity's shortcut keys are only handled when WebView
2578 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002579 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002580 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002581 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002582 pageDown();
2583 }
2584 return true;
2585 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002586 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002587 event.startTracking();
2588 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07002589 case KeyEvent.KEYCODE_FORWARD:
2590 if (!noModifiers) break;
2591 tab.goForward();
2592 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002593 case KeyEvent.KEYCODE_DPAD_LEFT:
2594 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002595 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05002596 return true;
2597 }
2598 break;
2599 case KeyEvent.KEYCODE_DPAD_RIGHT:
2600 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002601 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05002602 return true;
2603 }
2604 break;
2605 case KeyEvent.KEYCODE_A:
2606 if (ctrl) {
2607 webView.selectAll();
2608 return true;
2609 }
2610 break;
Michael Kolba4183062011-01-16 10:43:21 -08002611// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002612 case KeyEvent.KEYCODE_C:
2613 if (ctrl) {
2614 webView.copySelection();
2615 return true;
2616 }
2617 break;
Michael Kolba4183062011-01-16 10:43:21 -08002618// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002619// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002620// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002621// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002622// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002623// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002624// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002625// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002626// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002627// case KeyEvent.KEYCODE_M: // unused
2628// case KeyEvent.KEYCODE_N: // in Chrome: new window
2629// case KeyEvent.KEYCODE_O: // in Chrome: open file
2630// case KeyEvent.KEYCODE_P: // in Chrome: print page
2631// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002632// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002633// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2634 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002635 // we can't use the ctrl/shift flags, they check for
2636 // exclusive use of a modifier
2637 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002638 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002639 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002640 } else {
2641 openTabToHomePage();
2642 }
2643 return true;
2644 }
2645 break;
2646// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2647// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb5ae15bd2011-08-16 17:09:27 -07002648// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002649// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2650// case KeyEvent.KEYCODE_Y: // unused
2651// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002652 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002653 // it is a regular key and webview is not null
2654 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002655 }
2656
John Recke6bf4ab2011-02-24 15:48:05 -08002657 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2658 switch(keyCode) {
2659 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07002660 if (mUi.isWebShowing()) {
John Recke6bf4ab2011-02-24 15:48:05 -08002661 bookmarksOrHistoryPicker(true);
2662 return true;
2663 }
2664 break;
2665 }
2666 return false;
2667 }
2668
Michael Kolb8233fac2010-10-26 16:08:53 -07002669 boolean onKeyUp(int keyCode, KeyEvent event) {
Michael Kolb2814a362011-05-19 15:49:41 -07002670 if (KeyEvent.KEYCODE_MENU == keyCode) {
2671 mMenuIsDown = false;
2672 if (event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002673 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002674 }
2675 }
Cary Clark160bbb92011-01-10 11:17:07 -05002676 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002677 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002678 case KeyEvent.KEYCODE_BACK:
2679 if (event.isTracking() && !event.isCanceled()) {
2680 onBackKey();
2681 return true;
2682 }
2683 break;
2684 }
2685 return false;
2686 }
2687
2688 public boolean isMenuDown() {
2689 return mMenuIsDown;
2690 }
2691
Ben Murdoch8029a772010-11-16 11:58:21 +00002692 public void setupAutoFill(Message message) {
2693 // Open the settings activity at the AutoFill profile fragment so that
2694 // the user can create a new profile. When they return, we will dispatch
2695 // the message so that we can autofill the form using their new profile.
2696 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2697 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2698 AutoFillSettingsFragment.class.getName());
2699 mAutoFillSetupMessage = message;
2700 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2701 }
John Reckb3417f02011-01-14 11:01:05 -08002702
2703 @Override
Narayan Kamath5119edd2011-02-23 15:49:17 +00002704 public void registerDropdownChangeListener(DropdownChangeListener d) {
2705 mUi.registerDropdownChangeListener(d);
2706 }
Michael Kolbfbc579a2011-07-07 15:59:33 -07002707
2708 public boolean onSearchRequested() {
2709 mUi.editUrl(false);
2710 return true;
2711 }
2712
John Reck1cf4b792011-07-26 10:22:22 -07002713 @Override
2714 public boolean shouldCaptureThumbnails() {
2715 return mUi.shouldCaptureThumbnails();
2716 }
2717
Michael Kolbc3af0672011-08-09 10:24:41 -07002718 @Override
2719 public void setBlockEvents(boolean block) {
2720 mBlockEvents = block;
2721 }
2722
2723 public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002724 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002725 }
2726
2727 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002728 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002729 }
2730
2731 public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002732 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002733 }
2734
2735 public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002736 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002737 }
2738
2739 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002740 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002741 }
2742
Michael Kolb8233fac2010-10-26 16:08:53 -07002743}