blob: 4809f13c64e1254f05b55e8e0a0a8906b5c64a18 [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);
1251 updateInLoadMenuItems(menu);
1252 // hold on to the menu reference here; it is used by the page callbacks
1253 // to update the menu based on loading state
1254 mCachedMenu = menu;
1255 return true;
1256 }
1257
1258 protected void onCreateContextMenu(ContextMenu menu, View v,
1259 ContextMenuInfo menuInfo) {
John Reck0f602f32011-07-07 15:38:43 -07001260 if (v instanceof TitleBar) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001261 return;
1262 }
1263 if (!(v instanceof WebView)) {
1264 return;
1265 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001266 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001267 WebView.HitTestResult result = webview.getHitTestResult();
1268 if (result == null) {
1269 return;
1270 }
1271
1272 int type = result.getType();
1273 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1274 Log.w(LOGTAG,
1275 "We should not show context menu when nothing is touched");
1276 return;
1277 }
1278 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1279 // let TextView handles context menu
1280 return;
1281 }
1282
1283 // Note, http://b/issue?id=1106666 is requesting that
1284 // an inflated menu can be used again. This is not available
1285 // yet, so inflate each time (yuk!)
1286 MenuInflater inflater = mActivity.getMenuInflater();
1287 inflater.inflate(R.menu.browsercontext, menu);
1288
1289 // Show the correct menu group
1290 final String extra = result.getExtra();
1291 menu.setGroupVisible(R.id.PHONE_MENU,
1292 type == WebView.HitTestResult.PHONE_TYPE);
1293 menu.setGroupVisible(R.id.EMAIL_MENU,
1294 type == WebView.HitTestResult.EMAIL_TYPE);
1295 menu.setGroupVisible(R.id.GEO_MENU,
1296 type == WebView.HitTestResult.GEO_TYPE);
1297 menu.setGroupVisible(R.id.IMAGE_MENU,
1298 type == WebView.HitTestResult.IMAGE_TYPE
1299 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1300 menu.setGroupVisible(R.id.ANCHOR_MENU,
1301 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1302 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001303 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1304 || type == WebView.HitTestResult.PHONE_TYPE
1305 || type == WebView.HitTestResult.EMAIL_TYPE
1306 || type == WebView.HitTestResult.GEO_TYPE;
1307 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1308 if (hitText) {
1309 menu.findItem(R.id.select_text_menu_id)
1310 .setOnMenuItemClickListener(new SelectText(webview));
1311 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001312 // Setup custom handling depending on the type
1313 switch (type) {
1314 case WebView.HitTestResult.PHONE_TYPE:
1315 menu.setHeaderTitle(Uri.decode(extra));
1316 menu.findItem(R.id.dial_context_menu_id).setIntent(
1317 new Intent(Intent.ACTION_VIEW, Uri
1318 .parse(WebView.SCHEME_TEL + extra)));
1319 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1320 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1321 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1322 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1323 addIntent);
1324 menu.findItem(R.id.copy_phone_context_menu_id)
1325 .setOnMenuItemClickListener(
1326 new Copy(extra));
1327 break;
1328
1329 case WebView.HitTestResult.EMAIL_TYPE:
1330 menu.setHeaderTitle(extra);
1331 menu.findItem(R.id.email_context_menu_id).setIntent(
1332 new Intent(Intent.ACTION_VIEW, Uri
1333 .parse(WebView.SCHEME_MAILTO + extra)));
1334 menu.findItem(R.id.copy_mail_context_menu_id)
1335 .setOnMenuItemClickListener(
1336 new Copy(extra));
1337 break;
1338
1339 case WebView.HitTestResult.GEO_TYPE:
1340 menu.setHeaderTitle(extra);
1341 menu.findItem(R.id.map_context_menu_id).setIntent(
1342 new Intent(Intent.ACTION_VIEW, Uri
1343 .parse(WebView.SCHEME_GEO
1344 + URLEncoder.encode(extra))));
1345 menu.findItem(R.id.copy_geo_context_menu_id)
1346 .setOnMenuItemClickListener(
1347 new Copy(extra));
1348 break;
1349
1350 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1351 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001352 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001353 // decide whether to show the open link in new tab option
1354 boolean showNewTab = mTabControl.canCreateNewTab();
1355 MenuItem newTabItem
1356 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001357 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001358 ? R.string.contextmenu_openlink_newwindow_background
1359 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001360 newTabItem.setVisible(showNewTab);
1361 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001362 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1363 newTabItem.setOnMenuItemClickListener(
1364 new MenuItem.OnMenuItemClickListener() {
1365 @Override
1366 public boolean onMenuItemClick(MenuItem item) {
1367 final HashMap<String, WebView> hrefMap =
1368 new HashMap<String, WebView>();
1369 hrefMap.put("webview", webview);
1370 final Message msg = mHandler.obtainMessage(
1371 FOCUS_NODE_HREF,
1372 R.id.open_newtab_context_menu_id,
1373 0, hrefMap);
1374 webview.requestFocusNodeHref(msg);
1375 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001376 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001377 });
1378 } else {
1379 newTabItem.setOnMenuItemClickListener(
1380 new MenuItem.OnMenuItemClickListener() {
1381 @Override
1382 public boolean onMenuItemClick(MenuItem item) {
1383 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001384 openTab(extra, parent,
1385 !mSettings.openInBackground(),
1386 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001387 return true;
1388 }
1389 });
1390 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001391 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001392 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1393 break;
1394 }
1395 // otherwise fall through to handle image part
1396 case WebView.HitTestResult.IMAGE_TYPE:
1397 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1398 menu.setHeaderTitle(extra);
1399 }
1400 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1401 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1402 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001403 setOnMenuItemClickListener(
1404 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001405 menu.findItem(R.id.set_wallpaper_context_menu_id).
1406 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1407 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001408 break;
1409
1410 default:
1411 Log.w(LOGTAG, "We should not get here.");
1412 break;
1413 }
1414 //update the ui
1415 mUi.onContextMenuCreated(menu);
1416 }
1417
1418 /**
1419 * As the menu can be open when loading state changes
1420 * we must manually update the state of the stop/reload menu
1421 * item
1422 */
1423 private void updateInLoadMenuItems(Menu menu) {
1424 if (menu == null) {
1425 return;
1426 }
1427 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1428 MenuItem src = mInLoad ?
1429 menu.findItem(R.id.stop_menu_id):
1430 menu.findItem(R.id.reload_menu_id);
1431 if (src != null) {
1432 dest.setIcon(src.getIcon());
1433 dest.setTitle(src.getTitle());
1434 }
1435 }
1436
John Reckb3417f02011-01-14 11:01:05 -08001437 boolean onPrepareOptionsMenu(Menu 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;
Michael Kolb4bf79712011-07-14 14:18:12 -07001468 if (tab != null) {
1469 canGoBack = tab.canGoBack();
1470 canGoForward = tab.canGoForward();
1471 isHome = mSettings.getHomePage().equals(tab.getUrl());
John Reck42229bc2011-08-19 13:26:43 -07001472 isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
Michael Kolb4bf79712011-07-14 14:18:12 -07001473 }
1474 final MenuItem back = menu.findItem(R.id.back_menu_id);
1475 back.setEnabled(canGoBack);
1476
1477 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1478 home.setEnabled(!isHome);
1479
1480 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1481 forward.setEnabled(canGoForward);
1482
1483 final MenuItem source = menu.findItem(mInLoad ? R.id.stop_menu_id : R.id.reload_menu_id);
1484 final MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolb7ab75ee2011-07-14 16:36:38 -07001485 if (source != null && dest != null) {
1486 dest.setTitle(source.getTitle());
1487 dest.setIcon(source.getIcon());
1488 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001489
1490 // decide whether to show the share link option
1491 PackageManager pm = mActivity.getPackageManager();
1492 Intent send = new Intent(Intent.ACTION_SEND);
1493 send.setType("text/plain");
1494 ResolveInfo ri = pm.resolveActivity(send,
1495 PackageManager.MATCH_DEFAULT_ONLY);
1496 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1497
1498 boolean isNavDump = mSettings.enableNavDump();
1499 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1500 nav.setVisible(isNavDump);
1501 nav.setEnabled(isNavDump);
1502
1503 boolean showDebugSettings = mSettings.isDebugEnabled();
1504 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1505 counter.setVisible(showDebugSettings);
1506 counter.setEnabled(showDebugSettings);
John Reck42229bc2011-08-19 13:26:43 -07001507 final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
1508 uaSwitcher.setChecked(isDesktopUa);
Michael Kolb4bf79712011-07-14 14:18:12 -07001509
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001510 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001511 }
1512
Michael Kolb8233fac2010-10-26 16:08:53 -07001513 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001514 if (null == getCurrentTopWebView()) {
1515 return false;
1516 }
1517 if (mMenuIsDown) {
1518 // The shortcut action consumes the MENU. Even if it is still down,
1519 // it won't trigger the next shortcut action. In the case of the
1520 // shortcut action triggering a new activity, like Bookmarks, we
1521 // won't get onKeyUp for MENU. So it is important to reset it here.
1522 mMenuIsDown = false;
1523 }
Michael Kolb3ca12752011-07-20 13:52:25 -07001524 if (mUi.onOptionsItemSelected(item)) {
1525 // ui callback handled it
1526 return true;
1527 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001528 switch (item.getItemId()) {
1529 // -- Main menu
1530 case R.id.new_tab_menu_id:
1531 openTabToHomePage();
1532 break;
1533
1534 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001535 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001536 break;
1537
1538 case R.id.goto_menu_id:
1539 editUrl();
1540 break;
1541
1542 case R.id.bookmarks_menu_id:
1543 bookmarksOrHistoryPicker(false);
1544 break;
1545
Michael Kolb8233fac2010-10-26 16:08:53 -07001546 case R.id.add_bookmark_menu_id:
John Recka60fffa2011-09-06 16:30:29 -07001547 Intent bookmarkIntent = createBookmarkCurrentPageIntent(false);
1548 if (bookmarkIntent != null) {
1549 mActivity.startActivity(bookmarkIntent);
1550 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001551 break;
1552
1553 case R.id.stop_reload_menu_id:
1554 if (mInLoad) {
1555 stopLoading();
1556 } else {
1557 getCurrentTopWebView().reload();
1558 }
1559 break;
1560
1561 case R.id.back_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001562 getCurrentTab().goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07001563 break;
1564
1565 case R.id.forward_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001566 getCurrentTab().goForward();
Michael Kolb8233fac2010-10-26 16:08:53 -07001567 break;
1568
1569 case R.id.close_menu_id:
1570 // Close the subwindow if it exists.
1571 if (mTabControl.getCurrentSubWindow() != null) {
1572 dismissSubWindow(mTabControl.getCurrentTab());
1573 break;
1574 }
1575 closeCurrentTab();
1576 break;
1577
1578 case R.id.homepage_menu_id:
1579 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07001580 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07001581 break;
1582
1583 case R.id.preferences_menu_id:
1584 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1585 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1586 getCurrentTopWebView().getUrl());
1587 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1588 break;
1589
1590 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001591 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001592 break;
1593
John Reck2bc80422011-06-30 15:11:49 -07001594 case R.id.save_snapshot_menu_id:
1595 final Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07001596 if (source == null) break;
John Reckd8c74522011-06-14 08:45:00 -07001597 final ContentResolver cr = mActivity.getContentResolver();
1598 final ContentValues values = source.createSnapshotValues();
John Reck2bc80422011-06-30 15:11:49 -07001599 if (values != null) {
1600 new AsyncTask<Tab, Void, Long>() {
John Reckd8c74522011-06-14 08:45:00 -07001601
John Reck2bc80422011-06-30 15:11:49 -07001602 @Override
1603 protected Long doInBackground(Tab... params) {
1604 Uri result = cr.insert(Snapshots.CONTENT_URI, values);
1605 long id = ContentUris.parseId(result);
1606 return id;
John Reckd8c74522011-06-14 08:45:00 -07001607 }
John Reckf33b1632011-06-04 20:00:23 -07001608
John Reck2bc80422011-06-30 15:11:49 -07001609 @Override
1610 protected void onPostExecute(Long id) {
1611 Bundle b = new Bundle();
1612 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
1613 mUi.showComboView(ComboViews.Snapshots, b);
1614 };
1615 }.execute(source);
1616 } else {
1617 Toast.makeText(mActivity, R.string.snapshot_failed,
Leon Scrogginsac993842011-02-02 12:54:07 -05001618 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001619 }
Leon Scrogginsac993842011-02-02 12:54:07 -05001620 break;
1621
Michael Kolb8233fac2010-10-26 16:08:53 -07001622 case R.id.page_info_menu_id:
Huahui Wuae0c0412011-06-28 10:17:05 -07001623 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001624 break;
1625
1626 case R.id.classic_history_menu_id:
1627 bookmarksOrHistoryPicker(true);
1628 break;
1629
Michael Kolb8233fac2010-10-26 16:08:53 -07001630 case R.id.share_page_menu_id:
1631 Tab currentTab = mTabControl.getCurrentTab();
1632 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001633 return false;
1634 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001635 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001636 break;
1637
1638 case R.id.dump_nav_menu_id:
1639 getCurrentTopWebView().debugDump();
1640 break;
1641
1642 case R.id.dump_counters_menu_id:
1643 getCurrentTopWebView().dumpV8Counters();
1644 break;
1645
1646 case R.id.zoom_in_menu_id:
1647 getCurrentTopWebView().zoomIn();
1648 break;
1649
1650 case R.id.zoom_out_menu_id:
1651 getCurrentTopWebView().zoomOut();
1652 break;
1653
1654 case R.id.view_downloads_menu_id:
1655 viewDownloads();
1656 break;
1657
John Reck42229bc2011-08-19 13:26:43 -07001658 case R.id.ua_desktop_menu_id:
1659 WebView web = getCurrentWebView();
1660 mSettings.toggleDesktopUseragent(web);
1661 web.loadUrl(web.getOriginalUrl());
1662 break;
1663
Michael Kolb8233fac2010-10-26 16:08:53 -07001664 case R.id.window_one_menu_id:
1665 case R.id.window_two_menu_id:
1666 case R.id.window_three_menu_id:
1667 case R.id.window_four_menu_id:
1668 case R.id.window_five_menu_id:
1669 case R.id.window_six_menu_id:
1670 case R.id.window_seven_menu_id:
1671 case R.id.window_eight_menu_id:
1672 {
1673 int menuid = item.getItemId();
1674 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1675 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1676 Tab desiredTab = mTabControl.getTab(id);
1677 if (desiredTab != null &&
1678 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001679 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001680 }
1681 break;
1682 }
1683 }
1684 }
1685 break;
1686
1687 default:
1688 return false;
1689 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001690 return true;
1691 }
1692
1693 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001694 // Let the History and Bookmark fragments handle menus they created.
1695 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1696 return false;
1697 }
1698
Michael Kolb8233fac2010-10-26 16:08:53 -07001699 int id = item.getItemId();
1700 boolean result = true;
1701 switch (id) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001702 // -- Browser context menu
1703 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001704 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001705 case R.id.copy_link_context_menu_id:
1706 final WebView webView = getCurrentTopWebView();
1707 if (null == webView) {
1708 result = false;
1709 break;
1710 }
1711 final HashMap<String, WebView> hrefMap =
1712 new HashMap<String, WebView>();
1713 hrefMap.put("webview", webView);
1714 final Message msg = mHandler.obtainMessage(
1715 FOCUS_NODE_HREF, id, 0, hrefMap);
1716 webView.requestFocusNodeHref(msg);
1717 break;
1718
1719 default:
1720 // For other context menus
1721 result = onOptionsItemSelected(item);
1722 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001723 return result;
1724 }
1725
1726 /**
1727 * support programmatically opening the context menu
1728 */
1729 public void openContextMenu(View view) {
1730 mActivity.openContextMenu(view);
1731 }
1732
1733 /**
1734 * programmatically open the options menu
1735 */
1736 public void openOptionsMenu() {
1737 mActivity.openOptionsMenu();
1738 }
1739
1740 public boolean onMenuOpened(int featureId, Menu menu) {
1741 if (mOptionsMenuOpen) {
1742 if (mConfigChanged) {
1743 // We do not need to make any changes to the state of the
1744 // title bar, since the only thing that happened was a
1745 // change in orientation
1746 mConfigChanged = false;
1747 } else {
1748 if (!mExtendedMenuOpen) {
1749 mExtendedMenuOpen = true;
1750 mUi.onExtendedMenuOpened();
1751 } else {
1752 // Switching the menu back to icon view, so show the
1753 // title bar once again.
1754 mExtendedMenuOpen = false;
1755 mUi.onExtendedMenuClosed(mInLoad);
Michael Kolb8233fac2010-10-26 16:08:53 -07001756 }
1757 }
1758 } else {
1759 // The options menu is closed, so open it, and show the title
1760 mOptionsMenuOpen = true;
1761 mConfigChanged = false;
1762 mExtendedMenuOpen = false;
1763 mUi.onOptionsMenuOpened();
1764 }
1765 return true;
1766 }
1767
1768 public void onOptionsMenuClosed(Menu menu) {
1769 mOptionsMenuOpen = false;
1770 mUi.onOptionsMenuClosed(mInLoad);
1771 }
1772
1773 public void onContextMenuClosed(Menu menu) {
1774 mUi.onContextMenuClosed(menu, mInLoad);
1775 }
1776
1777 // Helper method for getting the top window.
1778 @Override
1779 public WebView getCurrentTopWebView() {
1780 return mTabControl.getCurrentTopWebView();
1781 }
1782
1783 @Override
1784 public WebView getCurrentWebView() {
1785 return mTabControl.getCurrentWebView();
1786 }
1787
1788 /*
1789 * This method is called as a result of the user selecting the options
1790 * menu to see the download window. It shows the download window on top of
1791 * the current window.
1792 */
1793 void viewDownloads() {
1794 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1795 mActivity.startActivity(intent);
1796 }
1797
John Reck30b065e2011-07-19 10:58:05 -07001798 int getActionModeHeight() {
1799 TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
1800 new int[] { android.R.attr.actionBarSize });
1801 int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
1802 actionBarSizeTypedArray.recycle();
1803 return size;
1804 }
1805
Michael Kolb8233fac2010-10-26 16:08:53 -07001806 // action mode
1807
1808 void onActionModeStarted(ActionMode mode) {
1809 mUi.onActionModeStarted(mode);
1810 mActionMode = mode;
Michael Kolb42c0c062011-08-02 12:56:06 -07001811 if (mSimulateActionBarOverlayMode && !mUi.isEditingUrl()) {
John Reck30b065e2011-07-19 10:58:05 -07001812 WebView web = getCurrentWebView();
1813 // Simulate overlay mode by scrolling the webview the amount it will be
1814 // pushed down. Actual overlay mode doesn't work for us as otherwise
1815 // the CAB will, well, overlay the content, which breaks things like
1816 // find on page.
1817 int scrollBy = getActionModeHeight();
1818 web.scrollBy(0, scrollBy);
1819 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001820 }
1821
1822 /*
1823 * True if a custom ActionMode (i.e. find or select) is in use.
1824 */
1825 @Override
1826 public boolean isInCustomActionMode() {
1827 return mActionMode != null;
1828 }
1829
1830 /*
1831 * End the current ActionMode.
1832 */
1833 @Override
1834 public void endActionMode() {
1835 if (mActionMode != null) {
1836 mActionMode.finish();
1837 }
1838 }
1839
1840 /*
1841 * Called by find and select when they are finished. Replace title bars
1842 * as necessary.
1843 */
1844 public void onActionModeFinished(ActionMode mode) {
1845 if (!isInCustomActionMode()) return;
1846 mUi.onActionModeFinished(mInLoad);
1847 mActionMode = null;
John Reck30b065e2011-07-19 10:58:05 -07001848 if (mSimulateActionBarOverlayMode) {
1849 WebView web = getCurrentWebView();
1850 int scrollBy = getActionModeHeight();
1851 web.scrollBy(0, -scrollBy);
1852 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001853 }
1854
1855 boolean isInLoad() {
1856 return mInLoad;
1857 }
1858
1859 // bookmark handling
1860
1861 /**
1862 * add the current page as a bookmark to the given folder id
1863 * @param folderId use -1 for the default folder
John Reckd3e4d5b2011-07-13 15:48:43 -07001864 * @param editExisting If true, check to see whether the site is already
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001865 * bookmarked, and if it is, edit that bookmark. If false, and
1866 * the site is already bookmarked, do not attempt to edit the
1867 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001868 */
1869 @Override
John Reckd3e4d5b2011-07-13 15:48:43 -07001870 public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
John Recka60fffa2011-09-06 16:30:29 -07001871 WebView w = getCurrentTopWebView();
1872 if (w == null) {
1873 return null;
1874 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001875 Intent i = new Intent(mActivity,
1876 AddBookmarkPage.class);
Michael Kolb8233fac2010-10-26 16:08:53 -07001877 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1878 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1879 String touchIconUrl = w.getTouchIconUrl();
1880 if (touchIconUrl != null) {
1881 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1882 WebSettings settings = w.getSettings();
1883 if (settings != null) {
1884 i.putExtra(AddBookmarkPage.USER_AGENT,
1885 settings.getUserAgentString());
1886 }
1887 }
1888 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1889 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1890 getDesiredThumbnailHeight(mActivity)));
1891 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07001892 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001893 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1894 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001895 // Put the dialog at the upper right of the screen, covering the
1896 // star on the title bar.
1897 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07001898 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07001899 }
1900
1901 // file chooser
1902 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1903 mUploadHandler = new UploadHandler(this);
1904 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1905 }
1906
1907 // thumbnails
1908
1909 /**
1910 * Return the desired width for thumbnail screenshots, which are stored in
1911 * the database, and used on the bookmarks screen.
1912 * @param context Context for finding out the density of the screen.
1913 * @return desired width for thumbnail screenshot.
1914 */
1915 static int getDesiredThumbnailWidth(Context context) {
1916 return context.getResources().getDimensionPixelOffset(
1917 R.dimen.bookmarkThumbnailWidth);
1918 }
1919
1920 /**
1921 * Return the desired height for thumbnail screenshots, which are stored in
1922 * the database, and used on the bookmarks screen.
1923 * @param context Context for finding out the density of the screen.
1924 * @return desired height for thumbnail screenshot.
1925 */
1926 static int getDesiredThumbnailHeight(Context context) {
1927 return context.getResources().getDimensionPixelOffset(
1928 R.dimen.bookmarkThumbnailHeight);
1929 }
1930
John Reck8cc92352011-07-06 17:41:52 -07001931 static Bitmap createScreenshot(WebView view, int width, int height) {
John Reckd7dd9b22011-08-30 09:18:29 -07001932 if (view == null || view.getContentHeight() == 0
1933 || view.getContentWidth() == 0) {
1934 return null;
1935 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001936 // We render to a bitmap 2x the desired size so that we can then
1937 // re-scale it with filtering since canvas.scale doesn't filter
1938 // This helps reduce aliasing at the cost of being slightly blurry
1939 final int filter_scale = 2;
John Reckd7dd9b22011-08-30 09:18:29 -07001940 int scaledWidth = width * filter_scale;
1941 int scaledHeight = height * filter_scale;
1942 if (sThumbnailBitmap == null || sThumbnailBitmap.getWidth() != scaledWidth
1943 || sThumbnailBitmap.getHeight() != scaledHeight) {
1944 if (sThumbnailBitmap != null) {
1945 sThumbnailBitmap.recycle();
1946 sThumbnailBitmap = null;
1947 }
1948 sThumbnailBitmap =
1949 Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.RGB_565);
Michael Kolb8233fac2010-10-26 16:08:53 -07001950 }
John Reckd7dd9b22011-08-30 09:18:29 -07001951 Canvas canvas = new Canvas(sThumbnailBitmap);
1952 int contentWidth = view.getContentWidth();
1953 float overviewScale = scaledWidth / (view.getScale() * contentWidth);
1954 if (view instanceof BrowserWebView) {
1955 int dy = -((BrowserWebView)view).getTitleHeight();
1956 canvas.translate(0, dy * overviewScale);
1957 }
1958
1959 canvas.scale(overviewScale, overviewScale);
1960
1961 if (view instanceof BrowserWebView) {
1962 ((BrowserWebView)view).drawContent(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07001963 } else {
John Reckd7dd9b22011-08-30 09:18:29 -07001964 view.draw(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07001965 }
John Reckd7dd9b22011-08-30 09:18:29 -07001966 Bitmap ret = Bitmap.createScaledBitmap(sThumbnailBitmap,
1967 width, height, true);
Dianne Hackborn43cfe8a2011-08-02 16:59:35 -07001968 canvas.setBitmap(null);
John Reck5c6ac2f2011-01-05 10:18:03 -08001969 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001970 }
1971
John Reck34ef2672011-02-10 11:30:55 -08001972 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001973 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07001974 // FIXME: Would like to make sure there is actually something to
1975 // draw, but the API for that (WebViewCore.pictureReady()) is not
1976 // currently accessible here.
1977
John Reck34ef2672011-02-10 11:30:55 -08001978 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08001979 if (view == null) {
1980 // Tab was destroyed
1981 return;
1982 }
John Reck34ef2672011-02-10 11:30:55 -08001983 final String url = tab.getUrl();
1984 final String originalUrl = view.getOriginalUrl();
1985
1986 if (TextUtils.isEmpty(url)) {
1987 return;
1988 }
1989
1990 // Only update thumbnails for web urls (http(s)://), not for
1991 // about:, javascript:, data:, etc...
1992 // Unless it is a bookmarked site, then always update
1993 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
1994 return;
1995 }
1996
Michael Kolb8233fac2010-10-26 16:08:53 -07001997 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1998 getDesiredThumbnailHeight(mActivity));
1999 if (bm == null) {
2000 return;
2001 }
2002
2003 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002004 new AsyncTask<Void, Void, Void>() {
2005 @Override
2006 protected Void doInBackground(Void... unused) {
2007 Cursor cursor = null;
2008 try {
2009 // TODO: Clean this up
2010 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2011 if (cursor != null && cursor.moveToFirst()) {
2012 final ByteArrayOutputStream os =
2013 new ByteArrayOutputStream();
2014 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002015
John Reck34ef2672011-02-10 11:30:55 -08002016 ContentValues values = new ContentValues();
2017 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002018
John Reck34ef2672011-02-10 11:30:55 -08002019 do {
John Reck617fd832011-02-16 14:35:59 -08002020 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002021 cr.update(Images.CONTENT_URI, values, null, null);
2022 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002023 }
John Reck34ef2672011-02-10 11:30:55 -08002024 } catch (IllegalStateException e) {
2025 // Ignore
2026 } finally {
2027 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002028 }
John Reck34ef2672011-02-10 11:30:55 -08002029 return null;
2030 }
2031 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002032 }
2033
2034 private class Copy implements OnMenuItemClickListener {
2035 private CharSequence mText;
2036
2037 public boolean onMenuItemClick(MenuItem item) {
2038 copy(mText);
2039 return true;
2040 }
2041
2042 public Copy(CharSequence toCopy) {
2043 mText = toCopy;
2044 }
2045 }
2046
Leon Scroggins63c02662010-11-18 15:16:27 -05002047 private static class Download implements OnMenuItemClickListener {
2048 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002049 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002050 private boolean mPrivateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002051
2052 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002053 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002054 null, null, mPrivateBrowsing);
Michael Kolb8233fac2010-10-26 16:08:53 -07002055 return true;
2056 }
2057
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002058 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002059 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002060 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002061 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002062 }
2063 }
2064
Cary Clark8974d282010-11-22 10:46:05 -05002065 private static class SelectText implements OnMenuItemClickListener {
2066 private WebView mWebView;
2067
2068 public boolean onMenuItemClick(MenuItem item) {
2069 if (mWebView != null) {
2070 return mWebView.selectText();
2071 }
2072 return false;
2073 }
2074
2075 public SelectText(WebView webView) {
2076 mWebView = webView;
2077 }
2078
2079 }
2080
Michael Kolb8233fac2010-10-26 16:08:53 -07002081 /********************** TODO: UI stuff *****************************/
2082
2083 // these methods have been copied, they still need to be cleaned up
2084
2085 /****************** tabs ***************************************************/
2086
2087 // basic tab interactions:
2088
2089 // it is assumed that tabcontrol already knows about the tab
2090 protected void addTab(Tab tab) {
2091 mUi.addTab(tab);
2092 }
2093
2094 protected void removeTab(Tab tab) {
2095 mUi.removeTab(tab);
2096 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002097 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002098 }
2099
Michael Kolbf2055602011-04-09 17:20:03 -07002100 @Override
2101 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002102 // monkey protection against delayed start
2103 if (tab != null) {
2104 mTabControl.setCurrentTab(tab);
2105 // the tab is guaranteed to have a webview after setCurrentTab
2106 mUi.setActiveTab(tab);
2107 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002108 }
2109
John Reck8bcafc12011-08-29 16:43:02 -07002110 protected void closeEmptyTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002111 Tab current = mTabControl.getCurrentTab();
2112 if (current != null
2113 && current.getWebView().copyBackForwardList().getSize() == 0) {
John Reck8bcafc12011-08-29 16:43:02 -07002114 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002115 }
2116 }
2117
John Reck26b18322011-06-21 13:08:58 -07002118 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002119 // Dismiss the subwindow if applicable.
2120 dismissSubWindow(appTab);
2121 // Since we might kill the WebView, remove it from the
2122 // content view first.
2123 mUi.detachTab(appTab);
2124 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002125 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002126 // TODO: analyze why the remove and add are necessary
2127 mUi.attachTab(appTab);
2128 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002129 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002130 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002131 } else {
2132 // If the tab was the current tab, we have to attach
2133 // it to the view system again.
2134 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002135 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002136 }
2137 }
2138
2139 // Remove the sub window if it exists. Also called by TabControl when the
2140 // user clicks the 'X' to dismiss a sub window.
2141 public void dismissSubWindow(Tab tab) {
2142 removeSubWindow(tab);
2143 // dismiss the subwindow. This will destroy the WebView.
2144 tab.dismissSubWindow();
2145 getCurrentTopWebView().requestFocus();
2146 }
2147
2148 @Override
2149 public void removeSubWindow(Tab t) {
2150 if (t.getSubWebView() != null) {
2151 mUi.removeSubWindow(t.getSubViewContainer());
2152 }
2153 }
2154
2155 @Override
2156 public void attachSubWindow(Tab tab) {
2157 if (tab.getSubWebView() != null) {
2158 mUi.attachSubWindow(tab.getSubViewContainer());
2159 getCurrentTopWebView().requestFocus();
2160 }
2161 }
2162
Mathew Inwood29721c22011-06-29 17:55:24 +01002163 private Tab showPreloadedTab(final UrlData urlData) {
2164 if (!urlData.isPreloaded()) {
2165 return null;
2166 }
2167 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2168 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2169 if (sbQuery != null) {
Mathew Inwoodb4e831b2011-09-05 18:58:48 +01002170 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders,
2171 urlData.getOnLoadCompletePendingIntent())) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002172 // Could not submit query. Fallback to regular tab creation
2173 tabControl.destroy();
2174 return null;
2175 }
2176 }
Michael Kolbff6a7482011-07-26 16:37:15 -07002177 // check tab count and make room for new tab
2178 if (!mTabControl.canCreateNewTab()) {
2179 Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
2180 if (leastUsed != null) {
2181 closeTab(leastUsed);
2182 }
2183 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002184 Tab t = tabControl.getTab();
Mathew Inwoode09305e2011-09-02 12:03:26 +01002185 t.refreshIdAfterPreload();
Mathew Inwood29721c22011-06-29 17:55:24 +01002186 mTabControl.addPreloadedTab(t);
2187 addTab(t);
2188 setActiveTab(t);
Mathew Inwoodb4e831b2011-09-05 18:58:48 +01002189 if (sbQuery == null) {
2190 // if the searchbox query is set, the load complete notification is handled within
2191 // the preloaded tab controller.
2192 if (t.inPageLoad()) {
2193 requestLoadCompleteNotification(urlData.mOnLoadCompletePendingIntent, t,
2194 urlData.mUrl, true, true);
2195 } else {
2196 // the page is already fully loaded
2197 IntentHandler.sendPageLoadCompletePendingIntent(mActivity,
2198 urlData.mOnLoadCompletePendingIntent, true, true);
2199 }
2200 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002201 return t;
2202 }
2203
Michael Kolb7bcafde2011-05-09 13:55:59 -07002204 // open a non inconito tab with the given url data
2205 // and set as active tab
2206 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002207 Tab tab = showPreloadedTab(urlData);
2208 if (tab == null) {
2209 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002210 if ((tab != null) && !urlData.isEmpty()) {
2211 loadUrlDataIn(tab, urlData);
2212 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002213 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002214 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002215 }
2216
Michael Kolb843510f2010-12-09 10:51:49 -08002217 @Override
2218 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002219 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002220 }
2221
Michael Kolb8233fac2010-10-26 16:08:53 -07002222 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002223 public Tab openIncognitoTab() {
2224 return openTab(INCOGNITO_URI, true, true, false);
2225 }
2226
2227 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002228 public Tab openTab(String url, boolean incognito, boolean setActive,
2229 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002230 return openTab(url, incognito, setActive, useCurrent, null);
2231 }
2232
2233 @Override
2234 public Tab openTab(String url, Tab parent, boolean setActive,
2235 boolean useCurrent) {
2236 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2237 setActive, useCurrent, parent);
2238 }
2239
2240 public Tab openTab(String url, boolean incognito, boolean setActive,
2241 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002242 Tab tab = createNewTab(incognito, setActive, useCurrent);
2243 if (tab != null) {
John Reck5949c662011-05-27 09:52:29 -07002244 if (parent != null && parent != tab) {
2245 parent.addChildTab(tab);
2246 }
Michael Kolb519d2282011-05-09 17:03:19 -07002247 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002248 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002249 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002250 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002251 return tab;
2252 }
2253
2254 // this method will attempt to create a new tab
2255 // incognito: private browsing tab
2256 // setActive: ste tab as current tab
2257 // useCurrent: if no new tab can be created, return current tab
2258 private Tab createNewTab(boolean incognito, boolean setActive,
2259 boolean useCurrent) {
2260 Tab tab = null;
2261 if (mTabControl.canCreateNewTab()) {
2262 tab = mTabControl.createNewTab(incognito);
2263 addTab(tab);
2264 if (setActive) {
2265 setActiveTab(tab);
2266 }
2267 } else {
2268 if (useCurrent) {
2269 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002270 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002271 } else {
2272 mUi.showMaxTabsWarning();
2273 }
2274 }
2275 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002276 }
2277
John Reck2bc80422011-06-30 15:11:49 -07002278 @Override
2279 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2280 SnapshotTab tab = null;
2281 if (mTabControl.canCreateNewTab()) {
2282 tab = mTabControl.createSnapshotTab(snapshotId);
2283 addTab(tab);
2284 if (setActive) {
2285 setActiveTab(tab);
2286 }
2287 } else {
2288 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07002289 }
2290 return tab;
2291 }
2292
Michael Kolb8233fac2010-10-26 16:08:53 -07002293 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002294 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002295 * @return boolean True if we successfully switched to a different tab. If
2296 * the indexth tab is null, or if that tab is the same as
2297 * the current one, return false.
2298 */
2299 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002300 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002301 Tab currentTab = mTabControl.getCurrentTab();
2302 if (tab == null || tab == currentTab) {
2303 return false;
2304 }
2305 setActiveTab(tab);
2306 return true;
2307 }
2308
2309 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002310 public void closeCurrentTab() {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002311 closeCurrentTab(false);
2312 }
2313
2314 protected void closeCurrentTab(boolean andQuit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002315 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07002316 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07002317 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08002318 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002319 return;
2320 }
Michael Kolbc831b632011-05-11 09:30:34 -07002321 final Tab current = mTabControl.getCurrentTab();
2322 final int pos = mTabControl.getCurrentPosition();
2323 Tab newTab = current.getParent();
2324 if (newTab == null) {
2325 newTab = mTabControl.getTab(pos + 1);
2326 if (newTab == null) {
2327 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002328 }
2329 }
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002330 if (andQuit) {
2331 mTabControl.setCurrentTab(newTab);
2332 closeTab(current);
2333 } else if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002334 // Close window
2335 closeTab(current);
2336 }
2337 }
2338
2339 /**
2340 * Close the tab, remove its associated title bar, and adjust mTabControl's
2341 * current tab to a valid value.
2342 */
2343 @Override
2344 public void closeTab(Tab tab) {
Michael Kolb2d59c322011-01-25 13:18:55 -08002345 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002346 }
2347
Michael Kolb8233fac2010-10-26 16:08:53 -07002348 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07002349 protected void loadUrlFromContext(String url) {
2350 Tab tab = getCurrentTab();
2351 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002352 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07002353 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002354 url = UrlUtils.smartUrlFilter(url);
2355 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07002356 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07002357 }
2358 }
2359 }
2360
2361 /**
2362 * Load the URL into the given WebView and update the title bar
2363 * to reflect the new load. Call this instead of WebView.loadUrl
2364 * directly.
2365 * @param view The WebView used to load url.
2366 * @param url The URL to load.
2367 */
John Reck71e51422011-07-01 16:49:28 -07002368 @Override
2369 public void loadUrl(Tab tab, String url) {
John Reck26b18322011-06-21 13:08:58 -07002370 loadUrl(tab, url, null);
2371 }
2372
2373 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
2374 if (tab != null) {
2375 dismissSubWindow(tab);
2376 tab.loadUrl(url, headers);
2377 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002378 }
2379
2380 /**
2381 * Load UrlData into a Tab and update the title bar to reflect the new
2382 * load. Call this instead of UrlData.loadIn directly.
2383 * @param t The Tab used to load.
2384 * @param data The UrlData being loaded.
2385 */
2386 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07002387 if (data != null) {
2388 if (data.mVoiceIntent != null) {
2389 t.activateVoiceSearchMode(data.mVoiceIntent);
Michael Kolb14612442011-06-24 13:06:29 -07002390 } else if (data.isPreloaded()) {
2391 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07002392 } else {
2393 loadUrl(t, data.mUrl, data.mHeaders);
Mathew Inwoodb4e831b2011-09-05 18:58:48 +01002394 requestLoadCompleteNotification(data.mOnLoadCompletePendingIntent, t, data.mUrl,
2395 null, null);
John Reck26b18322011-06-21 13:08:58 -07002396 }
2397 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002398 }
2399
Mathew Inwoodb4e831b2011-09-05 18:58:48 +01002400 private void requestLoadCompleteNotification(final PendingIntent loadCompletePendingIntent,
2401 Tab t, String forUrl, final Boolean preloaded, final Boolean preloadSuccess) {
2402 if (loadCompletePendingIntent != null) {
2403 Pattern urlMatch = Pattern.compile(Pattern.quote(forUrl));
2404 t.setOnPageLoadCompleteListener(urlMatch, new Tab.OnPageLoadCompleteListener() {
2405 @Override
2406 public void onPageLoadComplete() {
2407 IntentHandler.sendPageLoadCompletePendingIntent(mActivity,
2408 loadCompletePendingIntent, preloaded, preloadSuccess);
2409 }
2410 });
2411 }
2412 }
2413
John Reck30c714c2010-12-16 17:30:34 -08002414 @Override
2415 public void onUserCanceledSsl(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08002416 // TODO: Figure out the "right" behavior
John Reckef654f12011-07-12 16:42:08 -07002417 if (tab.canGoBack()) {
2418 tab.goBack();
John Reck30c714c2010-12-16 17:30:34 -08002419 } else {
John Reckef654f12011-07-12 16:42:08 -07002420 tab.loadUrl(mSettings.getHomePage(), null);
John Reck30c714c2010-12-16 17:30:34 -08002421 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002422 }
2423
2424 void goBackOnePageOrQuit() {
2425 Tab current = mTabControl.getCurrentTab();
2426 if (current == null) {
2427 /*
2428 * Instead of finishing the activity, simply push this to the back
2429 * of the stack and let ActivityManager to choose the foreground
2430 * activity. As BrowserActivity is singleTask, it will be always the
2431 * root of the task. So we can use either true or false for
2432 * moveTaskToBack().
2433 */
2434 mActivity.moveTaskToBack(true);
2435 return;
2436 }
John Reckef654f12011-07-12 16:42:08 -07002437 if (current.canGoBack()) {
2438 current.goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07002439 } else {
2440 // Check to see if we are closing a window that was created by
2441 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002442 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002443 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002444 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002445 // Now we close the other tab
2446 closeTab(current);
2447 } else {
Michael Kolbe28b3472011-08-04 16:54:31 -07002448 if ((current.getAppId() != null) || current.closeOnBack()) {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002449 closeCurrentTab(true);
Michael Kolbe28b3472011-08-04 16:54:31 -07002450 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002451 /*
2452 * Instead of finishing the activity, simply push this to the back
2453 * of the stack and let ActivityManager to choose the foreground
2454 * activity. As BrowserActivity is singleTask, it will be always the
2455 * root of the task. So we can use either true or false for
2456 * moveTaskToBack().
2457 */
2458 mActivity.moveTaskToBack(true);
2459 }
2460 }
2461 }
2462
2463 /**
2464 * Feed the previously stored results strings to the BrowserProvider so that
2465 * the SearchDialog will show them instead of the standard searches.
2466 * @param result String to show on the editable line of the SearchDialog.
2467 */
2468 @Override
2469 public void showVoiceSearchResults(String result) {
2470 ContentProviderClient client = mActivity.getContentResolver()
2471 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2472 ContentProvider prov = client.getLocalContentProvider();
2473 BrowserProvider bp = (BrowserProvider) prov;
2474 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2475 client.release();
2476
2477 Bundle bundle = createGoogleSearchSourceBundle(
2478 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2479 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2480 startSearch(result, false, bundle, false);
2481 }
2482
2483 private void startSearch(String initialQuery, boolean selectInitialQuery,
2484 Bundle appSearchData, boolean globalSearch) {
2485 if (appSearchData == null) {
2486 appSearchData = createGoogleSearchSourceBundle(
2487 GOOGLE_SEARCH_SOURCE_TYPE);
2488 }
2489
2490 SearchEngine searchEngine = mSettings.getSearchEngine();
2491 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2492 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2493 }
2494 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2495 globalSearch);
2496 }
2497
2498 private Bundle createGoogleSearchSourceBundle(String source) {
2499 Bundle bundle = new Bundle();
2500 bundle.putString(Search.SOURCE, source);
2501 return bundle;
2502 }
2503
2504 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002505 * helper method for key handler
2506 * returns the current tab if it can't advance
2507 */
Michael Kolbc831b632011-05-11 09:30:34 -07002508 private Tab getNextTab() {
2509 return mTabControl.getTab(Math.min(mTabControl.getTabCount() - 1,
2510 mTabControl.getCurrentPosition() + 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002511 }
2512
2513 /**
2514 * helper method for key handler
2515 * returns the current tab if it can't advance
2516 */
Michael Kolbc831b632011-05-11 09:30:34 -07002517 private Tab getPrevTab() {
2518 return mTabControl.getTab(Math.max(0,
2519 mTabControl.getCurrentPosition() - 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002520 }
2521
2522 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002523 * handle key events in browser
2524 *
2525 * @param keyCode
2526 * @param event
2527 * @return true if handled, false to pass to super
2528 */
2529 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002530 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002531 // Even if MENU is already held down, we need to call to super to open
2532 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002533 if (!noModifiers
2534 && ((KeyEvent.KEYCODE_MENU == keyCode)
2535 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2536 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002537 mMenuIsDown = true;
2538 return false;
2539 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002540
Cary Clark8ff8c662010-12-29 15:03:05 -05002541 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07002542 Tab tab = getCurrentTab();
2543 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05002544
Cary Clark160bbb92011-01-10 11:17:07 -05002545 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2546 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002547
Michael Kolb8233fac2010-10-26 16:08:53 -07002548 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002549 case KeyEvent.KEYCODE_TAB:
2550 if (event.isCtrlPressed()) {
2551 if (event.isShiftPressed()) {
2552 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002553 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002554 } else {
2555 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002556 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002557 }
2558 return true;
2559 }
2560 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002561 case KeyEvent.KEYCODE_SPACE:
2562 // WebView/WebTextView handle the keys in the KeyDown. As
2563 // the Activity's shortcut keys are only handled when WebView
2564 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002565 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002566 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002567 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002568 pageDown();
2569 }
2570 return true;
2571 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002572 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002573 event.startTracking();
2574 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07002575 case KeyEvent.KEYCODE_FORWARD:
2576 if (!noModifiers) break;
2577 tab.goForward();
2578 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002579 case KeyEvent.KEYCODE_DPAD_LEFT:
2580 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002581 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05002582 return true;
2583 }
2584 break;
2585 case KeyEvent.KEYCODE_DPAD_RIGHT:
2586 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002587 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05002588 return true;
2589 }
2590 break;
2591 case KeyEvent.KEYCODE_A:
2592 if (ctrl) {
2593 webView.selectAll();
2594 return true;
2595 }
2596 break;
Michael Kolba4183062011-01-16 10:43:21 -08002597// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002598 case KeyEvent.KEYCODE_C:
2599 if (ctrl) {
2600 webView.copySelection();
2601 return true;
2602 }
2603 break;
Michael Kolba4183062011-01-16 10:43:21 -08002604// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002605// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002606// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002607// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002608// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002609// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002610// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002611// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002612// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002613// case KeyEvent.KEYCODE_M: // unused
2614// case KeyEvent.KEYCODE_N: // in Chrome: new window
2615// case KeyEvent.KEYCODE_O: // in Chrome: open file
2616// case KeyEvent.KEYCODE_P: // in Chrome: print page
2617// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002618// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002619// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2620 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002621 // we can't use the ctrl/shift flags, they check for
2622 // exclusive use of a modifier
2623 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002624 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002625 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002626 } else {
2627 openTabToHomePage();
2628 }
2629 return true;
2630 }
2631 break;
2632// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2633// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb5ae15bd2011-08-16 17:09:27 -07002634// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002635// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2636// case KeyEvent.KEYCODE_Y: // unused
2637// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002638 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002639 // it is a regular key and webview is not null
2640 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002641 }
2642
John Recke6bf4ab2011-02-24 15:48:05 -08002643 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2644 switch(keyCode) {
2645 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07002646 if (mUi.isWebShowing()) {
John Recke6bf4ab2011-02-24 15:48:05 -08002647 bookmarksOrHistoryPicker(true);
2648 return true;
2649 }
2650 break;
2651 }
2652 return false;
2653 }
2654
Michael Kolb8233fac2010-10-26 16:08:53 -07002655 boolean onKeyUp(int keyCode, KeyEvent event) {
Michael Kolb2814a362011-05-19 15:49:41 -07002656 if (KeyEvent.KEYCODE_MENU == keyCode) {
2657 mMenuIsDown = false;
2658 if (event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002659 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002660 }
2661 }
Cary Clark160bbb92011-01-10 11:17:07 -05002662 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002663 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002664 case KeyEvent.KEYCODE_BACK:
2665 if (event.isTracking() && !event.isCanceled()) {
2666 onBackKey();
2667 return true;
2668 }
2669 break;
2670 }
2671 return false;
2672 }
2673
2674 public boolean isMenuDown() {
2675 return mMenuIsDown;
2676 }
2677
Ben Murdoch8029a772010-11-16 11:58:21 +00002678 public void setupAutoFill(Message message) {
2679 // Open the settings activity at the AutoFill profile fragment so that
2680 // the user can create a new profile. When they return, we will dispatch
2681 // the message so that we can autofill the form using their new profile.
2682 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2683 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2684 AutoFillSettingsFragment.class.getName());
2685 mAutoFillSetupMessage = message;
2686 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2687 }
John Reckb3417f02011-01-14 11:01:05 -08002688
2689 @Override
Narayan Kamath5119edd2011-02-23 15:49:17 +00002690 public void registerDropdownChangeListener(DropdownChangeListener d) {
2691 mUi.registerDropdownChangeListener(d);
2692 }
Michael Kolbfbc579a2011-07-07 15:59:33 -07002693
2694 public boolean onSearchRequested() {
2695 mUi.editUrl(false);
2696 return true;
2697 }
2698
John Reck1cf4b792011-07-26 10:22:22 -07002699 @Override
2700 public boolean shouldCaptureThumbnails() {
2701 return mUi.shouldCaptureThumbnails();
2702 }
2703
Michael Kolbc3af0672011-08-09 10:24:41 -07002704 @Override
2705 public void setBlockEvents(boolean block) {
2706 mBlockEvents = block;
2707 }
2708
2709 public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002710 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002711 }
2712
2713 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002714 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002715 }
2716
2717 public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002718 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002719 }
2720
2721 public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002722 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002723 }
2724
2725 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002726 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002727 }
2728
Michael Kolb8233fac2010-10-26 16:08:53 -07002729}