blob: 05ccdd2820d339226ee92b98a1cc74fa94cc85fa [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;
John Reck68234a92012-04-19 15:27:12 -070020import android.app.AlertDialog;
21import android.app.Dialog;
Michael Kolb8233fac2010-10-26 16:08:53 -070022import android.app.DownloadManager;
John Reck68234a92012-04-19 15:27:12 -070023import android.app.ProgressDialog;
Michael Kolb8233fac2010-10-26 16:08:53 -070024import android.app.SearchManager;
25import android.content.ClipboardManager;
26import android.content.ContentProvider;
27import android.content.ContentProviderClient;
28import android.content.ContentResolver;
John Reckd8c74522011-06-14 08:45:00 -070029import android.content.ContentUris;
Michael Kolb8233fac2010-10-26 16:08:53 -070030import android.content.ContentValues;
31import android.content.Context;
John Reck68234a92012-04-19 15:27:12 -070032import android.content.DialogInterface;
33import android.content.DialogInterface.OnCancelListener;
Michael Kolb8233fac2010-10-26 16:08:53 -070034import android.content.Intent;
35import android.content.pm.PackageManager;
36import android.content.pm.ResolveInfo;
37import android.content.res.Configuration;
John Reck30b065e2011-07-19 10:58:05 -070038import android.content.res.TypedArray;
Leon Scroggins1961ed22010-12-07 15:22:21 -050039import android.database.ContentObserver;
Michael Kolb8233fac2010-10-26 16:08:53 -070040import android.database.Cursor;
41import android.database.sqlite.SQLiteDatabase;
Michael Kolb8233fac2010-10-26 16:08:53 -070042import android.graphics.Bitmap;
43import android.graphics.Canvas;
Michael Kolb8233fac2010-10-26 16:08:53 -070044import android.net.Uri;
45import android.net.http.SslError;
46import android.os.AsyncTask;
47import android.os.Bundle;
George Mount387d45d2011-10-07 15:57:53 -070048import android.os.Environment;
Michael Kolb8233fac2010-10-26 16:08:53 -070049import android.os.Handler;
50import android.os.Message;
51import android.os.PowerManager;
52import android.os.PowerManager.WakeLock;
Ben Murdoch8029a772010-11-16 11:58:21 +000053import android.preference.PreferenceActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -070054import android.provider.Browser;
55import android.provider.BrowserContract;
Michael Kolb8233fac2010-10-26 16:08:53 -070056import android.provider.BrowserContract.Images;
57import android.provider.ContactsContract;
58import android.provider.ContactsContract.Intents.Insert;
Michael Kolbcfa3af52010-12-14 10:36:11 -080059import android.speech.RecognizerIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070060import android.text.TextUtils;
61import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080062import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070063import android.view.ActionMode;
64import android.view.ContextMenu;
65import android.view.ContextMenu.ContextMenuInfo;
66import android.view.Gravity;
67import android.view.KeyEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070068import android.view.Menu;
69import android.view.MenuInflater;
70import android.view.MenuItem;
71import android.view.MenuItem.OnMenuItemClickListener;
Michael Kolbc3af0672011-08-09 10:24:41 -070072import android.view.MotionEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070073import android.view.View;
74import android.webkit.CookieManager;
75import android.webkit.CookieSyncManager;
76import android.webkit.HttpAuthHandler;
George Mount387d45d2011-10-07 15:57:53 -070077import android.webkit.MimeTypeMap;
Michael Kolb8233fac2010-10-26 16:08:53 -070078import android.webkit.SslErrorHandler;
79import android.webkit.ValueCallback;
80import android.webkit.WebChromeClient;
81import android.webkit.WebIconDatabase;
82import android.webkit.WebSettings;
83import android.webkit.WebView;
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +000084import android.webkit.WebViewClassic;
Leon Scrogginsac993842011-02-02 12:54:07 -050085import android.widget.Toast;
Michael Kolb8233fac2010-10-26 16:08:53 -070086
Michael Kolb4bd767d2011-05-27 11:33:55 -070087import com.android.browser.IntentHandler.UrlData;
John Reck2bc80422011-06-30 15:11:49 -070088import com.android.browser.UI.ComboViews;
Michael Kolb4bd767d2011-05-27 11:33:55 -070089import com.android.browser.provider.BrowserProvider;
John Reck1cf4b792011-07-26 10:22:22 -070090import com.android.browser.provider.BrowserProvider2.Thumbnails;
John Reck8cc92352011-07-06 17:41:52 -070091import com.android.browser.provider.SnapshotProvider.Snapshots;
Michael Kolb4bd767d2011-05-27 11:33:55 -070092import com.android.browser.search.SearchEngine;
93import com.android.common.Search;
94
Michael Kolb8233fac2010-10-26 16:08:53 -070095import java.io.ByteArrayOutputStream;
George Mount387d45d2011-10-07 15:57:53 -070096import java.io.File;
97import java.io.FileOutputStream;
98import java.io.IOException;
Michael Kolb8233fac2010-10-26 16:08:53 -070099import java.net.URLEncoder;
George Mount387d45d2011-10-07 15:57:53 -0700100import java.text.DateFormat;
101import java.text.SimpleDateFormat;
John Reck1cf4b792011-07-26 10:22:22 -0700102import java.util.ArrayList;
Michael Kolb8233fac2010-10-26 16:08:53 -0700103import java.util.Calendar;
George Mount387d45d2011-10-07 15:57:53 -0700104import java.util.Date;
Michael Kolb8233fac2010-10-26 16:08:53 -0700105import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -0800106import java.util.List;
John Reck26b18322011-06-21 13:08:58 -0700107import java.util.Map;
Michael Kolb8233fac2010-10-26 16:08:53 -0700108
109/**
110 * Controller for browser
111 */
112public class Controller
113 implements WebViewController, UiController {
114
115 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800116 private static final String SEND_APP_ID_EXTRA =
117 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
Michael Kolba4261fd2011-05-05 11:27:37 -0700118 private static final String INCOGNITO_URI = "browser:incognito";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800119
Michael Kolb8233fac2010-10-26 16:08:53 -0700120
121 // public message ids
122 public final static int LOAD_URL = 1001;
123 public final static int STOP_LOAD = 1002;
124
125 // Message Ids
126 private static final int FOCUS_NODE_HREF = 102;
127 private static final int RELEASE_WAKELOCK = 107;
128
129 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
130
131 private static final int OPEN_BOOKMARKS = 201;
132
133 private static final int EMPTY_MENU = -1;
134
Michael Kolb8233fac2010-10-26 16:08:53 -0700135 // activity requestCode
John Reckd3e4d5b2011-07-13 15:48:43 -0700136 final static int COMBO_VIEW = 1;
Michael Kolb8233fac2010-10-26 16:08:53 -0700137 final static int PREFERENCES_PAGE = 3;
138 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000139 final static int AUTOFILL_SETUP = 5;
140
Michael Kolb8233fac2010-10-26 16:08:53 -0700141 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
142
143 // As the ids are dynamically created, we can't guarantee that they will
144 // be in sequence, so this static array maps ids to a window number.
145 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
146 { R.id.window_one_menu_id, R.id.window_two_menu_id,
147 R.id.window_three_menu_id, R.id.window_four_menu_id,
148 R.id.window_five_menu_id, R.id.window_six_menu_id,
149 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
150
151 // "source" parameter for Google search through search key
152 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
153 // "source" parameter for Google search through simplily type
154 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
155
George Mount387d45d2011-10-07 15:57:53 -0700156 // "no-crash-recovery" parameter in intent to suppress crash recovery
Guang Zhu9e78f512011-05-04 11:45:11 -0700157 final static String NO_CRASH_RECOVERY = "no-crash-recovery";
158
John Reckd7dd9b22011-08-30 09:18:29 -0700159 // A bitmap that is re-used in createScreenshot as scratch space
160 private static Bitmap sThumbnailBitmap;
161
Michael Kolb8233fac2010-10-26 16:08:53 -0700162 private Activity mActivity;
163 private UI mUi;
164 private TabControl mTabControl;
165 private BrowserSettings mSettings;
166 private WebViewFactory mFactory;
167
168 private WakeLock mWakeLock;
169
170 private UrlHandler mUrlHandler;
171 private UploadHandler mUploadHandler;
172 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700173 private PageDialogsHandler mPageDialogsHandler;
174 private NetworkStateHandler mNetworkHandler;
175
Ben Murdoch8029a772010-11-16 11:58:21 +0000176 private Message mAutoFillSetupMessage;
177
Michael Kolb8233fac2010-10-26 16:08:53 -0700178 private boolean mShouldShowErrorConsole;
179
180 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
181
182 // FIXME, temp address onPrepareMenu performance problem.
183 // When we move everything out of view, we should rewrite this.
184 private int mCurrentMenuState = 0;
185 private int mMenuState = R.id.MAIN_MENU;
186 private int mOldMenuState = EMPTY_MENU;
187 private Menu mCachedMenu;
188
Michael Kolb8233fac2010-10-26 16:08:53 -0700189 private boolean mMenuIsDown;
190
191 // For select and find, we keep track of the ActionMode so that
192 // finish() can be called as desired.
193 private ActionMode mActionMode;
194
195 /**
196 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
197 * of whether the configuration has changed. The first onMenuOpened call
198 * after a configuration change is simply a reopening of the same menu
199 * (i.e. mIconView did not change).
200 */
201 private boolean mConfigChanged;
202
203 /**
204 * Keeps track of whether the options menu is open. This is important in
205 * determining whether to show or hide the title bar overlay
206 */
207 private boolean mOptionsMenuOpen;
208
209 /**
210 * Whether or not the options menu is in its bigger, popup menu form. When
211 * true, we want the title bar overlay to be gone. When false, we do not.
212 * Only meaningful if mOptionsMenuOpen is true.
213 */
214 private boolean mExtendedMenuOpen;
215
Michael Kolb8233fac2010-10-26 16:08:53 -0700216 private boolean mActivityPaused = true;
217 private boolean mLoadStopped;
218
219 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500220 // Checks to see when the bookmarks database has changed, and updates the
221 // Tabs' notion of whether they represent bookmarked sites.
222 private ContentObserver mBookmarksObserver;
John Reck847b5322011-04-14 17:02:18 -0700223 private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700224
Michael Kolbc3af0672011-08-09 10:24:41 -0700225 private boolean mBlockEvents;
226
George Mount3636d0a2011-11-21 09:08:21 -0800227 public Controller(Activity browser) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700228 mActivity = browser;
229 mSettings = BrowserSettings.getInstance();
230 mTabControl = new TabControl(this);
231 mSettings.setController(this);
John Reck378a4102011-06-09 16:23:01 -0700232 mCrashRecoveryHandler = CrashRecoveryHandler.initialize(this);
George Mount3636d0a2011-11-21 09:08:21 -0800233 mCrashRecoveryHandler.preloadCrashState();
Michael Kolb14612442011-06-24 13:06:29 -0700234 mFactory = new BrowserWebViewFactory(browser);
Michael Kolb8233fac2010-10-26 16:08:53 -0700235
236 mUrlHandler = new UrlHandler(this);
237 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700238 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
239
Michael Kolb8233fac2010-10-26 16:08:53 -0700240 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500241 mBookmarksObserver = new ContentObserver(mHandler) {
242 @Override
243 public void onChange(boolean selfChange) {
244 int size = mTabControl.getTabCount();
245 for (int i = 0; i < size; i++) {
246 mTabControl.getTab(i).updateBookmarkedStatus();
247 }
248 }
249
250 };
251 browser.getContentResolver().registerContentObserver(
252 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700253
254 mNetworkHandler = new NetworkStateHandler(mActivity, this);
255 // Start watching the default geolocation permissions
256 mSystemAllowGeolocationOrigins =
257 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
258 mSystemAllowGeolocationOrigins.start();
259
John Reckaf262e72011-07-25 13:55:44 -0700260 openIconDatabase();
Michael Kolb8233fac2010-10-26 16:08:53 -0700261 }
262
George Mount3636d0a2011-11-21 09:08:21 -0800263 void start(final Intent intent) {
264 // mCrashRecoverHandler has any previously saved state.
265 mCrashRecoveryHandler.startRecovery(intent);
John Reck847b5322011-04-14 17:02:18 -0700266 }
267
George Mount3636d0a2011-11-21 09:08:21 -0800268 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() {
George Mount3636d0a2011-11-21 09:08:21 -0800296 onPreloginFinished(icicle, intent, currentTabId,
297 restoreIncognitoTabs);
Patrick Scott7d50a932011-02-04 09:27:26 -0500298 }
299 });
300 }
301
Michael Kolbc831b632011-05-11 09:30:34 -0700302 private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId,
George Mount3636d0a2011-11-21 09:08:21 -0800303 boolean restoreIncognitoTabs) {
Michael Kolbc831b632011-05-11 09:30:34 -0700304 if (currentTabId == -1) {
John Reck1cf4b792011-07-26 10:22:22 -0700305 BackgroundHandler.execute(new PruneThumbnails(mActivity, null));
George Mount3636d0a2011-11-21 09:08:21 -0800306 if (intent == null) {
307 // This won't happen under common scenarios. The icicle is
308 // not null, but there aren't any tabs to restore.
309 openTabToHomePage();
Michael Kolb7bcafde2011-05-09 13:55:59 -0700310 } else {
George Mount3636d0a2011-11-21 09:08:21 -0800311 final Bundle extra = intent.getExtras();
312 // Create an initial tab.
313 // If the intent is ACTION_VIEW and data is not null, the Browser is
314 // invoked to view the content by another application. In this case,
315 // the tab will be close when exit.
316 UrlData urlData = IntentHandler.getUrlDataFromIntent(intent);
317 Tab t = null;
318 if (urlData.isEmpty()) {
319 t = openTabToHomePage();
320 } else {
321 t = openTab(urlData);
322 }
323 if (t != null) {
324 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
325 }
326 WebView webView = t.getWebView();
327 if (extra != null) {
328 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
329 if (scale > 0 && scale <= 1000) {
330 webView.setInitialScale(scale);
331 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700332 }
333 }
John Reckd8c74522011-06-14 08:45:00 -0700334 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700335 } else {
Michael Kolbc831b632011-05-11 09:30:34 -0700336 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
Patrick Scott7d50a932011-02-04 09:27:26 -0500337 mUi.needsRestoreAllTabs());
John Reck1cf4b792011-07-26 10:22:22 -0700338 List<Tab> tabs = mTabControl.getTabs();
339 ArrayList<Long> restoredTabs = new ArrayList<Long>(tabs.size());
340 for (Tab t : tabs) {
341 restoredTabs.add(t.getId());
342 }
343 BackgroundHandler.execute(new PruneThumbnails(mActivity, restoredTabs));
John Reck52be4782011-08-26 15:37:29 -0700344 if (tabs.size() == 0) {
345 openTabToHomePage();
346 }
John Reck1cf4b792011-07-26 10:22:22 -0700347 mUi.updateTabs(tabs);
Michael Kolb8233fac2010-10-26 16:08:53 -0700348 // TabControl.restoreState() will create a new tab even if
349 // restoring the state fails.
350 setActiveTab(mTabControl.getCurrentTab());
George Mount3636d0a2011-11-21 09:08:21 -0800351 // Intent is non-null when framework thinks the browser should be
352 // launching with a new intent (icicle is null).
353 if (intent != null) {
John Reck9dd4a412011-10-05 14:55:30 -0700354 mIntentHandler.onNewIntent(intent);
355 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700356 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700357 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700358 String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb8233fac2010-10-26 16:08:53 -0700359 if (jsFlags.trim().length() != 0) {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +0000360 WebViewClassic.fromWebView(getCurrentWebView()).setJsFlags(jsFlags);
Michael Kolb8233fac2010-10-26 16:08:53 -0700361 }
George Mount3636d0a2011-11-21 09:08:21 -0800362 if (intent != null
363 && BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
Michael Kolb315d5022011-10-13 12:47:11 -0700364 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
John Reck439c9a52010-12-14 10:04:39 -0800365 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700366 }
367
John Reck1cf4b792011-07-26 10:22:22 -0700368 private static class PruneThumbnails implements Runnable {
369 private Context mContext;
370 private List<Long> mIds;
371
372 PruneThumbnails(Context context, List<Long> preserveIds) {
373 mContext = context.getApplicationContext();
374 mIds = preserveIds;
375 }
376
377 @Override
378 public void run() {
379 ContentResolver cr = mContext.getContentResolver();
380 if (mIds == null || mIds.size() == 0) {
381 cr.delete(Thumbnails.CONTENT_URI, null, null);
382 } else {
383 int length = mIds.size();
384 StringBuilder where = new StringBuilder();
385 where.append(Thumbnails._ID);
386 where.append(" not in (");
387 for (int i = 0; i < length; i++) {
388 where.append(mIds.get(i));
389 if (i < (length - 1)) {
390 where.append(",");
391 }
392 }
393 where.append(")");
394 cr.delete(Thumbnails.CONTENT_URI, where.toString(), null);
395 }
396 }
397
398 }
399
Michael Kolb1514bb72010-11-22 09:11:48 -0800400 @Override
401 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700402 return mFactory;
403 }
404
405 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800406 public void onSetWebView(Tab tab, WebView view) {
407 mUi.onSetWebView(tab, view);
408 }
409
410 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800411 public void createSubWindow(Tab tab) {
412 endActionMode();
413 WebView mainView = tab.getWebView();
414 WebView subView = mFactory.createWebView((mainView == null)
415 ? false
416 : mainView.isPrivateBrowsingEnabled());
417 mUi.createSubWindow(tab, subView);
418 }
419
420 @Override
Michael Kolb14612442011-06-24 13:06:29 -0700421 public Context getContext() {
422 return mActivity;
423 }
424
425 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700426 public Activity getActivity() {
427 return mActivity;
428 }
429
430 void setUi(UI ui) {
431 mUi = ui;
432 }
433
434 BrowserSettings getSettings() {
435 return mSettings;
436 }
437
438 IntentHandler getIntentHandler() {
439 return mIntentHandler;
440 }
441
442 @Override
443 public UI getUi() {
444 return mUi;
445 }
446
447 int getMaxTabs() {
448 return mActivity.getResources().getInteger(R.integer.max_tabs);
449 }
450
451 @Override
452 public TabControl getTabControl() {
453 return mTabControl;
454 }
455
Michael Kolb1bf23132010-11-19 12:55:12 -0800456 @Override
457 public List<Tab> getTabs() {
458 return mTabControl.getTabs();
459 }
460
John Reckaf262e72011-07-25 13:55:44 -0700461 // Open the icon database.
462 private void openIconDatabase() {
463 // We have to call getInstance on the UI thread
464 final WebIconDatabase instance = WebIconDatabase.getInstance();
465 BackgroundHandler.execute(new Runnable() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000466
John Reckaf262e72011-07-25 13:55:44 -0700467 @Override
468 public void run() {
469 instance.open(mActivity.getDir("icons", 0).getPath());
Michael Kolb8233fac2010-10-26 16:08:53 -0700470 }
John Reckaf262e72011-07-25 13:55:44 -0700471 });
Michael Kolb8233fac2010-10-26 16:08:53 -0700472 }
473
474 private void startHandler() {
475 mHandler = new Handler() {
476
477 @Override
478 public void handleMessage(Message msg) {
479 switch (msg.what) {
480 case OPEN_BOOKMARKS:
Michael Kolb315d5022011-10-13 12:47:11 -0700481 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
Michael Kolb8233fac2010-10-26 16:08:53 -0700482 break;
483 case FOCUS_NODE_HREF:
484 {
485 String url = (String) msg.getData().get("url");
486 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500487 String src = (String) msg.getData().get("src");
488 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700489 if (TextUtils.isEmpty(url)) {
490 break;
491 }
492 HashMap focusNodeMap = (HashMap) msg.obj;
493 WebView view = (WebView) focusNodeMap.get("webview");
494 // Only apply the action if the top window did not change.
495 if (getCurrentTopWebView() != view) {
496 break;
497 }
498 switch (msg.arg1) {
499 case R.id.open_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700500 loadUrlFromContext(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700501 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500502 case R.id.view_image_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700503 loadUrlFromContext(src);
Cary Clark043c2d62010-12-15 11:19:39 -0500504 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500505 case R.id.open_newtab_context_menu_id:
506 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -0700507 openTab(url, parent,
508 !mSettings.openInBackground(), true);
Leon Scroggins026f2542010-11-22 13:26:12 -0500509 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700510 case R.id.copy_link_context_menu_id:
511 copy(url);
512 break;
513 case R.id.save_link_context_menu_id:
514 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500515 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000516 mActivity, url, null, null, null,
517 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700518 break;
519 }
520 break;
521 }
522
523 case LOAD_URL:
John Reck26b18322011-06-21 13:08:58 -0700524 loadUrlFromContext((String) msg.obj);
Michael Kolb8233fac2010-10-26 16:08:53 -0700525 break;
526
527 case STOP_LOAD:
528 stopLoading();
529 break;
530
531 case RELEASE_WAKELOCK:
John Reckf57c0292011-07-21 18:15:39 -0700532 if (mWakeLock != null && mWakeLock.isHeld()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700533 mWakeLock.release();
534 // if we reach here, Browser should be still in the
535 // background loading after WAKELOCK_TIMEOUT (5-min).
536 // To avoid burning the battery, stop loading.
537 mTabControl.stopAllLoading();
538 }
539 break;
540
541 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800542 Tab tab = (Tab) msg.obj;
543 if (tab != null) {
544 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700545 }
546 break;
547 }
548 }
549 };
550
551 }
552
John Reckef654f12011-07-12 16:42:08 -0700553 @Override
Martijn Coenenb2f93552011-06-14 10:48:35 +0200554 public Tab getCurrentTab() {
555 return mTabControl.getCurrentTab();
556 }
557
Michael Kolbba99c5d2010-11-29 14:57:41 -0800558 @Override
559 public void shareCurrentPage() {
560 shareCurrentPage(mTabControl.getCurrentTab());
561 }
562
563 private void shareCurrentPage(Tab tab) {
564 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800565 sharePage(mActivity, tab.getTitle(),
566 tab.getUrl(), tab.getFavicon(),
567 createScreenshot(tab.getWebView(),
568 getDesiredThumbnailWidth(mActivity),
569 getDesiredThumbnailHeight(mActivity)));
570 }
571 }
572
Michael Kolb8233fac2010-10-26 16:08:53 -0700573 /**
574 * Share a page, providing the title, url, favicon, and a screenshot. Uses
575 * an {@link Intent} to launch the Activity chooser.
576 * @param c Context used to launch a new Activity.
577 * @param title Title of the page. Stored in the Intent with
578 * {@link Intent#EXTRA_SUBJECT}
579 * @param url URL of the page. Stored in the Intent with
580 * {@link Intent#EXTRA_TEXT}
581 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
582 * with {@link Browser#EXTRA_SHARE_FAVICON}
583 * @param screenshot Bitmap of a screenshot of the page. Stored in the
584 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
585 */
586 static final void sharePage(Context c, String title, String url,
587 Bitmap favicon, Bitmap screenshot) {
588 Intent send = new Intent(Intent.ACTION_SEND);
589 send.setType("text/plain");
590 send.putExtra(Intent.EXTRA_TEXT, url);
591 send.putExtra(Intent.EXTRA_SUBJECT, title);
592 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
593 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
594 try {
595 c.startActivity(Intent.createChooser(send, c.getString(
596 R.string.choosertitle_sharevia)));
597 } catch(android.content.ActivityNotFoundException ex) {
598 // if no app handles it, do nothing
599 }
600 }
601
602 private void copy(CharSequence text) {
603 ClipboardManager cm = (ClipboardManager) mActivity
604 .getSystemService(Context.CLIPBOARD_SERVICE);
605 cm.setText(text);
606 }
607
608 // lifecycle
609
610 protected void onConfgurationChanged(Configuration config) {
611 mConfigChanged = true;
Michael Kolb18f252f2012-03-06 13:36:20 -0800612 // update the menu in case of a locale change
613 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -0700614 if (mPageDialogsHandler != null) {
615 mPageDialogsHandler.onConfigurationChanged(config);
616 }
617 mUi.onConfigurationChanged(config);
618 }
619
620 @Override
621 public void handleNewIntent(Intent intent) {
Michael Kolb59e232c2011-08-18 17:19:53 -0700622 if (!mUi.isWebShowing()) {
623 mUi.showWeb(false);
624 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700625 mIntentHandler.onNewIntent(intent);
626 }
627
628 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800629 if (mUi.isCustomViewShowing()) {
630 hideCustomView();
631 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700632 if (mActivityPaused) {
633 Log.e(LOGTAG, "BrowserActivity is already paused.");
634 return;
635 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700636 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800637 Tab tab = mTabControl.getCurrentTab();
638 if (tab != null) {
639 tab.pause();
640 if (!pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700641 if (mWakeLock == null) {
642 PowerManager pm = (PowerManager) mActivity
643 .getSystemService(Context.POWER_SERVICE);
644 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
645 }
Michael Kolb70976932010-11-30 11:34:01 -0800646 mWakeLock.acquire();
647 mHandler.sendMessageDelayed(mHandler
648 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
649 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700650 }
651 mUi.onPause();
652 mNetworkHandler.onPause();
653
654 WebView.disablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100655 NfcHandler.unregister(mActivity);
John Reckd7dd9b22011-08-30 09:18:29 -0700656 if (sThumbnailBitmap != null) {
657 sThumbnailBitmap.recycle();
658 sThumbnailBitmap = null;
659 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700660 }
661
John Reck1cf4b792011-07-26 10:22:22 -0700662 void onSaveInstanceState(Bundle outState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700663 // Save all the tabs
George Mount3636d0a2011-11-21 09:08:21 -0800664 Bundle saveState = createSaveState();
665
666 // crash recovery manages all save & restore state
667 mCrashRecoveryHandler.writeState(saveState);
668 mSettings.setLastRunPaused(true);
669 }
670
671 /**
672 * Save the current state to outState. Does not write the state to
673 * disk.
674 * @return Bundle containing the current state of all tabs.
675 */
676 /* package */ Bundle createSaveState() {
677 Bundle saveState = new Bundle();
678 mTabControl.saveState(saveState);
679 if (!saveState.isEmpty()) {
John Reck24f18262011-06-17 14:47:20 -0700680 // Save time so that we know how old incognito tabs (if any) are.
George Mount3636d0a2011-11-21 09:08:21 -0800681 saveState.putSerializable("lastActiveDate", Calendar.getInstance());
John Reck24f18262011-06-17 14:47:20 -0700682 }
George Mount3636d0a2011-11-21 09:08:21 -0800683 return saveState;
Michael Kolb8233fac2010-10-26 16:08:53 -0700684 }
685
686 void onResume() {
687 if (!mActivityPaused) {
688 Log.e(LOGTAG, "BrowserActivity is already resumed.");
689 return;
690 }
George Mount3636d0a2011-11-21 09:08:21 -0800691 mSettings.setLastRunPaused(false);
Michael Kolb8233fac2010-10-26 16:08:53 -0700692 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800693 Tab current = mTabControl.getCurrentTab();
694 if (current != null) {
695 current.resume();
696 resumeWebViewTimers(current);
697 }
John Reckf57c0292011-07-21 18:15:39 -0700698 releaseWakeLock();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200699
Michael Kolb8233fac2010-10-26 16:08:53 -0700700 mUi.onResume();
701 mNetworkHandler.onResume();
702 WebView.enablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100703 NfcHandler.register(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700704 }
705
John Reckf57c0292011-07-21 18:15:39 -0700706 private void releaseWakeLock() {
707 if (mWakeLock != null && mWakeLock.isHeld()) {
708 mHandler.removeMessages(RELEASE_WAKELOCK);
709 mWakeLock.release();
710 }
711 }
712
Michael Kolb70976932010-11-30 11:34:01 -0800713 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800714 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800715 * @param tab guaranteed non-null
716 */
717 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700718 boolean inLoad = tab.inPageLoad();
719 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
720 CookieSyncManager.getInstance().startSync();
721 WebView w = tab.getWebView();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100722 WebViewTimersControl.getInstance().onBrowserActivityResume(w);
Michael Kolb8233fac2010-10-26 16:08:53 -0700723 }
724 }
725
Michael Kolb70976932010-11-30 11:34:01 -0800726 /**
727 * Pause all WebView timers using the WebView of the given tab
728 * @param tab
729 * @return true if the timers are paused or tab is null
730 */
731 private boolean pauseWebViewTimers(Tab tab) {
732 if (tab == null) {
733 return true;
734 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700735 CookieSyncManager.getInstance().stopSync();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100736 WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView());
Michael Kolb8233fac2010-10-26 16:08:53 -0700737 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700738 }
Michael Kolb70976932010-11-30 11:34:01 -0800739 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700740 }
741
742 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800743 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700744 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
745 mUploadHandler = null;
746 }
747 if (mTabControl == null) return;
748 mUi.onDestroy();
749 // Remove the current tab and sub window
750 Tab t = mTabControl.getCurrentTab();
751 if (t != null) {
752 dismissSubWindow(t);
753 removeTab(t);
754 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500755 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700756 // Destroy all the tabs
757 mTabControl.destroy();
758 WebIconDatabase.getInstance().close();
759 // Stop watching the default geolocation permissions
760 mSystemAllowGeolocationOrigins.stop();
761 mSystemAllowGeolocationOrigins = null;
762 }
763
764 protected boolean isActivityPaused() {
765 return mActivityPaused;
766 }
767
768 protected void onLowMemory() {
769 mTabControl.freeMemory();
770 }
771
772 @Override
773 public boolean shouldShowErrorConsole() {
774 return mShouldShowErrorConsole;
775 }
776
777 protected void setShouldShowErrorConsole(boolean show) {
778 if (show == mShouldShowErrorConsole) {
779 // Nothing to do.
780 return;
781 }
782 mShouldShowErrorConsole = show;
783 Tab t = mTabControl.getCurrentTab();
784 if (t == null) {
785 // There is no current tab so we cannot toggle the error console
786 return;
787 }
788 mUi.setShouldShowErrorConsole(t, show);
789 }
790
791 @Override
792 public void stopLoading() {
793 mLoadStopped = true;
794 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700795 WebView w = getCurrentTopWebView();
Michael Kolb778a4882012-04-12 15:27:28 -0700796 if (w != null) {
797 w.stopLoading();
798 mUi.onPageStopped(tab);
799 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700800 }
801
802 boolean didUserStopLoading() {
803 return mLoadStopped;
804 }
805
806 // WebViewController
807
808 @Override
John Reck324d4402011-01-11 16:56:42 -0800809 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700810
811 // We've started to load a new page. If there was a pending message
812 // to save a screenshot then we will now take the new page and save
813 // an incorrect screenshot. Therefore, remove any pending thumbnail
814 // messages from the queue.
815 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800816 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700817
818 // reset sync timer to avoid sync starts during loading a page
819 CookieSyncManager.getInstance().resetSync();
820
821 if (!mNetworkHandler.isNetworkUp()) {
822 view.setNetworkAvailable(false);
823 }
824
825 // when BrowserActivity just starts, onPageStarted may be called before
826 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
827 // to start the timer. As we won't switch tabs while an activity is in
828 // pause state, we can ensure calling resume and pause in pair.
829 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800830 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700831 }
832 mLoadStopped = false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700833 endActionMode();
834
John Reck30c714c2010-12-16 17:30:34 -0800835 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700836
John Reck324d4402011-01-11 16:56:42 -0800837 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700838 // update the bookmark database for favicon
839 maybeUpdateFavicon(tab, null, url, favicon);
840
841 Performance.tracePageStart(url);
842
843 // Performance probe
844 if (false) {
845 Performance.onPageStarted();
846 }
847
848 }
849
850 @Override
John Reck324d4402011-01-11 16:56:42 -0800851 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800852 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700853 // pause the WebView timer and release the wake lock if it is finished
854 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800855 if (mActivityPaused && pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700856 releaseWakeLock();
Michael Kolb8233fac2010-10-26 16:08:53 -0700857 }
Martijn Coenenb2f93552011-06-14 10:48:35 +0200858
Michael Kolb8233fac2010-10-26 16:08:53 -0700859 // Performance probe
860 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800861 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700862 }
863
864 Performance.tracePageFinished();
865 }
866
867 @Override
John Reck30c714c2010-12-16 17:30:34 -0800868 public void onProgressChanged(Tab tab) {
John Reck6c2e2f32011-08-22 13:41:23 -0700869 mCrashRecoveryHandler.backupState();
John Reck30c714c2010-12-16 17:30:34 -0800870 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700871
872 if (newProgress == 100) {
873 CookieSyncManager.getInstance().sync();
874 // onProgressChanged() may continue to be called after the main
875 // frame has finished loading, as any remaining sub frames continue
876 // to load. We'll only get called once though with newProgress as
877 // 100 when everything is loaded. (onPageFinished is called once
878 // when the main frame completes loading regardless of the state of
879 // any sub frames so calls to onProgressChanges may continue after
880 // onPageFinished has executed)
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800881 if (tab.inPageLoad()) {
882 updateInLoadMenuItems(mCachedMenu, tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700883 }
John Reckd9862372012-02-21 15:04:50 -0800884 if (!tab.isPrivateBrowsingEnabled()
885 && !TextUtils.isEmpty(tab.getUrl())
886 && !tab.isSnapshot()) {
887 // Only update the bookmark screenshot if the user did not
888 // cancel the load early and there is not already
889 // a pending update for the tab.
890 if (tab.inForeground() && !didUserStopLoading()
891 || !tab.inForeground()) {
892 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
893 mHandler.sendMessageDelayed(mHandler.obtainMessage(
894 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
895 500);
896 }
897 }
898 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700899 } else {
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800900 if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700901 // onPageFinished may have already been called but a subframe is
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800902 // still loading
903 // updating the progress and
Michael Kolb8233fac2010-10-26 16:08:53 -0700904 // update the menu items.
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800905 updateInLoadMenuItems(mCachedMenu, tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700906 }
907 }
John Reck30c714c2010-12-16 17:30:34 -0800908 mUi.onProgressChanged(tab);
909 }
910
911 @Override
Steve Block2466eff2011-10-03 15:33:09 +0100912 public void onUpdatedSecurityState(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800913 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700914 }
915
916 @Override
917 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800918 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800919 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800920 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700921 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
922 return;
923 }
924 // Update the title in the history database if not in private browsing mode
925 if (!tab.isPrivateBrowsingEnabled()) {
John Reckf57c0292011-07-21 18:15:39 -0700926 DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700927 }
928 }
929
930 @Override
931 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800932 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700933 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
934 }
935
936 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800937 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
938 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700939 }
940
941 @Override
942 public boolean shouldOverrideKeyEvent(KeyEvent event) {
943 if (mMenuIsDown) {
944 // only check shortcut key when MENU is held
945 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
946 event);
947 } else {
948 return false;
949 }
950 }
951
952 @Override
953 public void onUnhandledKeyEvent(KeyEvent event) {
954 if (!isActivityPaused()) {
955 if (event.getAction() == KeyEvent.ACTION_DOWN) {
956 mActivity.onKeyDown(event.getKeyCode(), event);
957 } else {
958 mActivity.onKeyUp(event.getKeyCode(), event);
959 }
960 }
961 }
962
963 @Override
John Reck324d4402011-01-11 16:56:42 -0800964 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700965 // Don't save anything in private browsing mode
966 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800967 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700968
John Reck324d4402011-01-11 16:56:42 -0800969 if (TextUtils.isEmpty(url)
970 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700971 return;
972 }
John Reckf57c0292011-07-21 18:15:39 -0700973 DataController.getInstance(mActivity).updateVisitedHistory(url);
John Reck6c2e2f32011-08-22 13:41:23 -0700974 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -0700975 }
976
977 @Override
978 public void getVisitedHistory(final ValueCallback<String[]> callback) {
979 AsyncTask<Void, Void, String[]> task =
980 new AsyncTask<Void, Void, String[]>() {
981 @Override
982 public String[] doInBackground(Void... unused) {
983 return Browser.getVisitedHistory(mActivity.getContentResolver());
984 }
985 @Override
986 public void onPostExecute(String[] result) {
987 callback.onReceiveValue(result);
988 }
989 };
990 task.execute();
991 }
992
993 @Override
994 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
995 final HttpAuthHandler handler, final String host,
996 final String realm) {
997 String username = null;
998 String password = null;
999
1000 boolean reuseHttpAuthUsernamePassword
1001 = handler.useHttpAuthUsernamePassword();
1002
1003 if (reuseHttpAuthUsernamePassword && view != null) {
1004 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
1005 if (credentials != null && credentials.length == 2) {
1006 username = credentials[0];
1007 password = credentials[1];
1008 }
1009 }
1010
1011 if (username != null && password != null) {
1012 handler.proceed(username, password);
1013 } else {
Ben Murdochfdd37112011-08-05 15:48:14 +01001014 if (tab.inForeground() && !handler.suppressDialog()) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001015 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
1016 } else {
1017 handler.cancel();
1018 }
1019 }
1020 }
1021
1022 @Override
1023 public void onDownloadStart(Tab tab, String url, String userAgent,
1024 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001025 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -05001026 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001027 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
1028 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001029 // This Tab was opened for the sole purpose of downloading a
1030 // file. Remove it.
1031 if (tab == mTabControl.getCurrentTab()) {
1032 // In this case, the Tab is still on top.
1033 goBackOnePageOrQuit();
1034 } else {
1035 // In this case, it is not.
1036 closeTab(tab);
1037 }
1038 }
1039 }
1040
1041 @Override
1042 public Bitmap getDefaultVideoPoster() {
1043 return mUi.getDefaultVideoPoster();
1044 }
1045
1046 @Override
1047 public View getVideoLoadingProgressView() {
1048 return mUi.getVideoLoadingProgressView();
1049 }
1050
1051 @Override
1052 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1053 SslError error) {
1054 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1055 }
1056
Patrick Scott92066772011-03-10 08:46:27 -05001057 @Override
1058 public void showAutoLogin(Tab tab) {
1059 assert tab.inForeground();
1060 // Update the title bar to show the auto-login request.
1061 mUi.showAutoLogin(tab);
1062 }
1063
1064 @Override
1065 public void hideAutoLogin(Tab tab) {
1066 assert tab.inForeground();
1067 mUi.hideAutoLogin(tab);
1068 }
1069
Michael Kolb8233fac2010-10-26 16:08:53 -07001070 // helper method
1071
1072 /*
1073 * Update the favorites icon if the private browsing isn't enabled and the
1074 * icon is valid.
1075 */
1076 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1077 final String url, Bitmap favicon) {
1078 if (favicon == null) {
1079 return;
1080 }
1081 if (!tab.isPrivateBrowsingEnabled()) {
1082 Bookmarks.updateFavicon(mActivity
1083 .getContentResolver(), originalUrl, url, favicon);
1084 }
1085 }
1086
Leon Scroggins4cd97792010-12-03 15:31:56 -05001087 @Override
1088 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001089 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001090 mUi.bookmarkedStatusHasChanged(tab);
1091 }
1092
Michael Kolb8233fac2010-10-26 16:08:53 -07001093 // end WebViewController
1094
1095 protected void pageUp() {
1096 getCurrentTopWebView().pageUp(false);
1097 }
1098
1099 protected void pageDown() {
1100 getCurrentTopWebView().pageDown(false);
1101 }
1102
1103 // callback from phone title bar
1104 public void editUrl() {
1105 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001106 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001107 }
1108
Michael Kolbcfa3af52010-12-14 10:36:11 -08001109 public void startVoiceSearch() {
1110 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1111 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1112 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1113 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1114 mActivity.getComponentName().flattenToString());
1115 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001116 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001117 mActivity.startActivity(intent);
1118 }
1119
Michael Kolb11d19782011-03-20 10:17:40 -07001120 @Override
1121 public void activateVoiceSearchMode(String title, List<String> results) {
1122 mUi.showVoiceTitleBar(title, results);
Michael Kolb8233fac2010-10-26 16:08:53 -07001123 }
1124
1125 public void revertVoiceSearchMode(Tab tab) {
1126 mUi.revertVoiceTitleBar(tab);
1127 }
1128
Michael Kolb736990c2011-03-20 10:01:20 -07001129 public boolean supportsVoiceSearch() {
John Reck35e9dd62011-04-25 09:01:54 -07001130 SearchEngine searchEngine = getSettings().getSearchEngine();
Michael Kolb736990c2011-03-20 10:01:20 -07001131 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1132 }
1133
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001134 public void showCustomView(Tab tab, View view, int requestedOrientation,
Michael Kolb8233fac2010-10-26 16:08:53 -07001135 WebChromeClient.CustomViewCallback callback) {
1136 if (tab.inForeground()) {
1137 if (mUi.isCustomViewShowing()) {
1138 callback.onCustomViewHidden();
1139 return;
1140 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001141 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001142 // Save the menu state and set it to empty while the custom
1143 // view is showing.
1144 mOldMenuState = mMenuState;
1145 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001146 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001147 }
1148 }
1149
1150 @Override
1151 public void hideCustomView() {
1152 if (mUi.isCustomViewShowing()) {
1153 mUi.onHideCustomView();
1154 // Reset the old menu state.
1155 mMenuState = mOldMenuState;
1156 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001157 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001158 }
1159 }
1160
1161 protected void onActivityResult(int requestCode, int resultCode,
1162 Intent intent) {
1163 if (getCurrentTopWebView() == null) return;
1164 switch (requestCode) {
1165 case PREFERENCES_PAGE:
1166 if (resultCode == Activity.RESULT_OK && intent != null) {
1167 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001168 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001169 mTabControl.removeParentChildRelationShips();
1170 }
1171 }
1172 break;
1173 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001174 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001175 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001176 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001177 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001178 case AUTOFILL_SETUP:
1179 // Determine whether a profile was actually set up or not
1180 // and if so, send the message back to the WebTextView to
1181 // fill the form with the new profile.
1182 if (getSettings().getAutoFillProfile() != null) {
1183 mAutoFillSetupMessage.sendToTarget();
1184 mAutoFillSetupMessage = null;
1185 }
1186 break;
John Reckd3e4d5b2011-07-13 15:48:43 -07001187 case COMBO_VIEW:
1188 if (intent == null || resultCode != Activity.RESULT_OK) {
1189 break;
1190 }
John Reck3ba45532011-08-11 16:26:53 -07001191 mUi.showWeb(false);
John Reckd3e4d5b2011-07-13 15:48:43 -07001192 if (Intent.ACTION_VIEW.equals(intent.getAction())) {
1193 Tab t = getCurrentTab();
1194 Uri uri = intent.getData();
1195 loadUrl(t, uri.toString());
1196 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
1197 String[] urls = intent.getStringArrayExtra(
1198 ComboViewActivity.EXTRA_OPEN_ALL);
1199 Tab parent = getCurrentTab();
1200 for (String url : urls) {
1201 parent = openTab(url, parent,
1202 !mSettings.openInBackground(), true);
1203 }
1204 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
1205 long id = intent.getLongExtra(
1206 ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
1207 if (id >= 0) {
1208 createNewSnapshotTab(id, true);
1209 }
1210 }
1211 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001212 default:
1213 break;
1214 }
1215 getCurrentTopWebView().requestFocus();
1216 }
1217
1218 /**
1219 * Open the Go page.
1220 * @param startWithHistory If true, open starting on the history tab.
1221 * Otherwise, start with the bookmarks tab.
1222 */
1223 @Override
Michael Kolb315d5022011-10-13 12:47:11 -07001224 public void bookmarksOrHistoryPicker(ComboViews startView) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001225 if (mTabControl.getCurrentWebView() == null) {
1226 return;
1227 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001228 // clear action mode
1229 if (isInCustomActionMode()) {
1230 endActionMode();
1231 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001232 Bundle extras = new Bundle();
1233 // Disable opening in a new window if we have maxed out the windows
1234 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1235 !mTabControl.canCreateNewTab());
Michael Kolb315d5022011-10-13 12:47:11 -07001236 mUi.showComboView(startView, extras);
Michael Kolb8233fac2010-10-26 16:08:53 -07001237 }
1238
1239 // combo view callbacks
1240
Michael Kolb8233fac2010-10-26 16:08:53 -07001241 // key handling
1242 protected void onBackKey() {
1243 if (!mUi.onBackKey()) {
1244 WebView subwindow = mTabControl.getCurrentSubWindow();
1245 if (subwindow != null) {
1246 if (subwindow.canGoBack()) {
1247 subwindow.goBack();
1248 } else {
1249 dismissSubWindow(mTabControl.getCurrentTab());
1250 }
1251 } else {
1252 goBackOnePageOrQuit();
1253 }
1254 }
1255 }
1256
Michael Kolb4bd767d2011-05-27 11:33:55 -07001257 protected boolean onMenuKey() {
1258 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001259 }
1260
Michael Kolb8233fac2010-10-26 16:08:53 -07001261 // menu handling and state
1262 // TODO: maybe put into separate handler
1263
1264 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckd73c5a22010-12-22 10:22:50 -08001265 if (mMenuState == EMPTY_MENU) {
1266 return false;
1267 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001268 MenuInflater inflater = mActivity.getMenuInflater();
1269 inflater.inflate(R.menu.browser, menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001270 return true;
1271 }
1272
1273 protected void onCreateContextMenu(ContextMenu menu, View v,
1274 ContextMenuInfo menuInfo) {
John Reck0f602f32011-07-07 15:38:43 -07001275 if (v instanceof TitleBar) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001276 return;
1277 }
1278 if (!(v instanceof WebView)) {
1279 return;
1280 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001281 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001282 WebView.HitTestResult result = webview.getHitTestResult();
1283 if (result == null) {
1284 return;
1285 }
1286
1287 int type = result.getType();
1288 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1289 Log.w(LOGTAG,
1290 "We should not show context menu when nothing is touched");
1291 return;
1292 }
1293 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1294 // let TextView handles context menu
1295 return;
1296 }
1297
1298 // Note, http://b/issue?id=1106666 is requesting that
1299 // an inflated menu can be used again. This is not available
1300 // yet, so inflate each time (yuk!)
1301 MenuInflater inflater = mActivity.getMenuInflater();
1302 inflater.inflate(R.menu.browsercontext, menu);
1303
1304 // Show the correct menu group
1305 final String extra = result.getExtra();
Michael Kolbc159c1a2011-12-15 16:06:38 -08001306 if (extra == null) return;
Michael Kolb8233fac2010-10-26 16:08:53 -07001307 menu.setGroupVisible(R.id.PHONE_MENU,
1308 type == WebView.HitTestResult.PHONE_TYPE);
1309 menu.setGroupVisible(R.id.EMAIL_MENU,
1310 type == WebView.HitTestResult.EMAIL_TYPE);
1311 menu.setGroupVisible(R.id.GEO_MENU,
1312 type == WebView.HitTestResult.GEO_TYPE);
1313 menu.setGroupVisible(R.id.IMAGE_MENU,
1314 type == WebView.HitTestResult.IMAGE_TYPE
1315 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1316 menu.setGroupVisible(R.id.ANCHOR_MENU,
1317 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1318 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001319 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1320 || type == WebView.HitTestResult.PHONE_TYPE
1321 || type == WebView.HitTestResult.EMAIL_TYPE
1322 || type == WebView.HitTestResult.GEO_TYPE;
1323 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1324 if (hitText) {
1325 menu.findItem(R.id.select_text_menu_id)
1326 .setOnMenuItemClickListener(new SelectText(webview));
1327 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001328 // Setup custom handling depending on the type
1329 switch (type) {
1330 case WebView.HitTestResult.PHONE_TYPE:
1331 menu.setHeaderTitle(Uri.decode(extra));
1332 menu.findItem(R.id.dial_context_menu_id).setIntent(
1333 new Intent(Intent.ACTION_VIEW, Uri
1334 .parse(WebView.SCHEME_TEL + extra)));
1335 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1336 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1337 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1338 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1339 addIntent);
1340 menu.findItem(R.id.copy_phone_context_menu_id)
1341 .setOnMenuItemClickListener(
1342 new Copy(extra));
1343 break;
1344
1345 case WebView.HitTestResult.EMAIL_TYPE:
1346 menu.setHeaderTitle(extra);
1347 menu.findItem(R.id.email_context_menu_id).setIntent(
1348 new Intent(Intent.ACTION_VIEW, Uri
1349 .parse(WebView.SCHEME_MAILTO + extra)));
1350 menu.findItem(R.id.copy_mail_context_menu_id)
1351 .setOnMenuItemClickListener(
1352 new Copy(extra));
1353 break;
1354
1355 case WebView.HitTestResult.GEO_TYPE:
1356 menu.setHeaderTitle(extra);
1357 menu.findItem(R.id.map_context_menu_id).setIntent(
1358 new Intent(Intent.ACTION_VIEW, Uri
1359 .parse(WebView.SCHEME_GEO
1360 + URLEncoder.encode(extra))));
1361 menu.findItem(R.id.copy_geo_context_menu_id)
1362 .setOnMenuItemClickListener(
1363 new Copy(extra));
1364 break;
1365
1366 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1367 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001368 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001369 // decide whether to show the open link in new tab option
1370 boolean showNewTab = mTabControl.canCreateNewTab();
1371 MenuItem newTabItem
1372 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001373 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001374 ? R.string.contextmenu_openlink_newwindow_background
1375 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001376 newTabItem.setVisible(showNewTab);
1377 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001378 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1379 newTabItem.setOnMenuItemClickListener(
1380 new MenuItem.OnMenuItemClickListener() {
1381 @Override
1382 public boolean onMenuItemClick(MenuItem item) {
1383 final HashMap<String, WebView> hrefMap =
1384 new HashMap<String, WebView>();
1385 hrefMap.put("webview", webview);
1386 final Message msg = mHandler.obtainMessage(
1387 FOCUS_NODE_HREF,
1388 R.id.open_newtab_context_menu_id,
1389 0, hrefMap);
1390 webview.requestFocusNodeHref(msg);
1391 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001392 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001393 });
1394 } else {
1395 newTabItem.setOnMenuItemClickListener(
1396 new MenuItem.OnMenuItemClickListener() {
1397 @Override
1398 public boolean onMenuItemClick(MenuItem item) {
1399 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001400 openTab(extra, parent,
1401 !mSettings.openInBackground(),
1402 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001403 return true;
1404 }
1405 });
1406 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001407 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001408 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1409 break;
1410 }
1411 // otherwise fall through to handle image part
1412 case WebView.HitTestResult.IMAGE_TYPE:
Victoria Lease5987b802012-03-12 13:05:23 -07001413 MenuItem shareItem = menu.findItem(R.id.share_link_context_menu_id);
1414 shareItem.setVisible(type == WebView.HitTestResult.IMAGE_TYPE);
Michael Kolb8233fac2010-10-26 16:08:53 -07001415 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1416 menu.setHeaderTitle(extra);
Victoria Lease5987b802012-03-12 13:05:23 -07001417 shareItem.setOnMenuItemClickListener(
1418 new MenuItem.OnMenuItemClickListener() {
1419 @Override
1420 public boolean onMenuItemClick(MenuItem item) {
1421 sharePage(mActivity, null, extra, null,
1422 null);
1423 return true;
1424 }
1425 }
1426 );
Michael Kolb8233fac2010-10-26 16:08:53 -07001427 }
Michael Kolb3639c4c2011-09-28 15:36:40 -07001428 menu.findItem(R.id.view_image_context_menu_id)
1429 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1430 @Override
1431 public boolean onMenuItemClick(MenuItem item) {
1432 openTab(extra, mTabControl.getCurrentTab(), true, true);
1433 return false;
1434 }
1435 });
Michael Kolb8233fac2010-10-26 16:08:53 -07001436 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001437 setOnMenuItemClickListener(
1438 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001439 menu.findItem(R.id.set_wallpaper_context_menu_id).
1440 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1441 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001442 break;
1443
1444 default:
1445 Log.w(LOGTAG, "We should not get here.");
1446 break;
1447 }
1448 //update the ui
1449 mUi.onContextMenuCreated(menu);
1450 }
1451
1452 /**
1453 * As the menu can be open when loading state changes
1454 * we must manually update the state of the stop/reload menu
1455 * item
1456 */
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001457 private void updateInLoadMenuItems(Menu menu, Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001458 if (menu == null) {
1459 return;
1460 }
1461 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolbb8337132011-11-28 15:07:39 -08001462 MenuItem src = ((tab != null) && tab.inPageLoad()) ?
Michael Kolb8233fac2010-10-26 16:08:53 -07001463 menu.findItem(R.id.stop_menu_id):
1464 menu.findItem(R.id.reload_menu_id);
1465 if (src != null) {
1466 dest.setIcon(src.getIcon());
1467 dest.setTitle(src.getTitle());
1468 }
1469 }
1470
John Reckb3417f02011-01-14 11:01:05 -08001471 boolean onPrepareOptionsMenu(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001472 updateInLoadMenuItems(menu, getCurrentTab());
John Recke1a03a32011-09-14 17:04:16 -07001473 // hold on to the menu reference here; it is used by the page callbacks
1474 // to update the menu based on loading state
1475 mCachedMenu = menu;
Michael Kolb8233fac2010-10-26 16:08:53 -07001476 // Note: setVisible will decide whether an item is visible; while
1477 // setEnabled() will decide whether an item is enabled, which also means
1478 // whether the matching shortcut key will function.
1479 switch (mMenuState) {
1480 case EMPTY_MENU:
1481 if (mCurrentMenuState != mMenuState) {
1482 menu.setGroupVisible(R.id.MAIN_MENU, false);
1483 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1484 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1485 }
1486 break;
1487 default:
1488 if (mCurrentMenuState != mMenuState) {
1489 menu.setGroupVisible(R.id.MAIN_MENU, true);
1490 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1491 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1492 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001493 updateMenuState(getCurrentTab(), menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001494 break;
1495 }
1496 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001497 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001498 }
1499
Michael Kolb4bf79712011-07-14 14:18:12 -07001500 @Override
1501 public void updateMenuState(Tab tab, Menu menu) {
1502 boolean canGoBack = false;
1503 boolean canGoForward = false;
1504 boolean isHome = false;
John Reck42229bc2011-08-19 13:26:43 -07001505 boolean isDesktopUa = false;
John Recke1a03a32011-09-14 17:04:16 -07001506 boolean isLive = false;
Michael Kolb4bf79712011-07-14 14:18:12 -07001507 if (tab != null) {
1508 canGoBack = tab.canGoBack();
1509 canGoForward = tab.canGoForward();
1510 isHome = mSettings.getHomePage().equals(tab.getUrl());
John Reck42229bc2011-08-19 13:26:43 -07001511 isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
John Recke1a03a32011-09-14 17:04:16 -07001512 isLive = !tab.isSnapshot();
Michael Kolb4bf79712011-07-14 14:18:12 -07001513 }
1514 final MenuItem back = menu.findItem(R.id.back_menu_id);
1515 back.setEnabled(canGoBack);
1516
1517 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1518 home.setEnabled(!isHome);
1519
1520 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1521 forward.setEnabled(canGoForward);
1522
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001523 final MenuItem source = menu.findItem(isInLoad() ? R.id.stop_menu_id
1524 : R.id.reload_menu_id);
Michael Kolb4bf79712011-07-14 14:18:12 -07001525 final MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolb7ab75ee2011-07-14 16:36:38 -07001526 if (source != null && dest != null) {
1527 dest.setTitle(source.getTitle());
1528 dest.setIcon(source.getIcon());
1529 }
John Recke1a03a32011-09-14 17:04:16 -07001530 menu.setGroupVisible(R.id.NAV_MENU, isLive);
Michael Kolb4bf79712011-07-14 14:18:12 -07001531
1532 // decide whether to show the share link option
1533 PackageManager pm = mActivity.getPackageManager();
1534 Intent send = new Intent(Intent.ACTION_SEND);
1535 send.setType("text/plain");
1536 ResolveInfo ri = pm.resolveActivity(send,
1537 PackageManager.MATCH_DEFAULT_ONLY);
1538 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1539
1540 boolean isNavDump = mSettings.enableNavDump();
1541 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1542 nav.setVisible(isNavDump);
1543 nav.setEnabled(isNavDump);
1544
1545 boolean showDebugSettings = mSettings.isDebugEnabled();
John Reck42229bc2011-08-19 13:26:43 -07001546 final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
1547 uaSwitcher.setChecked(isDesktopUa);
John Recke1a03a32011-09-14 17:04:16 -07001548 menu.setGroupVisible(R.id.LIVE_MENU, isLive);
1549 menu.setGroupVisible(R.id.SNAPSHOT_MENU, !isLive);
Michael Kolb315d5022011-10-13 12:47:11 -07001550 menu.setGroupVisible(R.id.COMBO_MENU, false);
Michael Kolb4bf79712011-07-14 14:18:12 -07001551
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001552 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001553 }
1554
Michael Kolb8233fac2010-10-26 16:08:53 -07001555 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001556 if (null == getCurrentTopWebView()) {
1557 return false;
1558 }
1559 if (mMenuIsDown) {
1560 // The shortcut action consumes the MENU. Even if it is still down,
1561 // it won't trigger the next shortcut action. In the case of the
1562 // shortcut action triggering a new activity, like Bookmarks, we
1563 // won't get onKeyUp for MENU. So it is important to reset it here.
1564 mMenuIsDown = false;
1565 }
Michael Kolb3ca12752011-07-20 13:52:25 -07001566 if (mUi.onOptionsItemSelected(item)) {
1567 // ui callback handled it
1568 return true;
1569 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001570 switch (item.getItemId()) {
1571 // -- Main menu
1572 case R.id.new_tab_menu_id:
1573 openTabToHomePage();
1574 break;
1575
1576 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001577 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001578 break;
1579
1580 case R.id.goto_menu_id:
1581 editUrl();
1582 break;
1583
1584 case R.id.bookmarks_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001585 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
1586 break;
1587
1588 case R.id.history_menu_id:
1589 bookmarksOrHistoryPicker(ComboViews.History);
1590 break;
1591
1592 case R.id.snapshots_menu_id:
1593 bookmarksOrHistoryPicker(ComboViews.Snapshots);
Michael Kolb8233fac2010-10-26 16:08:53 -07001594 break;
1595
Michael Kolb8233fac2010-10-26 16:08:53 -07001596 case R.id.add_bookmark_menu_id:
Michael Kolb80f75082012-04-10 10:50:06 -07001597 bookmarkCurrentPage();
Michael Kolb8233fac2010-10-26 16:08:53 -07001598 break;
1599
1600 case R.id.stop_reload_menu_id:
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001601 if (isInLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001602 stopLoading();
1603 } else {
1604 getCurrentTopWebView().reload();
1605 }
1606 break;
1607
1608 case R.id.back_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001609 getCurrentTab().goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07001610 break;
1611
1612 case R.id.forward_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001613 getCurrentTab().goForward();
Michael Kolb8233fac2010-10-26 16:08:53 -07001614 break;
1615
1616 case R.id.close_menu_id:
1617 // Close the subwindow if it exists.
1618 if (mTabControl.getCurrentSubWindow() != null) {
1619 dismissSubWindow(mTabControl.getCurrentTab());
1620 break;
1621 }
1622 closeCurrentTab();
1623 break;
1624
1625 case R.id.homepage_menu_id:
1626 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07001627 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07001628 break;
1629
1630 case R.id.preferences_menu_id:
Michael Kolb80f75082012-04-10 10:50:06 -07001631 openPreferences();
Michael Kolb8233fac2010-10-26 16:08:53 -07001632 break;
1633
1634 case R.id.find_menu_id:
Michael Kolbe11b9212012-04-13 13:39:54 -07001635 findOnPage();
Michael Kolb8233fac2010-10-26 16:08:53 -07001636 break;
1637
John Reck2bc80422011-06-30 15:11:49 -07001638 case R.id.save_snapshot_menu_id:
1639 final Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07001640 if (source == null) break;
John Reck68234a92012-04-19 15:27:12 -07001641 new SaveSnapshotTask(source).execute();
Leon Scrogginsac993842011-02-02 12:54:07 -05001642 break;
1643
Michael Kolb8233fac2010-10-26 16:08:53 -07001644 case R.id.page_info_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001645 showPageInfo();
Michael Kolb8233fac2010-10-26 16:08:53 -07001646 break;
1647
John Recke1a03a32011-09-14 17:04:16 -07001648 case R.id.snapshot_go_live:
1649 goLive();
1650 return true;
1651
Michael Kolb8233fac2010-10-26 16:08:53 -07001652 case R.id.share_page_menu_id:
1653 Tab currentTab = mTabControl.getCurrentTab();
1654 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001655 return false;
1656 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001657 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001658 break;
1659
1660 case R.id.dump_nav_menu_id:
1661 getCurrentTopWebView().debugDump();
1662 break;
1663
Michael Kolb8233fac2010-10-26 16:08:53 -07001664 case R.id.zoom_in_menu_id:
1665 getCurrentTopWebView().zoomIn();
1666 break;
1667
1668 case R.id.zoom_out_menu_id:
1669 getCurrentTopWebView().zoomOut();
1670 break;
1671
1672 case R.id.view_downloads_menu_id:
1673 viewDownloads();
1674 break;
1675
John Reck42229bc2011-08-19 13:26:43 -07001676 case R.id.ua_desktop_menu_id:
Michael Kolb80f75082012-04-10 10:50:06 -07001677 toggleUserAgent();
John Reck42229bc2011-08-19 13:26:43 -07001678 break;
1679
Michael Kolb8233fac2010-10-26 16:08:53 -07001680 case R.id.window_one_menu_id:
1681 case R.id.window_two_menu_id:
1682 case R.id.window_three_menu_id:
1683 case R.id.window_four_menu_id:
1684 case R.id.window_five_menu_id:
1685 case R.id.window_six_menu_id:
1686 case R.id.window_seven_menu_id:
1687 case R.id.window_eight_menu_id:
1688 {
1689 int menuid = item.getItemId();
1690 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1691 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1692 Tab desiredTab = mTabControl.getTab(id);
1693 if (desiredTab != null &&
1694 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001695 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001696 }
1697 break;
1698 }
1699 }
1700 }
1701 break;
1702
1703 default:
1704 return false;
1705 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001706 return true;
1707 }
1708
John Reck68234a92012-04-19 15:27:12 -07001709 private class SaveSnapshotTask extends AsyncTask<Void, Void, Long>
1710 implements OnCancelListener {
1711
1712 private Tab mTab;
1713 private Dialog mProgressDialog;
1714 private ContentValues mValues;
1715
1716 private SaveSnapshotTask(Tab tab) {
1717 mTab = tab;
1718 }
1719
1720 @Override
1721 protected void onPreExecute() {
1722 CharSequence message = mActivity.getText(R.string.saving_snapshot);
1723 mProgressDialog = ProgressDialog.show(mActivity, null, message,
1724 true, true, this);
1725 mValues = mTab.createSnapshotValues();
1726 }
1727
1728 @Override
1729 protected Long doInBackground(Void... params) {
1730 if (!mTab.saveViewState(mValues)) {
1731 return null;
1732 }
1733 if (isCancelled()) {
1734 String path = mValues.getAsString(Snapshots.VIEWSTATE_PATH);
1735 File file = mActivity.getFileStreamPath(path);
1736 if (!file.delete()) {
1737 file.deleteOnExit();
1738 }
1739 return null;
1740 }
1741 final ContentResolver cr = mActivity.getContentResolver();
1742 Uri result = cr.insert(Snapshots.CONTENT_URI, mValues);
1743 if (result == null) {
1744 return null;
1745 }
1746 long id = ContentUris.parseId(result);
1747 return id;
1748 }
1749
1750 @Override
1751 protected void onPostExecute(Long id) {
1752 if (isCancelled()) {
1753 return;
1754 }
1755 mProgressDialog.dismiss();
1756 if (id == null) {
1757 Toast.makeText(mActivity, R.string.snapshot_failed,
1758 Toast.LENGTH_SHORT).show();
1759 return;
1760 }
1761 Bundle b = new Bundle();
1762 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
1763 mUi.showComboView(ComboViews.Snapshots, b);
1764 }
1765
1766 @Override
1767 public void onCancel(DialogInterface dialog) {
1768 cancel(true);
1769 }
1770 }
1771
Michael Kolb80f75082012-04-10 10:50:06 -07001772 @Override
1773 public void toggleUserAgent() {
1774 WebView web = getCurrentWebView();
1775 mSettings.toggleDesktopUseragent(web);
1776 web.loadUrl(web.getOriginalUrl());
1777 }
1778
1779 @Override
1780 public void findOnPage() {
1781 getCurrentTopWebView().showFindDialog(null, true);
1782 }
1783
1784 @Override
1785 public void openPreferences() {
1786 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1787 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1788 getCurrentTopWebView().getUrl());
1789 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1790 }
1791
1792 @Override
1793 public void bookmarkCurrentPage() {
1794 Intent bookmarkIntent = createBookmarkCurrentPageIntent(false);
1795 if (bookmarkIntent != null) {
1796 mActivity.startActivity(bookmarkIntent);
1797 }
1798 }
1799
John Recke1a03a32011-09-14 17:04:16 -07001800 private void goLive() {
1801 Tab t = getCurrentTab();
1802 t.loadUrl(t.getUrl(), null);
1803 }
1804
Michael Kolb315d5022011-10-13 12:47:11 -07001805 @Override
1806 public void showPageInfo() {
1807 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
1808 }
1809
Michael Kolb8233fac2010-10-26 16:08:53 -07001810 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001811 // Let the History and Bookmark fragments handle menus they created.
1812 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1813 return false;
1814 }
1815
Michael Kolb8233fac2010-10-26 16:08:53 -07001816 int id = item.getItemId();
1817 boolean result = true;
1818 switch (id) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001819 // -- Browser context menu
1820 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001821 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001822 case R.id.copy_link_context_menu_id:
1823 final WebView webView = getCurrentTopWebView();
1824 if (null == webView) {
1825 result = false;
1826 break;
1827 }
1828 final HashMap<String, WebView> hrefMap =
1829 new HashMap<String, WebView>();
1830 hrefMap.put("webview", webView);
1831 final Message msg = mHandler.obtainMessage(
1832 FOCUS_NODE_HREF, id, 0, hrefMap);
1833 webView.requestFocusNodeHref(msg);
1834 break;
1835
1836 default:
1837 // For other context menus
1838 result = onOptionsItemSelected(item);
1839 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001840 return result;
1841 }
1842
1843 /**
1844 * support programmatically opening the context menu
1845 */
1846 public void openContextMenu(View view) {
1847 mActivity.openContextMenu(view);
1848 }
1849
1850 /**
1851 * programmatically open the options menu
1852 */
1853 public void openOptionsMenu() {
1854 mActivity.openOptionsMenu();
1855 }
1856
1857 public boolean onMenuOpened(int featureId, Menu menu) {
1858 if (mOptionsMenuOpen) {
1859 if (mConfigChanged) {
1860 // We do not need to make any changes to the state of the
1861 // title bar, since the only thing that happened was a
1862 // change in orientation
1863 mConfigChanged = false;
1864 } else {
1865 if (!mExtendedMenuOpen) {
1866 mExtendedMenuOpen = true;
1867 mUi.onExtendedMenuOpened();
1868 } else {
1869 // Switching the menu back to icon view, so show the
1870 // title bar once again.
1871 mExtendedMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001872 mUi.onExtendedMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001873 }
1874 }
1875 } else {
1876 // The options menu is closed, so open it, and show the title
1877 mOptionsMenuOpen = true;
1878 mConfigChanged = false;
1879 mExtendedMenuOpen = false;
1880 mUi.onOptionsMenuOpened();
1881 }
1882 return true;
1883 }
1884
1885 public void onOptionsMenuClosed(Menu menu) {
1886 mOptionsMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001887 mUi.onOptionsMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001888 }
1889
1890 public void onContextMenuClosed(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001891 mUi.onContextMenuClosed(menu, isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001892 }
1893
1894 // Helper method for getting the top window.
1895 @Override
1896 public WebView getCurrentTopWebView() {
1897 return mTabControl.getCurrentTopWebView();
1898 }
1899
1900 @Override
1901 public WebView getCurrentWebView() {
1902 return mTabControl.getCurrentWebView();
1903 }
1904
1905 /*
1906 * This method is called as a result of the user selecting the options
1907 * menu to see the download window. It shows the download window on top of
1908 * the current window.
1909 */
1910 void viewDownloads() {
1911 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1912 mActivity.startActivity(intent);
1913 }
1914
John Reck30b065e2011-07-19 10:58:05 -07001915 int getActionModeHeight() {
1916 TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
1917 new int[] { android.R.attr.actionBarSize });
1918 int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
1919 actionBarSizeTypedArray.recycle();
1920 return size;
1921 }
1922
Michael Kolb8233fac2010-10-26 16:08:53 -07001923 // action mode
1924
1925 void onActionModeStarted(ActionMode mode) {
1926 mUi.onActionModeStarted(mode);
1927 mActionMode = mode;
1928 }
1929
1930 /*
1931 * True if a custom ActionMode (i.e. find or select) is in use.
1932 */
1933 @Override
1934 public boolean isInCustomActionMode() {
1935 return mActionMode != null;
1936 }
1937
1938 /*
1939 * End the current ActionMode.
1940 */
1941 @Override
1942 public void endActionMode() {
1943 if (mActionMode != null) {
1944 mActionMode.finish();
1945 }
1946 }
1947
1948 /*
1949 * Called by find and select when they are finished. Replace title bars
1950 * as necessary.
1951 */
1952 public void onActionModeFinished(ActionMode mode) {
1953 if (!isInCustomActionMode()) return;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001954 mUi.onActionModeFinished(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001955 mActionMode = null;
1956 }
1957
1958 boolean isInLoad() {
Michael Kolbc5b0b2d2011-11-29 16:13:35 -08001959 final Tab tab = getCurrentTab();
1960 return (tab != null) && tab.inPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07001961 }
1962
1963 // bookmark handling
1964
1965 /**
1966 * add the current page as a bookmark to the given folder id
1967 * @param folderId use -1 for the default folder
John Reckd3e4d5b2011-07-13 15:48:43 -07001968 * @param editExisting If true, check to see whether the site is already
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001969 * bookmarked, and if it is, edit that bookmark. If false, and
1970 * the site is already bookmarked, do not attempt to edit the
1971 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001972 */
1973 @Override
John Reckd3e4d5b2011-07-13 15:48:43 -07001974 public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
John Recka60fffa2011-09-06 16:30:29 -07001975 WebView w = getCurrentTopWebView();
1976 if (w == null) {
1977 return null;
1978 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001979 Intent i = new Intent(mActivity,
1980 AddBookmarkPage.class);
Michael Kolb8233fac2010-10-26 16:08:53 -07001981 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1982 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1983 String touchIconUrl = w.getTouchIconUrl();
1984 if (touchIconUrl != null) {
1985 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1986 WebSettings settings = w.getSettings();
1987 if (settings != null) {
1988 i.putExtra(AddBookmarkPage.USER_AGENT,
1989 settings.getUserAgentString());
1990 }
1991 }
1992 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1993 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1994 getDesiredThumbnailHeight(mActivity)));
1995 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07001996 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001997 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1998 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001999 // Put the dialog at the upper right of the screen, covering the
2000 // star on the title bar.
2001 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07002002 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07002003 }
2004
2005 // file chooser
Ben Murdoch8cad4132012-01-11 10:56:43 +00002006 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002007 mUploadHandler = new UploadHandler(this);
Ben Murdoch8cad4132012-01-11 10:56:43 +00002008 mUploadHandler.openFileChooser(uploadMsg, acceptType, capture);
Michael Kolb8233fac2010-10-26 16:08:53 -07002009 }
2010
2011 // thumbnails
2012
2013 /**
2014 * Return the desired width for thumbnail screenshots, which are stored in
2015 * the database, and used on the bookmarks screen.
2016 * @param context Context for finding out the density of the screen.
2017 * @return desired width for thumbnail screenshot.
2018 */
2019 static int getDesiredThumbnailWidth(Context context) {
2020 return context.getResources().getDimensionPixelOffset(
2021 R.dimen.bookmarkThumbnailWidth);
2022 }
2023
2024 /**
2025 * Return the desired height for thumbnail screenshots, which are stored in
2026 * the database, and used on the bookmarks screen.
2027 * @param context Context for finding out the density of the screen.
2028 * @return desired height for thumbnail screenshot.
2029 */
2030 static int getDesiredThumbnailHeight(Context context) {
2031 return context.getResources().getDimensionPixelOffset(
2032 R.dimen.bookmarkThumbnailHeight);
2033 }
2034
John Reck8cc92352011-07-06 17:41:52 -07002035 static Bitmap createScreenshot(WebView view, int width, int height) {
John Reckd7dd9b22011-08-30 09:18:29 -07002036 if (view == null || view.getContentHeight() == 0
2037 || view.getContentWidth() == 0) {
2038 return null;
2039 }
John Reck5c6ac2f2011-01-05 10:18:03 -08002040 // We render to a bitmap 2x the desired size so that we can then
2041 // re-scale it with filtering since canvas.scale doesn't filter
2042 // This helps reduce aliasing at the cost of being slightly blurry
2043 final int filter_scale = 2;
John Reckd7dd9b22011-08-30 09:18:29 -07002044 int scaledWidth = width * filter_scale;
2045 int scaledHeight = height * filter_scale;
2046 if (sThumbnailBitmap == null || sThumbnailBitmap.getWidth() != scaledWidth
2047 || sThumbnailBitmap.getHeight() != scaledHeight) {
2048 if (sThumbnailBitmap != null) {
2049 sThumbnailBitmap.recycle();
2050 sThumbnailBitmap = null;
2051 }
2052 sThumbnailBitmap =
2053 Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.RGB_565);
Michael Kolb8233fac2010-10-26 16:08:53 -07002054 }
John Reckd7dd9b22011-08-30 09:18:29 -07002055 Canvas canvas = new Canvas(sThumbnailBitmap);
2056 int contentWidth = view.getContentWidth();
2057 float overviewScale = scaledWidth / (view.getScale() * contentWidth);
2058 if (view instanceof BrowserWebView) {
2059 int dy = -((BrowserWebView)view).getTitleHeight();
2060 canvas.translate(0, dy * overviewScale);
2061 }
2062
2063 canvas.scale(overviewScale, overviewScale);
2064
2065 if (view instanceof BrowserWebView) {
2066 ((BrowserWebView)view).drawContent(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07002067 } else {
John Reckd7dd9b22011-08-30 09:18:29 -07002068 view.draw(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07002069 }
John Reckd7dd9b22011-08-30 09:18:29 -07002070 Bitmap ret = Bitmap.createScaledBitmap(sThumbnailBitmap,
2071 width, height, true);
Dianne Hackborn43cfe8a2011-08-02 16:59:35 -07002072 canvas.setBitmap(null);
John Reck5c6ac2f2011-01-05 10:18:03 -08002073 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07002074 }
2075
John Reck34ef2672011-02-10 11:30:55 -08002076 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002077 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07002078 // FIXME: Would like to make sure there is actually something to
2079 // draw, but the API for that (WebViewCore.pictureReady()) is not
2080 // currently accessible here.
2081
John Reck34ef2672011-02-10 11:30:55 -08002082 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08002083 if (view == null) {
2084 // Tab was destroyed
2085 return;
2086 }
John Reck34ef2672011-02-10 11:30:55 -08002087 final String url = tab.getUrl();
2088 final String originalUrl = view.getOriginalUrl();
John Reck34ef2672011-02-10 11:30:55 -08002089 if (TextUtils.isEmpty(url)) {
2090 return;
2091 }
2092
2093 // Only update thumbnails for web urls (http(s)://), not for
2094 // about:, javascript:, data:, etc...
2095 // Unless it is a bookmarked site, then always update
2096 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2097 return;
2098 }
2099
Michael Kolb8233fac2010-10-26 16:08:53 -07002100 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2101 getDesiredThumbnailHeight(mActivity));
2102 if (bm == null) {
2103 return;
2104 }
2105
2106 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002107 new AsyncTask<Void, Void, Void>() {
2108 @Override
2109 protected Void doInBackground(Void... unused) {
2110 Cursor cursor = null;
2111 try {
2112 // TODO: Clean this up
2113 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2114 if (cursor != null && cursor.moveToFirst()) {
2115 final ByteArrayOutputStream os =
2116 new ByteArrayOutputStream();
2117 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002118
John Reck34ef2672011-02-10 11:30:55 -08002119 ContentValues values = new ContentValues();
2120 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002121
John Reck34ef2672011-02-10 11:30:55 -08002122 do {
John Reck617fd832011-02-16 14:35:59 -08002123 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002124 cr.update(Images.CONTENT_URI, values, null, null);
2125 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002126 }
John Reck34ef2672011-02-10 11:30:55 -08002127 } catch (IllegalStateException e) {
2128 // Ignore
2129 } finally {
2130 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002131 }
John Reck34ef2672011-02-10 11:30:55 -08002132 return null;
2133 }
2134 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002135 }
2136
2137 private class Copy implements OnMenuItemClickListener {
2138 private CharSequence mText;
2139
2140 public boolean onMenuItemClick(MenuItem item) {
2141 copy(mText);
2142 return true;
2143 }
2144
2145 public Copy(CharSequence toCopy) {
2146 mText = toCopy;
2147 }
2148 }
2149
Leon Scroggins63c02662010-11-18 15:16:27 -05002150 private static class Download implements OnMenuItemClickListener {
2151 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002152 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002153 private boolean mPrivateBrowsing;
George Mount387d45d2011-10-07 15:57:53 -07002154 private static final String FALLBACK_EXTENSION = "dat";
2155 private static final String IMAGE_BASE_FORMAT = "yyyy-MM-dd-HH-mm-ss-";
Michael Kolb8233fac2010-10-26 16:08:53 -07002156
2157 public boolean onMenuItemClick(MenuItem item) {
George Mount387d45d2011-10-07 15:57:53 -07002158 if (DataUri.isDataUri(mText)) {
2159 saveDataUri();
2160 } else {
2161 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
2162 null, null, mPrivateBrowsing);
2163 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002164 return true;
2165 }
2166
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002167 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002168 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002169 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002170 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002171 }
George Mount387d45d2011-10-07 15:57:53 -07002172
2173 /**
2174 * Treats mText as a data URI and writes its contents to a file
2175 * based on the current time.
2176 */
2177 private void saveDataUri() {
2178 FileOutputStream outputStream = null;
2179 try {
2180 DataUri uri = new DataUri(mText);
2181 File target = getTarget(uri);
2182 outputStream = new FileOutputStream(target);
2183 outputStream.write(uri.getData());
2184 final DownloadManager manager =
2185 (DownloadManager) mActivity.getSystemService(Context.DOWNLOAD_SERVICE);
2186 manager.addCompletedDownload(target.getName(),
2187 mActivity.getTitle().toString(), false,
2188 uri.getMimeType(), target.getAbsolutePath(),
George Mount7501bf42011-11-17 11:17:03 -08002189 (long)uri.getData().length, true);
George Mount387d45d2011-10-07 15:57:53 -07002190 } catch (IOException e) {
2191 Log.e(LOGTAG, "Could not save data URL");
2192 } finally {
2193 if (outputStream != null) {
2194 try {
2195 outputStream.close();
2196 } catch (IOException e) {
2197 // ignore close errors
2198 }
2199 }
2200 }
2201 }
2202
2203 /**
2204 * Creates a File based on the current time stamp and uses
2205 * the mime type of the DataUri to get the extension.
2206 */
2207 private File getTarget(DataUri uri) throws IOException {
2208 File dir = mActivity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
2209 DateFormat format = new SimpleDateFormat(IMAGE_BASE_FORMAT);
2210 String nameBase = format.format(new Date());
2211 String mimeType = uri.getMimeType();
2212 MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
2213 String extension = mimeTypeMap.getExtensionFromMimeType(mimeType);
2214 if (extension == null) {
2215 Log.w(LOGTAG, "Unknown mime type in data URI" + mimeType);
2216 extension = FALLBACK_EXTENSION;
2217 }
2218 extension = "." + extension; // createTempFile needs the '.'
2219 File targetFile = File.createTempFile(nameBase, extension, dir);
2220 return targetFile;
2221 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002222 }
2223
Cary Clark8974d282010-11-22 10:46:05 -05002224 private static class SelectText implements OnMenuItemClickListener {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002225 private WebViewClassic mWebView;
Cary Clark8974d282010-11-22 10:46:05 -05002226
2227 public boolean onMenuItemClick(MenuItem item) {
2228 if (mWebView != null) {
2229 return mWebView.selectText();
2230 }
2231 return false;
2232 }
2233
2234 public SelectText(WebView webView) {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002235 mWebView = WebViewClassic.fromWebView(webView);
Cary Clark8974d282010-11-22 10:46:05 -05002236 }
2237
2238 }
2239
Michael Kolb8233fac2010-10-26 16:08:53 -07002240 /********************** TODO: UI stuff *****************************/
2241
2242 // these methods have been copied, they still need to be cleaned up
2243
2244 /****************** tabs ***************************************************/
2245
2246 // basic tab interactions:
2247
2248 // it is assumed that tabcontrol already knows about the tab
2249 protected void addTab(Tab tab) {
2250 mUi.addTab(tab);
2251 }
2252
2253 protected void removeTab(Tab tab) {
2254 mUi.removeTab(tab);
2255 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002256 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002257 }
2258
Michael Kolbf2055602011-04-09 17:20:03 -07002259 @Override
2260 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002261 // monkey protection against delayed start
2262 if (tab != null) {
2263 mTabControl.setCurrentTab(tab);
2264 // the tab is guaranteed to have a webview after setCurrentTab
2265 mUi.setActiveTab(tab);
2266 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002267 }
2268
John Reck8bcafc12011-08-29 16:43:02 -07002269 protected void closeEmptyTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002270 Tab current = mTabControl.getCurrentTab();
2271 if (current != null
2272 && current.getWebView().copyBackForwardList().getSize() == 0) {
John Reck8bcafc12011-08-29 16:43:02 -07002273 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002274 }
2275 }
2276
John Reck26b18322011-06-21 13:08:58 -07002277 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002278 // Dismiss the subwindow if applicable.
2279 dismissSubWindow(appTab);
2280 // Since we might kill the WebView, remove it from the
2281 // content view first.
2282 mUi.detachTab(appTab);
2283 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002284 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002285 // TODO: analyze why the remove and add are necessary
2286 mUi.attachTab(appTab);
2287 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002288 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002289 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002290 } else {
2291 // If the tab was the current tab, we have to attach
2292 // it to the view system again.
2293 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002294 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002295 }
2296 }
2297
2298 // Remove the sub window if it exists. Also called by TabControl when the
2299 // user clicks the 'X' to dismiss a sub window.
2300 public void dismissSubWindow(Tab tab) {
2301 removeSubWindow(tab);
2302 // dismiss the subwindow. This will destroy the WebView.
2303 tab.dismissSubWindow();
Michael Kolbe8c97572011-11-21 14:03:56 -08002304 WebView wv = getCurrentTopWebView();
2305 if (wv != null) {
2306 wv.requestFocus();
2307 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002308 }
2309
2310 @Override
2311 public void removeSubWindow(Tab t) {
2312 if (t.getSubWebView() != null) {
2313 mUi.removeSubWindow(t.getSubViewContainer());
2314 }
2315 }
2316
2317 @Override
2318 public void attachSubWindow(Tab tab) {
2319 if (tab.getSubWebView() != null) {
2320 mUi.attachSubWindow(tab.getSubViewContainer());
2321 getCurrentTopWebView().requestFocus();
2322 }
2323 }
2324
Mathew Inwood29721c22011-06-29 17:55:24 +01002325 private Tab showPreloadedTab(final UrlData urlData) {
2326 if (!urlData.isPreloaded()) {
2327 return null;
2328 }
2329 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2330 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2331 if (sbQuery != null) {
Mathew Inwood9ad1eac2011-09-15 11:29:50 +01002332 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002333 // Could not submit query. Fallback to regular tab creation
2334 tabControl.destroy();
2335 return null;
2336 }
2337 }
Michael Kolbff6a7482011-07-26 16:37:15 -07002338 // check tab count and make room for new tab
2339 if (!mTabControl.canCreateNewTab()) {
2340 Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
2341 if (leastUsed != null) {
2342 closeTab(leastUsed);
2343 }
2344 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002345 Tab t = tabControl.getTab();
Mathew Inwoode09305e2011-09-02 12:03:26 +01002346 t.refreshIdAfterPreload();
Mathew Inwood29721c22011-06-29 17:55:24 +01002347 mTabControl.addPreloadedTab(t);
2348 addTab(t);
2349 setActiveTab(t);
2350 return t;
2351 }
2352
Michael Kolb7bcafde2011-05-09 13:55:59 -07002353 // open a non inconito tab with the given url data
2354 // and set as active tab
2355 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002356 Tab tab = showPreloadedTab(urlData);
2357 if (tab == null) {
2358 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002359 if ((tab != null) && !urlData.isEmpty()) {
2360 loadUrlDataIn(tab, urlData);
2361 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002362 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002363 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002364 }
2365
Michael Kolb843510f2010-12-09 10:51:49 -08002366 @Override
2367 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002368 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002369 }
2370
Michael Kolb8233fac2010-10-26 16:08:53 -07002371 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002372 public Tab openIncognitoTab() {
2373 return openTab(INCOGNITO_URI, true, true, false);
2374 }
2375
2376 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002377 public Tab openTab(String url, boolean incognito, boolean setActive,
2378 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002379 return openTab(url, incognito, setActive, useCurrent, null);
2380 }
2381
2382 @Override
2383 public Tab openTab(String url, Tab parent, boolean setActive,
2384 boolean useCurrent) {
2385 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2386 setActive, useCurrent, parent);
2387 }
2388
2389 public Tab openTab(String url, boolean incognito, boolean setActive,
2390 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002391 Tab tab = createNewTab(incognito, setActive, useCurrent);
2392 if (tab != null) {
John Reck5949c662011-05-27 09:52:29 -07002393 if (parent != null && parent != tab) {
2394 parent.addChildTab(tab);
2395 }
Michael Kolb519d2282011-05-09 17:03:19 -07002396 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002397 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002398 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002399 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002400 return tab;
2401 }
2402
2403 // this method will attempt to create a new tab
2404 // incognito: private browsing tab
2405 // setActive: ste tab as current tab
2406 // useCurrent: if no new tab can be created, return current tab
2407 private Tab createNewTab(boolean incognito, boolean setActive,
2408 boolean useCurrent) {
2409 Tab tab = null;
2410 if (mTabControl.canCreateNewTab()) {
2411 tab = mTabControl.createNewTab(incognito);
2412 addTab(tab);
2413 if (setActive) {
2414 setActiveTab(tab);
2415 }
2416 } else {
2417 if (useCurrent) {
2418 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002419 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002420 } else {
2421 mUi.showMaxTabsWarning();
2422 }
2423 }
2424 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002425 }
2426
John Reck2bc80422011-06-30 15:11:49 -07002427 @Override
2428 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2429 SnapshotTab tab = null;
2430 if (mTabControl.canCreateNewTab()) {
2431 tab = mTabControl.createSnapshotTab(snapshotId);
2432 addTab(tab);
2433 if (setActive) {
2434 setActiveTab(tab);
2435 }
2436 } else {
2437 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07002438 }
2439 return tab;
2440 }
2441
Michael Kolb8233fac2010-10-26 16:08:53 -07002442 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002443 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002444 * @return boolean True if we successfully switched to a different tab. If
2445 * the indexth tab is null, or if that tab is the same as
2446 * the current one, return false.
2447 */
2448 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002449 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002450 Tab currentTab = mTabControl.getCurrentTab();
2451 if (tab == null || tab == currentTab) {
2452 return false;
2453 }
2454 setActiveTab(tab);
2455 return true;
2456 }
2457
2458 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002459 public void closeCurrentTab() {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002460 closeCurrentTab(false);
2461 }
2462
2463 protected void closeCurrentTab(boolean andQuit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002464 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07002465 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07002466 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08002467 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002468 return;
2469 }
Michael Kolbc831b632011-05-11 09:30:34 -07002470 final Tab current = mTabControl.getCurrentTab();
2471 final int pos = mTabControl.getCurrentPosition();
2472 Tab newTab = current.getParent();
2473 if (newTab == null) {
2474 newTab = mTabControl.getTab(pos + 1);
2475 if (newTab == null) {
2476 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002477 }
2478 }
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002479 if (andQuit) {
2480 mTabControl.setCurrentTab(newTab);
2481 closeTab(current);
2482 } else if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002483 // Close window
2484 closeTab(current);
2485 }
2486 }
2487
2488 /**
2489 * Close the tab, remove its associated title bar, and adjust mTabControl's
2490 * current tab to a valid value.
2491 */
2492 @Override
2493 public void closeTab(Tab tab) {
John Reck28263772011-10-11 17:13:42 -07002494 if (tab == mTabControl.getCurrentTab()) {
2495 closeCurrentTab();
2496 } else {
2497 removeTab(tab);
2498 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002499 }
2500
Michael Kolb8233fac2010-10-26 16:08:53 -07002501 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07002502 protected void loadUrlFromContext(String url) {
2503 Tab tab = getCurrentTab();
2504 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002505 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07002506 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002507 url = UrlUtils.smartUrlFilter(url);
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002508 if (!WebViewClassic.fromWebView(view).getWebViewClient().
2509 shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07002510 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07002511 }
2512 }
2513 }
2514
2515 /**
2516 * Load the URL into the given WebView and update the title bar
2517 * to reflect the new load. Call this instead of WebView.loadUrl
2518 * directly.
2519 * @param view The WebView used to load url.
2520 * @param url The URL to load.
2521 */
John Reck71e51422011-07-01 16:49:28 -07002522 @Override
2523 public void loadUrl(Tab tab, String url) {
John Reck26b18322011-06-21 13:08:58 -07002524 loadUrl(tab, url, null);
2525 }
2526
2527 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
2528 if (tab != null) {
2529 dismissSubWindow(tab);
2530 tab.loadUrl(url, headers);
Michael Kolba53c9892011-10-05 13:31:40 -07002531 mUi.onProgressChanged(tab);
John Reck26b18322011-06-21 13:08:58 -07002532 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002533 }
2534
2535 /**
2536 * Load UrlData into a Tab and update the title bar to reflect the new
2537 * load. Call this instead of UrlData.loadIn directly.
2538 * @param t The Tab used to load.
2539 * @param data The UrlData being loaded.
2540 */
2541 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07002542 if (data != null) {
2543 if (data.mVoiceIntent != null) {
2544 t.activateVoiceSearchMode(data.mVoiceIntent);
Michael Kolb14612442011-06-24 13:06:29 -07002545 } else if (data.isPreloaded()) {
2546 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07002547 } else {
2548 loadUrl(t, data.mUrl, data.mHeaders);
2549 }
2550 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002551 }
2552
John Reck30c714c2010-12-16 17:30:34 -08002553 @Override
2554 public void onUserCanceledSsl(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08002555 // TODO: Figure out the "right" behavior
John Reckef654f12011-07-12 16:42:08 -07002556 if (tab.canGoBack()) {
2557 tab.goBack();
John Reck30c714c2010-12-16 17:30:34 -08002558 } else {
John Reckef654f12011-07-12 16:42:08 -07002559 tab.loadUrl(mSettings.getHomePage(), null);
John Reck30c714c2010-12-16 17:30:34 -08002560 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002561 }
2562
2563 void goBackOnePageOrQuit() {
2564 Tab current = mTabControl.getCurrentTab();
2565 if (current == null) {
2566 /*
2567 * Instead of finishing the activity, simply push this to the back
2568 * of the stack and let ActivityManager to choose the foreground
2569 * activity. As BrowserActivity is singleTask, it will be always the
2570 * root of the task. So we can use either true or false for
2571 * moveTaskToBack().
2572 */
2573 mActivity.moveTaskToBack(true);
2574 return;
2575 }
John Reckef654f12011-07-12 16:42:08 -07002576 if (current.canGoBack()) {
2577 current.goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07002578 } else {
2579 // Check to see if we are closing a window that was created by
2580 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002581 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002582 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002583 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002584 // Now we close the other tab
2585 closeTab(current);
2586 } else {
Michael Kolbe28b3472011-08-04 16:54:31 -07002587 if ((current.getAppId() != null) || current.closeOnBack()) {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002588 closeCurrentTab(true);
Michael Kolbe28b3472011-08-04 16:54:31 -07002589 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002590 /*
2591 * Instead of finishing the activity, simply push this to the back
2592 * of the stack and let ActivityManager to choose the foreground
2593 * activity. As BrowserActivity is singleTask, it will be always the
2594 * root of the task. So we can use either true or false for
2595 * moveTaskToBack().
2596 */
2597 mActivity.moveTaskToBack(true);
2598 }
2599 }
2600 }
2601
2602 /**
2603 * Feed the previously stored results strings to the BrowserProvider so that
2604 * the SearchDialog will show them instead of the standard searches.
2605 * @param result String to show on the editable line of the SearchDialog.
2606 */
2607 @Override
2608 public void showVoiceSearchResults(String result) {
2609 ContentProviderClient client = mActivity.getContentResolver()
2610 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2611 ContentProvider prov = client.getLocalContentProvider();
2612 BrowserProvider bp = (BrowserProvider) prov;
2613 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2614 client.release();
2615
2616 Bundle bundle = createGoogleSearchSourceBundle(
2617 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2618 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2619 startSearch(result, false, bundle, false);
2620 }
2621
2622 private void startSearch(String initialQuery, boolean selectInitialQuery,
2623 Bundle appSearchData, boolean globalSearch) {
2624 if (appSearchData == null) {
2625 appSearchData = createGoogleSearchSourceBundle(
2626 GOOGLE_SEARCH_SOURCE_TYPE);
2627 }
2628
2629 SearchEngine searchEngine = mSettings.getSearchEngine();
2630 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2631 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2632 }
2633 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2634 globalSearch);
2635 }
2636
2637 private Bundle createGoogleSearchSourceBundle(String source) {
2638 Bundle bundle = new Bundle();
2639 bundle.putString(Search.SOURCE, source);
2640 return bundle;
2641 }
2642
2643 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002644 * helper method for key handler
2645 * returns the current tab if it can't advance
2646 */
Michael Kolbc831b632011-05-11 09:30:34 -07002647 private Tab getNextTab() {
Michael Kolbf5261da2011-12-15 15:07:35 -08002648 int pos = mTabControl.getCurrentPosition() + 1;
2649 if (pos >= mTabControl.getTabCount()) {
2650 pos = 0;
2651 }
2652 return mTabControl.getTab(pos);
Michael Kolb0035fad2011-03-14 13:25:28 -07002653 }
2654
2655 /**
2656 * helper method for key handler
2657 * returns the current tab if it can't advance
2658 */
Michael Kolbc831b632011-05-11 09:30:34 -07002659 private Tab getPrevTab() {
Michael Kolbf5261da2011-12-15 15:07:35 -08002660 int pos = mTabControl.getCurrentPosition() - 1;
2661 if ( pos < 0) {
2662 pos = mTabControl.getTabCount() - 1;
2663 }
2664 return mTabControl.getTab(pos);
Michael Kolb0035fad2011-03-14 13:25:28 -07002665 }
2666
John Reckbcef87f2012-02-03 14:58:34 -08002667 boolean isMenuOrCtrlKey(int keyCode) {
2668 return (KeyEvent.KEYCODE_MENU == keyCode)
2669 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2670 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode);
2671 }
2672
Michael Kolb0035fad2011-03-14 13:25:28 -07002673 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002674 * handle key events in browser
2675 *
2676 * @param keyCode
2677 * @param event
2678 * @return true if handled, false to pass to super
2679 */
2680 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002681 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002682 // Even if MENU is already held down, we need to call to super to open
2683 // the IME on long press.
John Reckbcef87f2012-02-03 14:58:34 -08002684 if (!noModifiers && isMenuOrCtrlKey(keyCode)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002685 mMenuIsDown = true;
2686 return false;
2687 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002688
Cary Clark8ff8c662010-12-29 15:03:05 -05002689 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07002690 Tab tab = getCurrentTab();
2691 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05002692
Cary Clark160bbb92011-01-10 11:17:07 -05002693 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2694 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002695
Michael Kolb8233fac2010-10-26 16:08:53 -07002696 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002697 case KeyEvent.KEYCODE_TAB:
2698 if (event.isCtrlPressed()) {
2699 if (event.isShiftPressed()) {
2700 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002701 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002702 } else {
2703 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002704 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002705 }
2706 return true;
2707 }
2708 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002709 case KeyEvent.KEYCODE_SPACE:
2710 // WebView/WebTextView handle the keys in the KeyDown. As
2711 // the Activity's shortcut keys are only handled when WebView
2712 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002713 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002714 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002715 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002716 pageDown();
2717 }
2718 return true;
2719 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002720 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002721 event.startTracking();
2722 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07002723 case KeyEvent.KEYCODE_FORWARD:
2724 if (!noModifiers) break;
2725 tab.goForward();
2726 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002727 case KeyEvent.KEYCODE_DPAD_LEFT:
2728 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002729 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05002730 return true;
2731 }
2732 break;
2733 case KeyEvent.KEYCODE_DPAD_RIGHT:
2734 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002735 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05002736 return true;
2737 }
2738 break;
2739 case KeyEvent.KEYCODE_A:
2740 if (ctrl) {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002741 WebViewClassic.fromWebView(webView).selectAll();
Cary Clark8ff8c662010-12-29 15:03:05 -05002742 return true;
2743 }
2744 break;
Michael Kolba4183062011-01-16 10:43:21 -08002745// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002746 case KeyEvent.KEYCODE_C:
2747 if (ctrl) {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002748 WebViewClassic.fromWebView(webView).copySelection();
Cary Clark8ff8c662010-12-29 15:03:05 -05002749 return true;
2750 }
2751 break;
Michael Kolba4183062011-01-16 10:43:21 -08002752// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002753// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002754// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002755// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002756// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002757// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002758// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002759// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002760// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002761// case KeyEvent.KEYCODE_M: // unused
2762// case KeyEvent.KEYCODE_N: // in Chrome: new window
2763// case KeyEvent.KEYCODE_O: // in Chrome: open file
2764// case KeyEvent.KEYCODE_P: // in Chrome: print page
2765// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002766// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002767// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2768 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002769 // we can't use the ctrl/shift flags, they check for
2770 // exclusive use of a modifier
2771 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002772 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002773 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002774 } else {
2775 openTabToHomePage();
2776 }
2777 return true;
2778 }
2779 break;
2780// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2781// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb5ae15bd2011-08-16 17:09:27 -07002782// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002783// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2784// case KeyEvent.KEYCODE_Y: // unused
2785// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002786 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002787 // it is a regular key and webview is not null
2788 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002789 }
2790
John Recke6bf4ab2011-02-24 15:48:05 -08002791 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2792 switch(keyCode) {
2793 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07002794 if (mUi.isWebShowing()) {
Michael Kolb315d5022011-10-13 12:47:11 -07002795 bookmarksOrHistoryPicker(ComboViews.History);
John Recke6bf4ab2011-02-24 15:48:05 -08002796 return true;
2797 }
2798 break;
2799 }
2800 return false;
2801 }
2802
Michael Kolb8233fac2010-10-26 16:08:53 -07002803 boolean onKeyUp(int keyCode, KeyEvent event) {
John Reckbcef87f2012-02-03 14:58:34 -08002804 if (isMenuOrCtrlKey(keyCode)) {
Michael Kolb2814a362011-05-19 15:49:41 -07002805 mMenuIsDown = false;
John Reckbcef87f2012-02-03 14:58:34 -08002806 if (KeyEvent.KEYCODE_MENU == keyCode
2807 && event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002808 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002809 }
2810 }
Cary Clark160bbb92011-01-10 11:17:07 -05002811 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002812 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002813 case KeyEvent.KEYCODE_BACK:
2814 if (event.isTracking() && !event.isCanceled()) {
2815 onBackKey();
2816 return true;
2817 }
2818 break;
2819 }
2820 return false;
2821 }
2822
2823 public boolean isMenuDown() {
2824 return mMenuIsDown;
2825 }
2826
Ben Murdoch8029a772010-11-16 11:58:21 +00002827 public void setupAutoFill(Message message) {
2828 // Open the settings activity at the AutoFill profile fragment so that
2829 // the user can create a new profile. When they return, we will dispatch
2830 // the message so that we can autofill the form using their new profile.
2831 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2832 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2833 AutoFillSettingsFragment.class.getName());
2834 mAutoFillSetupMessage = message;
2835 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2836 }
John Reckb3417f02011-01-14 11:01:05 -08002837
Michael Kolbfbc579a2011-07-07 15:59:33 -07002838 public boolean onSearchRequested() {
2839 mUi.editUrl(false);
2840 return true;
2841 }
2842
John Reck1cf4b792011-07-26 10:22:22 -07002843 @Override
2844 public boolean shouldCaptureThumbnails() {
2845 return mUi.shouldCaptureThumbnails();
2846 }
2847
Michael Kolbc3af0672011-08-09 10:24:41 -07002848 @Override
2849 public void setBlockEvents(boolean block) {
2850 mBlockEvents = block;
2851 }
2852
2853 public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002854 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002855 }
2856
2857 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002858 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002859 }
2860
2861 public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002862 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002863 }
2864
2865 public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002866 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002867 }
2868
2869 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002870 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002871 }
2872
Michael Kolb8233fac2010-10-26 16:08:53 -07002873}