blob: fb535ba49f03cd38aaeaae5d02cb8c66570d73f2 [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.Dialog;
Michael Kolb8233fac2010-10-26 16:08:53 -070021import android.app.DownloadManager;
John Reck68234a92012-04-19 15:27:12 -070022import android.app.ProgressDialog;
Michael Kolb8233fac2010-10-26 16:08:53 -070023import android.app.SearchManager;
24import android.content.ClipboardManager;
25import android.content.ContentProvider;
26import android.content.ContentProviderClient;
27import android.content.ContentResolver;
John Reckd8c74522011-06-14 08:45:00 -070028import android.content.ContentUris;
Michael Kolb8233fac2010-10-26 16:08:53 -070029import android.content.ContentValues;
30import android.content.Context;
John Reck68234a92012-04-19 15:27:12 -070031import android.content.DialogInterface;
32import android.content.DialogInterface.OnCancelListener;
Michael Kolb8233fac2010-10-26 16:08:53 -070033import android.content.Intent;
34import android.content.pm.PackageManager;
35import android.content.pm.ResolveInfo;
36import android.content.res.Configuration;
John Reck30b065e2011-07-19 10:58:05 -070037import android.content.res.TypedArray;
Leon Scroggins1961ed22010-12-07 15:22:21 -050038import android.database.ContentObserver;
Michael Kolb8233fac2010-10-26 16:08:53 -070039import android.database.Cursor;
40import android.database.sqlite.SQLiteDatabase;
Michael Kolb8233fac2010-10-26 16:08:53 -070041import android.graphics.Bitmap;
42import android.graphics.Canvas;
Michael Kolb8233fac2010-10-26 16:08:53 -070043import android.net.Uri;
44import android.net.http.SslError;
45import android.os.AsyncTask;
46import android.os.Bundle;
George Mount387d45d2011-10-07 15:57:53 -070047import android.os.Environment;
Michael Kolb8233fac2010-10-26 16:08:53 -070048import android.os.Handler;
49import android.os.Message;
50import android.os.PowerManager;
51import android.os.PowerManager.WakeLock;
Ben Murdoch8029a772010-11-16 11:58:21 +000052import android.preference.PreferenceActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -070053import android.provider.Browser;
54import android.provider.BrowserContract;
Michael Kolb8233fac2010-10-26 16:08:53 -070055import android.provider.BrowserContract.Images;
56import android.provider.ContactsContract;
57import android.provider.ContactsContract.Intents.Insert;
Michael Kolb8233fac2010-10-26 16:08:53 -070058import android.text.TextUtils;
59import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080060import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070061import android.view.ActionMode;
62import android.view.ContextMenu;
63import android.view.ContextMenu.ContextMenuInfo;
64import android.view.Gravity;
65import android.view.KeyEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070066import android.view.Menu;
67import android.view.MenuInflater;
68import android.view.MenuItem;
69import android.view.MenuItem.OnMenuItemClickListener;
Michael Kolbc3af0672011-08-09 10:24:41 -070070import android.view.MotionEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070071import android.view.View;
72import android.webkit.CookieManager;
73import android.webkit.CookieSyncManager;
74import android.webkit.HttpAuthHandler;
George Mount387d45d2011-10-07 15:57:53 -070075import android.webkit.MimeTypeMap;
Michael Kolb8233fac2010-10-26 16:08:53 -070076import android.webkit.SslErrorHandler;
77import android.webkit.ValueCallback;
78import android.webkit.WebChromeClient;
79import android.webkit.WebIconDatabase;
80import android.webkit.WebSettings;
81import android.webkit.WebView;
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +000082import android.webkit.WebViewClassic;
Leon Scrogginsac993842011-02-02 12:54:07 -050083import android.widget.Toast;
Michael Kolb8233fac2010-10-26 16:08:53 -070084
Michael Kolb4bd767d2011-05-27 11:33:55 -070085import com.android.browser.IntentHandler.UrlData;
John Reck2bc80422011-06-30 15:11:49 -070086import com.android.browser.UI.ComboViews;
Michael Kolb4bd767d2011-05-27 11:33:55 -070087import com.android.browser.provider.BrowserProvider;
John Reck1cf4b792011-07-26 10:22:22 -070088import com.android.browser.provider.BrowserProvider2.Thumbnails;
John Reck8cc92352011-07-06 17:41:52 -070089import com.android.browser.provider.SnapshotProvider.Snapshots;
Michael Kolb4bd767d2011-05-27 11:33:55 -070090import com.android.browser.search.SearchEngine;
91import com.android.common.Search;
92
Michael Kolb8233fac2010-10-26 16:08:53 -070093import java.io.ByteArrayOutputStream;
George Mount387d45d2011-10-07 15:57:53 -070094import java.io.File;
95import java.io.FileOutputStream;
96import java.io.IOException;
Michael Kolb8233fac2010-10-26 16:08:53 -070097import java.net.URLEncoder;
George Mount387d45d2011-10-07 15:57:53 -070098import java.text.DateFormat;
99import java.text.SimpleDateFormat;
John Reck1cf4b792011-07-26 10:22:22 -0700100import java.util.ArrayList;
Michael Kolb8233fac2010-10-26 16:08:53 -0700101import java.util.Calendar;
George Mount387d45d2011-10-07 15:57:53 -0700102import java.util.Date;
Michael Kolb8233fac2010-10-26 16:08:53 -0700103import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -0800104import java.util.List;
John Reck26b18322011-06-21 13:08:58 -0700105import java.util.Map;
Michael Kolb8233fac2010-10-26 16:08:53 -0700106
107/**
108 * Controller for browser
109 */
110public class Controller
111 implements WebViewController, UiController {
112
113 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800114 private static final String SEND_APP_ID_EXTRA =
115 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
Michael Kolba4261fd2011-05-05 11:27:37 -0700116 private static final String INCOGNITO_URI = "browser:incognito";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800117
Michael Kolb8233fac2010-10-26 16:08:53 -0700118
119 // public message ids
120 public final static int LOAD_URL = 1001;
121 public final static int STOP_LOAD = 1002;
122
123 // Message Ids
124 private static final int FOCUS_NODE_HREF = 102;
125 private static final int RELEASE_WAKELOCK = 107;
126
127 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
128
129 private static final int OPEN_BOOKMARKS = 201;
130
131 private static final int EMPTY_MENU = -1;
132
Michael Kolb8233fac2010-10-26 16:08:53 -0700133 // activity requestCode
John Reckd3e4d5b2011-07-13 15:48:43 -0700134 final static int COMBO_VIEW = 1;
Michael Kolb8233fac2010-10-26 16:08:53 -0700135 final static int PREFERENCES_PAGE = 3;
136 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000137 final static int AUTOFILL_SETUP = 5;
138
Michael Kolb8233fac2010-10-26 16:08:53 -0700139 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
140
141 // As the ids are dynamically created, we can't guarantee that they will
142 // be in sequence, so this static array maps ids to a window number.
143 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
144 { R.id.window_one_menu_id, R.id.window_two_menu_id,
145 R.id.window_three_menu_id, R.id.window_four_menu_id,
146 R.id.window_five_menu_id, R.id.window_six_menu_id,
147 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
148
149 // "source" parameter for Google search through search key
150 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
151 // "source" parameter for Google search through simplily type
152 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
153
George Mount387d45d2011-10-07 15:57:53 -0700154 // "no-crash-recovery" parameter in intent to suppress crash recovery
Guang Zhu9e78f512011-05-04 11:45:11 -0700155 final static String NO_CRASH_RECOVERY = "no-crash-recovery";
156
John Reckd7dd9b22011-08-30 09:18:29 -0700157 // A bitmap that is re-used in createScreenshot as scratch space
158 private static Bitmap sThumbnailBitmap;
159
Michael Kolb8233fac2010-10-26 16:08:53 -0700160 private Activity mActivity;
161 private UI mUi;
162 private TabControl mTabControl;
163 private BrowserSettings mSettings;
164 private WebViewFactory mFactory;
165
166 private WakeLock mWakeLock;
167
168 private UrlHandler mUrlHandler;
169 private UploadHandler mUploadHandler;
170 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700171 private PageDialogsHandler mPageDialogsHandler;
172 private NetworkStateHandler mNetworkHandler;
173
Ben Murdoch8029a772010-11-16 11:58:21 +0000174 private Message mAutoFillSetupMessage;
175
Michael Kolb8233fac2010-10-26 16:08:53 -0700176 private boolean mShouldShowErrorConsole;
177
178 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
179
180 // FIXME, temp address onPrepareMenu performance problem.
181 // When we move everything out of view, we should rewrite this.
182 private int mCurrentMenuState = 0;
183 private int mMenuState = R.id.MAIN_MENU;
184 private int mOldMenuState = EMPTY_MENU;
185 private Menu mCachedMenu;
186
Michael Kolb8233fac2010-10-26 16:08:53 -0700187 private boolean mMenuIsDown;
188
189 // For select and find, we keep track of the ActionMode so that
190 // finish() can be called as desired.
191 private ActionMode mActionMode;
192
193 /**
194 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
195 * of whether the configuration has changed. The first onMenuOpened call
196 * after a configuration change is simply a reopening of the same menu
197 * (i.e. mIconView did not change).
198 */
199 private boolean mConfigChanged;
200
201 /**
202 * Keeps track of whether the options menu is open. This is important in
203 * determining whether to show or hide the title bar overlay
204 */
205 private boolean mOptionsMenuOpen;
206
207 /**
208 * Whether or not the options menu is in its bigger, popup menu form. When
209 * true, we want the title bar overlay to be gone. When false, we do not.
210 * Only meaningful if mOptionsMenuOpen is true.
211 */
212 private boolean mExtendedMenuOpen;
213
Michael Kolb8233fac2010-10-26 16:08:53 -0700214 private boolean mActivityPaused = true;
215 private boolean mLoadStopped;
216
217 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500218 // Checks to see when the bookmarks database has changed, and updates the
219 // Tabs' notion of whether they represent bookmarked sites.
220 private ContentObserver mBookmarksObserver;
John Reck847b5322011-04-14 17:02:18 -0700221 private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700222
Michael Kolbc3af0672011-08-09 10:24:41 -0700223 private boolean mBlockEvents;
224
George Mount3636d0a2011-11-21 09:08:21 -0800225 public Controller(Activity browser) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700226 mActivity = browser;
227 mSettings = BrowserSettings.getInstance();
228 mTabControl = new TabControl(this);
229 mSettings.setController(this);
John Reck378a4102011-06-09 16:23:01 -0700230 mCrashRecoveryHandler = CrashRecoveryHandler.initialize(this);
George Mount3636d0a2011-11-21 09:08:21 -0800231 mCrashRecoveryHandler.preloadCrashState();
Michael Kolb14612442011-06-24 13:06:29 -0700232 mFactory = new BrowserWebViewFactory(browser);
Michael Kolb8233fac2010-10-26 16:08:53 -0700233
234 mUrlHandler = new UrlHandler(this);
235 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700236 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
237
Michael Kolb8233fac2010-10-26 16:08:53 -0700238 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500239 mBookmarksObserver = new ContentObserver(mHandler) {
240 @Override
241 public void onChange(boolean selfChange) {
242 int size = mTabControl.getTabCount();
243 for (int i = 0; i < size; i++) {
244 mTabControl.getTab(i).updateBookmarkedStatus();
245 }
246 }
247
248 };
249 browser.getContentResolver().registerContentObserver(
250 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700251
252 mNetworkHandler = new NetworkStateHandler(mActivity, this);
253 // Start watching the default geolocation permissions
254 mSystemAllowGeolocationOrigins =
255 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
256 mSystemAllowGeolocationOrigins.start();
257
John Reckaf262e72011-07-25 13:55:44 -0700258 openIconDatabase();
Michael Kolb8233fac2010-10-26 16:08:53 -0700259 }
260
George Mount3636d0a2011-11-21 09:08:21 -0800261 void start(final Intent intent) {
Ben Murdochf695f6b2012-05-24 12:59:45 +0100262 WebViewClassic.setShouldMonitorWebCoreThread();
George Mount3636d0a2011-11-21 09:08:21 -0800263 // mCrashRecoverHandler has any previously saved state.
264 mCrashRecoveryHandler.startRecovery(intent);
John Reck847b5322011-04-14 17:02:18 -0700265 }
266
George Mount3636d0a2011-11-21 09:08:21 -0800267 void doStart(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700268 // Unless the last browser usage was within 24 hours, destroy any
269 // remaining incognito tabs.
270
271 Calendar lastActiveDate = icicle != null ?
272 (Calendar) icicle.getSerializable("lastActiveDate") : null;
273 Calendar today = Calendar.getInstance();
274 Calendar yesterday = Calendar.getInstance();
275 yesterday.add(Calendar.DATE, -1);
276
Patrick Scott7d50a932011-02-04 09:27:26 -0500277 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700278 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800279 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700280
Patrick Scott7d50a932011-02-04 09:27:26 -0500281 // Find out if we will restore any state and remember the tab.
Michael Kolbc831b632011-05-11 09:30:34 -0700282 final long currentTabId =
Patrick Scott7d50a932011-02-04 09:27:26 -0500283 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000284
Michael Kolbc831b632011-05-11 09:30:34 -0700285 if (currentTabId == -1) {
Patrick Scott7d50a932011-02-04 09:27:26 -0500286 // Not able to restore so we go ahead and clear session cookies. We
287 // must do this before trying to login the user as we don't want to
288 // clear any session cookies set during login.
289 CookieManager.getInstance().removeSessionCookie();
290 }
291
Patrick Scottd43e75a2011-03-14 14:47:23 -0400292 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500293 new Runnable() {
294 @Override public void run() {
George Mount3636d0a2011-11-21 09:08:21 -0800295 onPreloginFinished(icicle, intent, currentTabId,
296 restoreIncognitoTabs);
Patrick Scott7d50a932011-02-04 09:27:26 -0500297 }
298 });
299 }
300
Michael Kolbc831b632011-05-11 09:30:34 -0700301 private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId,
George Mount3636d0a2011-11-21 09:08:21 -0800302 boolean restoreIncognitoTabs) {
Michael Kolbc831b632011-05-11 09:30:34 -0700303 if (currentTabId == -1) {
John Reck1cf4b792011-07-26 10:22:22 -0700304 BackgroundHandler.execute(new PruneThumbnails(mActivity, null));
George Mount3636d0a2011-11-21 09:08:21 -0800305 if (intent == null) {
306 // This won't happen under common scenarios. The icicle is
307 // not null, but there aren't any tabs to restore.
308 openTabToHomePage();
Michael Kolb7bcafde2011-05-09 13:55:59 -0700309 } else {
George Mount3636d0a2011-11-21 09:08:21 -0800310 final Bundle extra = intent.getExtras();
311 // Create an initial tab.
312 // If the intent is ACTION_VIEW and data is not null, the Browser is
313 // invoked to view the content by another application. In this case,
314 // the tab will be close when exit.
315 UrlData urlData = IntentHandler.getUrlDataFromIntent(intent);
316 Tab t = null;
317 if (urlData.isEmpty()) {
318 t = openTabToHomePage();
319 } else {
320 t = openTab(urlData);
321 }
322 if (t != null) {
323 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
324 }
325 WebView webView = t.getWebView();
326 if (extra != null) {
327 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
328 if (scale > 0 && scale <= 1000) {
329 webView.setInitialScale(scale);
330 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700331 }
332 }
John Reckd8c74522011-06-14 08:45:00 -0700333 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700334 } else {
Michael Kolbc831b632011-05-11 09:30:34 -0700335 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
Patrick Scott7d50a932011-02-04 09:27:26 -0500336 mUi.needsRestoreAllTabs());
John Reck1cf4b792011-07-26 10:22:22 -0700337 List<Tab> tabs = mTabControl.getTabs();
338 ArrayList<Long> restoredTabs = new ArrayList<Long>(tabs.size());
339 for (Tab t : tabs) {
340 restoredTabs.add(t.getId());
341 }
342 BackgroundHandler.execute(new PruneThumbnails(mActivity, restoredTabs));
John Reck52be4782011-08-26 15:37:29 -0700343 if (tabs.size() == 0) {
344 openTabToHomePage();
345 }
John Reck1cf4b792011-07-26 10:22:22 -0700346 mUi.updateTabs(tabs);
Michael Kolb8233fac2010-10-26 16:08:53 -0700347 // TabControl.restoreState() will create a new tab even if
348 // restoring the state fails.
349 setActiveTab(mTabControl.getCurrentTab());
George Mount3636d0a2011-11-21 09:08:21 -0800350 // Intent is non-null when framework thinks the browser should be
351 // launching with a new intent (icicle is null).
352 if (intent != null) {
John Reck9dd4a412011-10-05 14:55:30 -0700353 mIntentHandler.onNewIntent(intent);
354 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700355 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700356 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700357 String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb8233fac2010-10-26 16:08:53 -0700358 if (jsFlags.trim().length() != 0) {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +0000359 WebViewClassic.fromWebView(getCurrentWebView()).setJsFlags(jsFlags);
Michael Kolb8233fac2010-10-26 16:08:53 -0700360 }
George Mount3636d0a2011-11-21 09:08:21 -0800361 if (intent != null
362 && BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
Michael Kolb315d5022011-10-13 12:47:11 -0700363 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
John Reck439c9a52010-12-14 10:04:39 -0800364 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700365 }
366
John Reck1cf4b792011-07-26 10:22:22 -0700367 private static class PruneThumbnails implements Runnable {
368 private Context mContext;
369 private List<Long> mIds;
370
371 PruneThumbnails(Context context, List<Long> preserveIds) {
372 mContext = context.getApplicationContext();
373 mIds = preserveIds;
374 }
375
376 @Override
377 public void run() {
378 ContentResolver cr = mContext.getContentResolver();
379 if (mIds == null || mIds.size() == 0) {
380 cr.delete(Thumbnails.CONTENT_URI, null, null);
381 } else {
382 int length = mIds.size();
383 StringBuilder where = new StringBuilder();
384 where.append(Thumbnails._ID);
385 where.append(" not in (");
386 for (int i = 0; i < length; i++) {
387 where.append(mIds.get(i));
388 if (i < (length - 1)) {
389 where.append(",");
390 }
391 }
392 where.append(")");
393 cr.delete(Thumbnails.CONTENT_URI, where.toString(), null);
394 }
395 }
396
397 }
398
Michael Kolb1514bb72010-11-22 09:11:48 -0800399 @Override
400 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700401 return mFactory;
402 }
403
404 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800405 public void onSetWebView(Tab tab, WebView view) {
406 mUi.onSetWebView(tab, view);
407 }
408
409 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800410 public void createSubWindow(Tab tab) {
411 endActionMode();
412 WebView mainView = tab.getWebView();
413 WebView subView = mFactory.createWebView((mainView == null)
414 ? false
415 : mainView.isPrivateBrowsingEnabled());
416 mUi.createSubWindow(tab, subView);
417 }
418
419 @Override
Michael Kolb14612442011-06-24 13:06:29 -0700420 public Context getContext() {
421 return mActivity;
422 }
423
424 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700425 public Activity getActivity() {
426 return mActivity;
427 }
428
429 void setUi(UI ui) {
430 mUi = ui;
431 }
432
Michael Kolbaf63dba2012-05-16 12:58:05 -0700433 @Override
434 public BrowserSettings getSettings() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700435 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) {
Michael Kolb72864272012-05-03 15:42:15 -0700852 mCrashRecoveryHandler.backupState();
John Reck30c714c2010-12-16 17:30:34 -0800853 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700854 // pause the WebView timer and release the wake lock if it is finished
855 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800856 if (mActivityPaused && pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700857 releaseWakeLock();
Michael Kolb8233fac2010-10-26 16:08:53 -0700858 }
Martijn Coenenb2f93552011-06-14 10:48:35 +0200859
Michael Kolb8233fac2010-10-26 16:08:53 -0700860 // Performance probe
861 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800862 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700863 }
864
865 Performance.tracePageFinished();
866 }
867
868 @Override
John Reck30c714c2010-12-16 17:30:34 -0800869 public void onProgressChanged(Tab tab) {
870 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.
Michael Kolb72864272012-05-03 15:42:15 -0700890 if (tab.shouldUpdateThumbnail() &&
891 (tab.inForeground() && !didUserStopLoading()
892 || !tab.inForeground())) {
John Reckd9862372012-02-21 15:04:50 -0800893 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
894 mHandler.sendMessageDelayed(mHandler.obtainMessage(
895 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
896 500);
897 }
898 }
899 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700900 } else {
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800901 if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700902 // onPageFinished may have already been called but a subframe is
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800903 // still loading
904 // updating the progress and
Michael Kolb8233fac2010-10-26 16:08:53 -0700905 // update the menu items.
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800906 updateInLoadMenuItems(mCachedMenu, tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700907 }
908 }
John Reck30c714c2010-12-16 17:30:34 -0800909 mUi.onProgressChanged(tab);
910 }
911
912 @Override
Steve Block2466eff2011-10-03 15:33:09 +0100913 public void onUpdatedSecurityState(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800914 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700915 }
916
917 @Override
918 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800919 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800920 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800921 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700922 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
923 return;
924 }
925 // Update the title in the history database if not in private browsing mode
926 if (!tab.isPrivateBrowsingEnabled()) {
John Reckf57c0292011-07-21 18:15:39 -0700927 DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700928 }
929 }
930
931 @Override
932 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800933 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700934 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
935 }
936
937 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800938 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
939 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700940 }
941
942 @Override
943 public boolean shouldOverrideKeyEvent(KeyEvent event) {
944 if (mMenuIsDown) {
945 // only check shortcut key when MENU is held
946 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
947 event);
948 } else {
949 return false;
950 }
951 }
952
953 @Override
John Reck997b1b72012-04-19 18:08:25 -0700954 public boolean onUnhandledKeyEvent(KeyEvent event) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700955 if (!isActivityPaused()) {
956 if (event.getAction() == KeyEvent.ACTION_DOWN) {
John Reck997b1b72012-04-19 18:08:25 -0700957 return mActivity.onKeyDown(event.getKeyCode(), event);
Michael Kolb8233fac2010-10-26 16:08:53 -0700958 } else {
John Reck997b1b72012-04-19 18:08:25 -0700959 return mActivity.onKeyUp(event.getKeyCode(), event);
Michael Kolb8233fac2010-10-26 16:08:53 -0700960 }
961 }
John Reck997b1b72012-04-19 18:08:25 -0700962 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700963 }
964
965 @Override
John Reck324d4402011-01-11 16:56:42 -0800966 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700967 // Don't save anything in private browsing mode
968 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800969 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700970
John Reck324d4402011-01-11 16:56:42 -0800971 if (TextUtils.isEmpty(url)
972 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700973 return;
974 }
John Reckf57c0292011-07-21 18:15:39 -0700975 DataController.getInstance(mActivity).updateVisitedHistory(url);
John Reck6c2e2f32011-08-22 13:41:23 -0700976 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -0700977 }
978
979 @Override
980 public void getVisitedHistory(final ValueCallback<String[]> callback) {
981 AsyncTask<Void, Void, String[]> task =
982 new AsyncTask<Void, Void, String[]>() {
983 @Override
984 public String[] doInBackground(Void... unused) {
985 return Browser.getVisitedHistory(mActivity.getContentResolver());
986 }
987 @Override
988 public void onPostExecute(String[] result) {
989 callback.onReceiveValue(result);
990 }
991 };
992 task.execute();
993 }
994
995 @Override
996 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
997 final HttpAuthHandler handler, final String host,
998 final String realm) {
999 String username = null;
1000 String password = null;
1001
1002 boolean reuseHttpAuthUsernamePassword
1003 = handler.useHttpAuthUsernamePassword();
1004
1005 if (reuseHttpAuthUsernamePassword && view != null) {
1006 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
1007 if (credentials != null && credentials.length == 2) {
1008 username = credentials[0];
1009 password = credentials[1];
1010 }
1011 }
1012
1013 if (username != null && password != null) {
1014 handler.proceed(username, password);
1015 } else {
Ben Murdochfdd37112011-08-05 15:48:14 +01001016 if (tab.inForeground() && !handler.suppressDialog()) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001017 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
1018 } else {
1019 handler.cancel();
1020 }
1021 }
1022 }
1023
1024 @Override
1025 public void onDownloadStart(Tab tab, String url, String userAgent,
1026 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001027 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -05001028 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001029 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
1030 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001031 // This Tab was opened for the sole purpose of downloading a
1032 // file. Remove it.
1033 if (tab == mTabControl.getCurrentTab()) {
1034 // In this case, the Tab is still on top.
1035 goBackOnePageOrQuit();
1036 } else {
1037 // In this case, it is not.
1038 closeTab(tab);
1039 }
1040 }
1041 }
1042
1043 @Override
1044 public Bitmap getDefaultVideoPoster() {
1045 return mUi.getDefaultVideoPoster();
1046 }
1047
1048 @Override
1049 public View getVideoLoadingProgressView() {
1050 return mUi.getVideoLoadingProgressView();
1051 }
1052
1053 @Override
1054 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1055 SslError error) {
1056 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1057 }
1058
Patrick Scott92066772011-03-10 08:46:27 -05001059 @Override
1060 public void showAutoLogin(Tab tab) {
1061 assert tab.inForeground();
1062 // Update the title bar to show the auto-login request.
1063 mUi.showAutoLogin(tab);
1064 }
1065
1066 @Override
1067 public void hideAutoLogin(Tab tab) {
1068 assert tab.inForeground();
1069 mUi.hideAutoLogin(tab);
1070 }
1071
Michael Kolb8233fac2010-10-26 16:08:53 -07001072 // helper method
1073
1074 /*
1075 * Update the favorites icon if the private browsing isn't enabled and the
1076 * icon is valid.
1077 */
1078 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1079 final String url, Bitmap favicon) {
1080 if (favicon == null) {
1081 return;
1082 }
1083 if (!tab.isPrivateBrowsingEnabled()) {
1084 Bookmarks.updateFavicon(mActivity
1085 .getContentResolver(), originalUrl, url, favicon);
1086 }
1087 }
1088
Leon Scroggins4cd97792010-12-03 15:31:56 -05001089 @Override
1090 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001091 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001092 mUi.bookmarkedStatusHasChanged(tab);
1093 }
1094
Michael Kolb8233fac2010-10-26 16:08:53 -07001095 // end WebViewController
1096
1097 protected void pageUp() {
1098 getCurrentTopWebView().pageUp(false);
1099 }
1100
1101 protected void pageDown() {
1102 getCurrentTopWebView().pageDown(false);
1103 }
1104
1105 // callback from phone title bar
1106 public void editUrl() {
1107 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolb1f9b3562012-04-24 14:38:34 -07001108 mUi.editUrl(false, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001109 }
1110
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001111 public void showCustomView(Tab tab, View view, int requestedOrientation,
Michael Kolb8233fac2010-10-26 16:08:53 -07001112 WebChromeClient.CustomViewCallback callback) {
1113 if (tab.inForeground()) {
1114 if (mUi.isCustomViewShowing()) {
1115 callback.onCustomViewHidden();
1116 return;
1117 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001118 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001119 // Save the menu state and set it to empty while the custom
1120 // view is showing.
1121 mOldMenuState = mMenuState;
1122 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001123 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001124 }
1125 }
1126
1127 @Override
1128 public void hideCustomView() {
1129 if (mUi.isCustomViewShowing()) {
1130 mUi.onHideCustomView();
1131 // Reset the old menu state.
1132 mMenuState = mOldMenuState;
1133 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001134 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001135 }
1136 }
1137
1138 protected void onActivityResult(int requestCode, int resultCode,
1139 Intent intent) {
1140 if (getCurrentTopWebView() == null) return;
1141 switch (requestCode) {
1142 case PREFERENCES_PAGE:
1143 if (resultCode == Activity.RESULT_OK && intent != null) {
1144 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001145 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001146 mTabControl.removeParentChildRelationShips();
1147 }
1148 }
1149 break;
1150 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001151 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001152 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001153 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001154 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001155 case AUTOFILL_SETUP:
1156 // Determine whether a profile was actually set up or not
1157 // and if so, send the message back to the WebTextView to
1158 // fill the form with the new profile.
1159 if (getSettings().getAutoFillProfile() != null) {
1160 mAutoFillSetupMessage.sendToTarget();
1161 mAutoFillSetupMessage = null;
1162 }
1163 break;
John Reckd3e4d5b2011-07-13 15:48:43 -07001164 case COMBO_VIEW:
1165 if (intent == null || resultCode != Activity.RESULT_OK) {
1166 break;
1167 }
John Reck3ba45532011-08-11 16:26:53 -07001168 mUi.showWeb(false);
John Reckd3e4d5b2011-07-13 15:48:43 -07001169 if (Intent.ACTION_VIEW.equals(intent.getAction())) {
1170 Tab t = getCurrentTab();
1171 Uri uri = intent.getData();
1172 loadUrl(t, uri.toString());
1173 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
1174 String[] urls = intent.getStringArrayExtra(
1175 ComboViewActivity.EXTRA_OPEN_ALL);
1176 Tab parent = getCurrentTab();
1177 for (String url : urls) {
1178 parent = openTab(url, parent,
1179 !mSettings.openInBackground(), true);
1180 }
1181 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
1182 long id = intent.getLongExtra(
1183 ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
1184 if (id >= 0) {
1185 createNewSnapshotTab(id, true);
1186 }
1187 }
1188 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001189 default:
1190 break;
1191 }
1192 getCurrentTopWebView().requestFocus();
1193 }
1194
1195 /**
1196 * Open the Go page.
1197 * @param startWithHistory If true, open starting on the history tab.
1198 * Otherwise, start with the bookmarks tab.
1199 */
1200 @Override
Michael Kolb315d5022011-10-13 12:47:11 -07001201 public void bookmarksOrHistoryPicker(ComboViews startView) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001202 if (mTabControl.getCurrentWebView() == null) {
1203 return;
1204 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001205 // clear action mode
1206 if (isInCustomActionMode()) {
1207 endActionMode();
1208 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001209 Bundle extras = new Bundle();
1210 // Disable opening in a new window if we have maxed out the windows
1211 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1212 !mTabControl.canCreateNewTab());
Michael Kolb315d5022011-10-13 12:47:11 -07001213 mUi.showComboView(startView, extras);
Michael Kolb8233fac2010-10-26 16:08:53 -07001214 }
1215
1216 // combo view callbacks
1217
Michael Kolb8233fac2010-10-26 16:08:53 -07001218 // key handling
1219 protected void onBackKey() {
1220 if (!mUi.onBackKey()) {
1221 WebView subwindow = mTabControl.getCurrentSubWindow();
1222 if (subwindow != null) {
1223 if (subwindow.canGoBack()) {
1224 subwindow.goBack();
1225 } else {
1226 dismissSubWindow(mTabControl.getCurrentTab());
1227 }
1228 } else {
1229 goBackOnePageOrQuit();
1230 }
1231 }
1232 }
1233
Michael Kolb4bd767d2011-05-27 11:33:55 -07001234 protected boolean onMenuKey() {
1235 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001236 }
1237
Michael Kolb8233fac2010-10-26 16:08:53 -07001238 // menu handling and state
1239 // TODO: maybe put into separate handler
1240
1241 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckd73c5a22010-12-22 10:22:50 -08001242 if (mMenuState == EMPTY_MENU) {
1243 return false;
1244 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001245 MenuInflater inflater = mActivity.getMenuInflater();
1246 inflater.inflate(R.menu.browser, menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001247 return true;
1248 }
1249
1250 protected void onCreateContextMenu(ContextMenu menu, View v,
1251 ContextMenuInfo menuInfo) {
John Reck0f602f32011-07-07 15:38:43 -07001252 if (v instanceof TitleBar) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001253 return;
1254 }
1255 if (!(v instanceof WebView)) {
1256 return;
1257 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001258 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001259 WebView.HitTestResult result = webview.getHitTestResult();
1260 if (result == null) {
1261 return;
1262 }
1263
1264 int type = result.getType();
1265 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1266 Log.w(LOGTAG,
1267 "We should not show context menu when nothing is touched");
1268 return;
1269 }
1270 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1271 // let TextView handles context menu
1272 return;
1273 }
1274
1275 // Note, http://b/issue?id=1106666 is requesting that
1276 // an inflated menu can be used again. This is not available
1277 // yet, so inflate each time (yuk!)
1278 MenuInflater inflater = mActivity.getMenuInflater();
1279 inflater.inflate(R.menu.browsercontext, menu);
1280
1281 // Show the correct menu group
1282 final String extra = result.getExtra();
Michael Kolbc159c1a2011-12-15 16:06:38 -08001283 if (extra == null) return;
Michael Kolb8233fac2010-10-26 16:08:53 -07001284 menu.setGroupVisible(R.id.PHONE_MENU,
1285 type == WebView.HitTestResult.PHONE_TYPE);
1286 menu.setGroupVisible(R.id.EMAIL_MENU,
1287 type == WebView.HitTestResult.EMAIL_TYPE);
1288 menu.setGroupVisible(R.id.GEO_MENU,
1289 type == WebView.HitTestResult.GEO_TYPE);
1290 menu.setGroupVisible(R.id.IMAGE_MENU,
1291 type == WebView.HitTestResult.IMAGE_TYPE
1292 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1293 menu.setGroupVisible(R.id.ANCHOR_MENU,
1294 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1295 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001296 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1297 || type == WebView.HitTestResult.PHONE_TYPE
1298 || type == WebView.HitTestResult.EMAIL_TYPE
1299 || type == WebView.HitTestResult.GEO_TYPE;
1300 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1301 if (hitText) {
1302 menu.findItem(R.id.select_text_menu_id)
1303 .setOnMenuItemClickListener(new SelectText(webview));
1304 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001305 // Setup custom handling depending on the type
1306 switch (type) {
1307 case WebView.HitTestResult.PHONE_TYPE:
1308 menu.setHeaderTitle(Uri.decode(extra));
1309 menu.findItem(R.id.dial_context_menu_id).setIntent(
1310 new Intent(Intent.ACTION_VIEW, Uri
1311 .parse(WebView.SCHEME_TEL + extra)));
1312 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1313 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1314 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1315 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1316 addIntent);
1317 menu.findItem(R.id.copy_phone_context_menu_id)
1318 .setOnMenuItemClickListener(
1319 new Copy(extra));
1320 break;
1321
1322 case WebView.HitTestResult.EMAIL_TYPE:
1323 menu.setHeaderTitle(extra);
1324 menu.findItem(R.id.email_context_menu_id).setIntent(
1325 new Intent(Intent.ACTION_VIEW, Uri
1326 .parse(WebView.SCHEME_MAILTO + extra)));
1327 menu.findItem(R.id.copy_mail_context_menu_id)
1328 .setOnMenuItemClickListener(
1329 new Copy(extra));
1330 break;
1331
1332 case WebView.HitTestResult.GEO_TYPE:
1333 menu.setHeaderTitle(extra);
1334 menu.findItem(R.id.map_context_menu_id).setIntent(
1335 new Intent(Intent.ACTION_VIEW, Uri
1336 .parse(WebView.SCHEME_GEO
1337 + URLEncoder.encode(extra))));
1338 menu.findItem(R.id.copy_geo_context_menu_id)
1339 .setOnMenuItemClickListener(
1340 new Copy(extra));
1341 break;
1342
1343 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1344 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001345 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001346 // decide whether to show the open link in new tab option
1347 boolean showNewTab = mTabControl.canCreateNewTab();
1348 MenuItem newTabItem
1349 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001350 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001351 ? R.string.contextmenu_openlink_newwindow_background
1352 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001353 newTabItem.setVisible(showNewTab);
1354 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001355 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1356 newTabItem.setOnMenuItemClickListener(
1357 new MenuItem.OnMenuItemClickListener() {
1358 @Override
1359 public boolean onMenuItemClick(MenuItem item) {
1360 final HashMap<String, WebView> hrefMap =
1361 new HashMap<String, WebView>();
1362 hrefMap.put("webview", webview);
1363 final Message msg = mHandler.obtainMessage(
1364 FOCUS_NODE_HREF,
1365 R.id.open_newtab_context_menu_id,
1366 0, hrefMap);
1367 webview.requestFocusNodeHref(msg);
1368 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001369 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001370 });
1371 } else {
1372 newTabItem.setOnMenuItemClickListener(
1373 new MenuItem.OnMenuItemClickListener() {
1374 @Override
1375 public boolean onMenuItemClick(MenuItem item) {
1376 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001377 openTab(extra, parent,
1378 !mSettings.openInBackground(),
1379 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001380 return true;
1381 }
1382 });
1383 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001384 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001385 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1386 break;
1387 }
1388 // otherwise fall through to handle image part
1389 case WebView.HitTestResult.IMAGE_TYPE:
Victoria Lease5987b802012-03-12 13:05:23 -07001390 MenuItem shareItem = menu.findItem(R.id.share_link_context_menu_id);
1391 shareItem.setVisible(type == WebView.HitTestResult.IMAGE_TYPE);
Michael Kolb8233fac2010-10-26 16:08:53 -07001392 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1393 menu.setHeaderTitle(extra);
Victoria Lease5987b802012-03-12 13:05:23 -07001394 shareItem.setOnMenuItemClickListener(
1395 new MenuItem.OnMenuItemClickListener() {
1396 @Override
1397 public boolean onMenuItemClick(MenuItem item) {
1398 sharePage(mActivity, null, extra, null,
1399 null);
1400 return true;
1401 }
1402 }
1403 );
Michael Kolb8233fac2010-10-26 16:08:53 -07001404 }
Michael Kolb3639c4c2011-09-28 15:36:40 -07001405 menu.findItem(R.id.view_image_context_menu_id)
1406 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1407 @Override
1408 public boolean onMenuItemClick(MenuItem item) {
1409 openTab(extra, mTabControl.getCurrentTab(), true, true);
1410 return false;
1411 }
1412 });
Michael Kolb8233fac2010-10-26 16:08:53 -07001413 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001414 setOnMenuItemClickListener(
1415 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001416 menu.findItem(R.id.set_wallpaper_context_menu_id).
1417 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1418 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001419 break;
1420
1421 default:
1422 Log.w(LOGTAG, "We should not get here.");
1423 break;
1424 }
1425 //update the ui
1426 mUi.onContextMenuCreated(menu);
1427 }
1428
1429 /**
1430 * As the menu can be open when loading state changes
1431 * we must manually update the state of the stop/reload menu
1432 * item
1433 */
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001434 private void updateInLoadMenuItems(Menu menu, Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001435 if (menu == null) {
1436 return;
1437 }
1438 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolbb8337132011-11-28 15:07:39 -08001439 MenuItem src = ((tab != null) && tab.inPageLoad()) ?
Michael Kolb8233fac2010-10-26 16:08:53 -07001440 menu.findItem(R.id.stop_menu_id):
1441 menu.findItem(R.id.reload_menu_id);
1442 if (src != null) {
1443 dest.setIcon(src.getIcon());
1444 dest.setTitle(src.getTitle());
1445 }
1446 }
1447
John Reckb3417f02011-01-14 11:01:05 -08001448 boolean onPrepareOptionsMenu(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001449 updateInLoadMenuItems(menu, getCurrentTab());
John Recke1a03a32011-09-14 17:04:16 -07001450 // hold on to the menu reference here; it is used by the page callbacks
1451 // to update the menu based on loading state
1452 mCachedMenu = menu;
Michael Kolb8233fac2010-10-26 16:08:53 -07001453 // Note: setVisible will decide whether an item is visible; while
1454 // setEnabled() will decide whether an item is enabled, which also means
1455 // whether the matching shortcut key will function.
1456 switch (mMenuState) {
1457 case EMPTY_MENU:
1458 if (mCurrentMenuState != mMenuState) {
1459 menu.setGroupVisible(R.id.MAIN_MENU, false);
1460 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1461 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1462 }
1463 break;
1464 default:
1465 if (mCurrentMenuState != mMenuState) {
1466 menu.setGroupVisible(R.id.MAIN_MENU, true);
1467 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1468 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1469 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001470 updateMenuState(getCurrentTab(), menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001471 break;
1472 }
1473 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001474 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001475 }
1476
Michael Kolb4bf79712011-07-14 14:18:12 -07001477 @Override
1478 public void updateMenuState(Tab tab, Menu menu) {
1479 boolean canGoBack = false;
1480 boolean canGoForward = false;
1481 boolean isHome = false;
John Reck42229bc2011-08-19 13:26:43 -07001482 boolean isDesktopUa = false;
John Recke1a03a32011-09-14 17:04:16 -07001483 boolean isLive = false;
Michael Kolb4bf79712011-07-14 14:18:12 -07001484 if (tab != null) {
1485 canGoBack = tab.canGoBack();
1486 canGoForward = tab.canGoForward();
1487 isHome = mSettings.getHomePage().equals(tab.getUrl());
John Reck42229bc2011-08-19 13:26:43 -07001488 isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
John Recke1a03a32011-09-14 17:04:16 -07001489 isLive = !tab.isSnapshot();
Michael Kolb4bf79712011-07-14 14:18:12 -07001490 }
1491 final MenuItem back = menu.findItem(R.id.back_menu_id);
1492 back.setEnabled(canGoBack);
1493
1494 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1495 home.setEnabled(!isHome);
1496
1497 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1498 forward.setEnabled(canGoForward);
1499
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001500 final MenuItem source = menu.findItem(isInLoad() ? R.id.stop_menu_id
1501 : R.id.reload_menu_id);
Michael Kolb4bf79712011-07-14 14:18:12 -07001502 final MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolb7ab75ee2011-07-14 16:36:38 -07001503 if (source != null && dest != null) {
1504 dest.setTitle(source.getTitle());
1505 dest.setIcon(source.getIcon());
1506 }
John Recke1a03a32011-09-14 17:04:16 -07001507 menu.setGroupVisible(R.id.NAV_MENU, isLive);
Michael Kolb4bf79712011-07-14 14:18:12 -07001508
1509 // decide whether to show the share link option
1510 PackageManager pm = mActivity.getPackageManager();
1511 Intent send = new Intent(Intent.ACTION_SEND);
1512 send.setType("text/plain");
1513 ResolveInfo ri = pm.resolveActivity(send,
1514 PackageManager.MATCH_DEFAULT_ONLY);
1515 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1516
1517 boolean isNavDump = mSettings.enableNavDump();
1518 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1519 nav.setVisible(isNavDump);
1520 nav.setEnabled(isNavDump);
1521
1522 boolean showDebugSettings = mSettings.isDebugEnabled();
John Reck42229bc2011-08-19 13:26:43 -07001523 final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
1524 uaSwitcher.setChecked(isDesktopUa);
John Recke1a03a32011-09-14 17:04:16 -07001525 menu.setGroupVisible(R.id.LIVE_MENU, isLive);
1526 menu.setGroupVisible(R.id.SNAPSHOT_MENU, !isLive);
Michael Kolb315d5022011-10-13 12:47:11 -07001527 menu.setGroupVisible(R.id.COMBO_MENU, false);
Michael Kolb4bf79712011-07-14 14:18:12 -07001528
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001529 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001530 }
1531
Michael Kolb8233fac2010-10-26 16:08:53 -07001532 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001533 if (null == getCurrentTopWebView()) {
1534 return false;
1535 }
1536 if (mMenuIsDown) {
1537 // The shortcut action consumes the MENU. Even if it is still down,
1538 // it won't trigger the next shortcut action. In the case of the
1539 // shortcut action triggering a new activity, like Bookmarks, we
1540 // won't get onKeyUp for MENU. So it is important to reset it here.
1541 mMenuIsDown = false;
1542 }
Michael Kolb3ca12752011-07-20 13:52:25 -07001543 if (mUi.onOptionsItemSelected(item)) {
1544 // ui callback handled it
1545 return true;
1546 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001547 switch (item.getItemId()) {
1548 // -- Main menu
1549 case R.id.new_tab_menu_id:
1550 openTabToHomePage();
1551 break;
1552
1553 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001554 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001555 break;
1556
1557 case R.id.goto_menu_id:
1558 editUrl();
1559 break;
1560
1561 case R.id.bookmarks_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001562 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
1563 break;
1564
1565 case R.id.history_menu_id:
1566 bookmarksOrHistoryPicker(ComboViews.History);
1567 break;
1568
1569 case R.id.snapshots_menu_id:
1570 bookmarksOrHistoryPicker(ComboViews.Snapshots);
Michael Kolb8233fac2010-10-26 16:08:53 -07001571 break;
1572
Michael Kolb8233fac2010-10-26 16:08:53 -07001573 case R.id.add_bookmark_menu_id:
Michael Kolb80f75082012-04-10 10:50:06 -07001574 bookmarkCurrentPage();
Michael Kolb8233fac2010-10-26 16:08:53 -07001575 break;
1576
1577 case R.id.stop_reload_menu_id:
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001578 if (isInLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001579 stopLoading();
1580 } else {
1581 getCurrentTopWebView().reload();
1582 }
1583 break;
1584
1585 case R.id.back_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001586 getCurrentTab().goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07001587 break;
1588
1589 case R.id.forward_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001590 getCurrentTab().goForward();
Michael Kolb8233fac2010-10-26 16:08:53 -07001591 break;
1592
1593 case R.id.close_menu_id:
1594 // Close the subwindow if it exists.
1595 if (mTabControl.getCurrentSubWindow() != null) {
1596 dismissSubWindow(mTabControl.getCurrentTab());
1597 break;
1598 }
1599 closeCurrentTab();
1600 break;
1601
1602 case R.id.homepage_menu_id:
1603 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07001604 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07001605 break;
1606
1607 case R.id.preferences_menu_id:
Michael Kolb80f75082012-04-10 10:50:06 -07001608 openPreferences();
Michael Kolb8233fac2010-10-26 16:08:53 -07001609 break;
1610
1611 case R.id.find_menu_id:
Michael Kolbe11b9212012-04-13 13:39:54 -07001612 findOnPage();
Michael Kolb8233fac2010-10-26 16:08:53 -07001613 break;
1614
John Reck2bc80422011-06-30 15:11:49 -07001615 case R.id.save_snapshot_menu_id:
1616 final Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07001617 if (source == null) break;
John Reck68234a92012-04-19 15:27:12 -07001618 new SaveSnapshotTask(source).execute();
Leon Scrogginsac993842011-02-02 12:54:07 -05001619 break;
1620
Michael Kolb8233fac2010-10-26 16:08:53 -07001621 case R.id.page_info_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001622 showPageInfo();
Michael Kolb8233fac2010-10-26 16:08:53 -07001623 break;
1624
John Recke1a03a32011-09-14 17:04:16 -07001625 case R.id.snapshot_go_live:
1626 goLive();
1627 return true;
1628
Michael Kolb8233fac2010-10-26 16:08:53 -07001629 case R.id.share_page_menu_id:
1630 Tab currentTab = mTabControl.getCurrentTab();
1631 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001632 return false;
1633 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001634 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001635 break;
1636
1637 case R.id.dump_nav_menu_id:
1638 getCurrentTopWebView().debugDump();
1639 break;
1640
Michael Kolb8233fac2010-10-26 16:08:53 -07001641 case R.id.zoom_in_menu_id:
1642 getCurrentTopWebView().zoomIn();
1643 break;
1644
1645 case R.id.zoom_out_menu_id:
1646 getCurrentTopWebView().zoomOut();
1647 break;
1648
1649 case R.id.view_downloads_menu_id:
1650 viewDownloads();
1651 break;
1652
John Reck42229bc2011-08-19 13:26:43 -07001653 case R.id.ua_desktop_menu_id:
Michael Kolb80f75082012-04-10 10:50:06 -07001654 toggleUserAgent();
John Reck42229bc2011-08-19 13:26:43 -07001655 break;
1656
Michael Kolb8233fac2010-10-26 16:08:53 -07001657 case R.id.window_one_menu_id:
1658 case R.id.window_two_menu_id:
1659 case R.id.window_three_menu_id:
1660 case R.id.window_four_menu_id:
1661 case R.id.window_five_menu_id:
1662 case R.id.window_six_menu_id:
1663 case R.id.window_seven_menu_id:
1664 case R.id.window_eight_menu_id:
1665 {
1666 int menuid = item.getItemId();
1667 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1668 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1669 Tab desiredTab = mTabControl.getTab(id);
1670 if (desiredTab != null &&
1671 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001672 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001673 }
1674 break;
1675 }
1676 }
1677 }
1678 break;
1679
1680 default:
1681 return false;
1682 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001683 return true;
1684 }
1685
John Reck68234a92012-04-19 15:27:12 -07001686 private class SaveSnapshotTask extends AsyncTask<Void, Void, Long>
1687 implements OnCancelListener {
1688
1689 private Tab mTab;
1690 private Dialog mProgressDialog;
1691 private ContentValues mValues;
1692
1693 private SaveSnapshotTask(Tab tab) {
1694 mTab = tab;
1695 }
1696
1697 @Override
1698 protected void onPreExecute() {
1699 CharSequence message = mActivity.getText(R.string.saving_snapshot);
1700 mProgressDialog = ProgressDialog.show(mActivity, null, message,
1701 true, true, this);
1702 mValues = mTab.createSnapshotValues();
1703 }
1704
1705 @Override
1706 protected Long doInBackground(Void... params) {
1707 if (!mTab.saveViewState(mValues)) {
1708 return null;
1709 }
1710 if (isCancelled()) {
1711 String path = mValues.getAsString(Snapshots.VIEWSTATE_PATH);
1712 File file = mActivity.getFileStreamPath(path);
1713 if (!file.delete()) {
1714 file.deleteOnExit();
1715 }
1716 return null;
1717 }
1718 final ContentResolver cr = mActivity.getContentResolver();
1719 Uri result = cr.insert(Snapshots.CONTENT_URI, mValues);
1720 if (result == null) {
1721 return null;
1722 }
1723 long id = ContentUris.parseId(result);
1724 return id;
1725 }
1726
1727 @Override
1728 protected void onPostExecute(Long id) {
1729 if (isCancelled()) {
1730 return;
1731 }
1732 mProgressDialog.dismiss();
1733 if (id == null) {
1734 Toast.makeText(mActivity, R.string.snapshot_failed,
1735 Toast.LENGTH_SHORT).show();
1736 return;
1737 }
1738 Bundle b = new Bundle();
1739 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
1740 mUi.showComboView(ComboViews.Snapshots, b);
1741 }
1742
1743 @Override
1744 public void onCancel(DialogInterface dialog) {
1745 cancel(true);
1746 }
1747 }
1748
Michael Kolb80f75082012-04-10 10:50:06 -07001749 @Override
1750 public void toggleUserAgent() {
1751 WebView web = getCurrentWebView();
1752 mSettings.toggleDesktopUseragent(web);
1753 web.loadUrl(web.getOriginalUrl());
1754 }
1755
1756 @Override
1757 public void findOnPage() {
1758 getCurrentTopWebView().showFindDialog(null, true);
1759 }
1760
1761 @Override
1762 public void openPreferences() {
1763 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1764 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1765 getCurrentTopWebView().getUrl());
1766 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1767 }
1768
1769 @Override
1770 public void bookmarkCurrentPage() {
1771 Intent bookmarkIntent = createBookmarkCurrentPageIntent(false);
1772 if (bookmarkIntent != null) {
1773 mActivity.startActivity(bookmarkIntent);
1774 }
1775 }
1776
John Recke1a03a32011-09-14 17:04:16 -07001777 private void goLive() {
1778 Tab t = getCurrentTab();
1779 t.loadUrl(t.getUrl(), null);
1780 }
1781
Michael Kolb315d5022011-10-13 12:47:11 -07001782 @Override
1783 public void showPageInfo() {
1784 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
1785 }
1786
Michael Kolb8233fac2010-10-26 16:08:53 -07001787 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001788 // Let the History and Bookmark fragments handle menus they created.
1789 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1790 return false;
1791 }
1792
Michael Kolb8233fac2010-10-26 16:08:53 -07001793 int id = item.getItemId();
1794 boolean result = true;
1795 switch (id) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001796 // -- Browser context menu
1797 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001798 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001799 case R.id.copy_link_context_menu_id:
1800 final WebView webView = getCurrentTopWebView();
1801 if (null == webView) {
1802 result = false;
1803 break;
1804 }
1805 final HashMap<String, WebView> hrefMap =
1806 new HashMap<String, WebView>();
1807 hrefMap.put("webview", webView);
1808 final Message msg = mHandler.obtainMessage(
1809 FOCUS_NODE_HREF, id, 0, hrefMap);
1810 webView.requestFocusNodeHref(msg);
1811 break;
1812
1813 default:
1814 // For other context menus
1815 result = onOptionsItemSelected(item);
1816 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001817 return result;
1818 }
1819
1820 /**
1821 * support programmatically opening the context menu
1822 */
1823 public void openContextMenu(View view) {
1824 mActivity.openContextMenu(view);
1825 }
1826
1827 /**
1828 * programmatically open the options menu
1829 */
1830 public void openOptionsMenu() {
1831 mActivity.openOptionsMenu();
1832 }
1833
1834 public boolean onMenuOpened(int featureId, Menu menu) {
1835 if (mOptionsMenuOpen) {
1836 if (mConfigChanged) {
1837 // We do not need to make any changes to the state of the
1838 // title bar, since the only thing that happened was a
1839 // change in orientation
1840 mConfigChanged = false;
1841 } else {
1842 if (!mExtendedMenuOpen) {
1843 mExtendedMenuOpen = true;
1844 mUi.onExtendedMenuOpened();
1845 } else {
1846 // Switching the menu back to icon view, so show the
1847 // title bar once again.
1848 mExtendedMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001849 mUi.onExtendedMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001850 }
1851 }
1852 } else {
1853 // The options menu is closed, so open it, and show the title
1854 mOptionsMenuOpen = true;
1855 mConfigChanged = false;
1856 mExtendedMenuOpen = false;
1857 mUi.onOptionsMenuOpened();
1858 }
1859 return true;
1860 }
1861
1862 public void onOptionsMenuClosed(Menu menu) {
1863 mOptionsMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001864 mUi.onOptionsMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001865 }
1866
1867 public void onContextMenuClosed(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001868 mUi.onContextMenuClosed(menu, isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001869 }
1870
1871 // Helper method for getting the top window.
1872 @Override
1873 public WebView getCurrentTopWebView() {
1874 return mTabControl.getCurrentTopWebView();
1875 }
1876
1877 @Override
1878 public WebView getCurrentWebView() {
1879 return mTabControl.getCurrentWebView();
1880 }
1881
1882 /*
1883 * This method is called as a result of the user selecting the options
1884 * menu to see the download window. It shows the download window on top of
1885 * the current window.
1886 */
1887 void viewDownloads() {
1888 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1889 mActivity.startActivity(intent);
1890 }
1891
John Reck30b065e2011-07-19 10:58:05 -07001892 int getActionModeHeight() {
1893 TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
1894 new int[] { android.R.attr.actionBarSize });
1895 int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
1896 actionBarSizeTypedArray.recycle();
1897 return size;
1898 }
1899
Michael Kolb8233fac2010-10-26 16:08:53 -07001900 // action mode
1901
1902 void onActionModeStarted(ActionMode mode) {
1903 mUi.onActionModeStarted(mode);
1904 mActionMode = mode;
1905 }
1906
1907 /*
1908 * True if a custom ActionMode (i.e. find or select) is in use.
1909 */
1910 @Override
1911 public boolean isInCustomActionMode() {
1912 return mActionMode != null;
1913 }
1914
1915 /*
1916 * End the current ActionMode.
1917 */
1918 @Override
1919 public void endActionMode() {
1920 if (mActionMode != null) {
1921 mActionMode.finish();
1922 }
1923 }
1924
1925 /*
1926 * Called by find and select when they are finished. Replace title bars
1927 * as necessary.
1928 */
1929 public void onActionModeFinished(ActionMode mode) {
1930 if (!isInCustomActionMode()) return;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001931 mUi.onActionModeFinished(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001932 mActionMode = null;
1933 }
1934
1935 boolean isInLoad() {
Michael Kolbc5b0b2d2011-11-29 16:13:35 -08001936 final Tab tab = getCurrentTab();
1937 return (tab != null) && tab.inPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07001938 }
1939
1940 // bookmark handling
1941
1942 /**
1943 * add the current page as a bookmark to the given folder id
1944 * @param folderId use -1 for the default folder
John Reckd3e4d5b2011-07-13 15:48:43 -07001945 * @param editExisting If true, check to see whether the site is already
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001946 * bookmarked, and if it is, edit that bookmark. If false, and
1947 * the site is already bookmarked, do not attempt to edit the
1948 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001949 */
1950 @Override
John Reckd3e4d5b2011-07-13 15:48:43 -07001951 public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
John Recka60fffa2011-09-06 16:30:29 -07001952 WebView w = getCurrentTopWebView();
1953 if (w == null) {
1954 return null;
1955 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001956 Intent i = new Intent(mActivity,
1957 AddBookmarkPage.class);
Michael Kolb8233fac2010-10-26 16:08:53 -07001958 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1959 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1960 String touchIconUrl = w.getTouchIconUrl();
1961 if (touchIconUrl != null) {
1962 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1963 WebSettings settings = w.getSettings();
1964 if (settings != null) {
1965 i.putExtra(AddBookmarkPage.USER_AGENT,
1966 settings.getUserAgentString());
1967 }
1968 }
1969 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1970 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1971 getDesiredThumbnailHeight(mActivity)));
1972 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07001973 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001974 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1975 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001976 // Put the dialog at the upper right of the screen, covering the
1977 // star on the title bar.
1978 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07001979 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07001980 }
1981
1982 // file chooser
Ben Murdoch8cad4132012-01-11 10:56:43 +00001983 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001984 mUploadHandler = new UploadHandler(this);
Ben Murdoch8cad4132012-01-11 10:56:43 +00001985 mUploadHandler.openFileChooser(uploadMsg, acceptType, capture);
Michael Kolb8233fac2010-10-26 16:08:53 -07001986 }
1987
1988 // thumbnails
1989
1990 /**
1991 * Return the desired width for thumbnail screenshots, which are stored in
1992 * the database, and used on the bookmarks screen.
1993 * @param context Context for finding out the density of the screen.
1994 * @return desired width for thumbnail screenshot.
1995 */
1996 static int getDesiredThumbnailWidth(Context context) {
1997 return context.getResources().getDimensionPixelOffset(
1998 R.dimen.bookmarkThumbnailWidth);
1999 }
2000
2001 /**
2002 * Return the desired height for thumbnail screenshots, which are stored in
2003 * the database, and used on the bookmarks screen.
2004 * @param context Context for finding out the density of the screen.
2005 * @return desired height for thumbnail screenshot.
2006 */
2007 static int getDesiredThumbnailHeight(Context context) {
2008 return context.getResources().getDimensionPixelOffset(
2009 R.dimen.bookmarkThumbnailHeight);
2010 }
2011
John Reck8cc92352011-07-06 17:41:52 -07002012 static Bitmap createScreenshot(WebView view, int width, int height) {
John Reckd7dd9b22011-08-30 09:18:29 -07002013 if (view == null || view.getContentHeight() == 0
2014 || view.getContentWidth() == 0) {
2015 return null;
2016 }
John Reck5c6ac2f2011-01-05 10:18:03 -08002017 // We render to a bitmap 2x the desired size so that we can then
2018 // re-scale it with filtering since canvas.scale doesn't filter
2019 // This helps reduce aliasing at the cost of being slightly blurry
2020 final int filter_scale = 2;
John Reckd7dd9b22011-08-30 09:18:29 -07002021 int scaledWidth = width * filter_scale;
2022 int scaledHeight = height * filter_scale;
2023 if (sThumbnailBitmap == null || sThumbnailBitmap.getWidth() != scaledWidth
2024 || sThumbnailBitmap.getHeight() != scaledHeight) {
2025 if (sThumbnailBitmap != null) {
2026 sThumbnailBitmap.recycle();
2027 sThumbnailBitmap = null;
2028 }
2029 sThumbnailBitmap =
2030 Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.RGB_565);
Michael Kolb8233fac2010-10-26 16:08:53 -07002031 }
John Reckd7dd9b22011-08-30 09:18:29 -07002032 Canvas canvas = new Canvas(sThumbnailBitmap);
2033 int contentWidth = view.getContentWidth();
2034 float overviewScale = scaledWidth / (view.getScale() * contentWidth);
2035 if (view instanceof BrowserWebView) {
2036 int dy = -((BrowserWebView)view).getTitleHeight();
2037 canvas.translate(0, dy * overviewScale);
2038 }
2039
2040 canvas.scale(overviewScale, overviewScale);
2041
2042 if (view instanceof BrowserWebView) {
2043 ((BrowserWebView)view).drawContent(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07002044 } else {
John Reckd7dd9b22011-08-30 09:18:29 -07002045 view.draw(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07002046 }
John Reckd7dd9b22011-08-30 09:18:29 -07002047 Bitmap ret = Bitmap.createScaledBitmap(sThumbnailBitmap,
2048 width, height, true);
Dianne Hackborn43cfe8a2011-08-02 16:59:35 -07002049 canvas.setBitmap(null);
John Reck5c6ac2f2011-01-05 10:18:03 -08002050 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07002051 }
2052
John Reck34ef2672011-02-10 11:30:55 -08002053 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002054 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07002055 // FIXME: Would like to make sure there is actually something to
2056 // draw, but the API for that (WebViewCore.pictureReady()) is not
2057 // currently accessible here.
2058
John Reck34ef2672011-02-10 11:30:55 -08002059 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08002060 if (view == null) {
2061 // Tab was destroyed
2062 return;
2063 }
John Reck34ef2672011-02-10 11:30:55 -08002064 final String url = tab.getUrl();
2065 final String originalUrl = view.getOriginalUrl();
John Reck34ef2672011-02-10 11:30:55 -08002066 if (TextUtils.isEmpty(url)) {
2067 return;
2068 }
2069
2070 // Only update thumbnails for web urls (http(s)://), not for
2071 // about:, javascript:, data:, etc...
2072 // Unless it is a bookmarked site, then always update
2073 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2074 return;
2075 }
2076
Michael Kolb8233fac2010-10-26 16:08:53 -07002077 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2078 getDesiredThumbnailHeight(mActivity));
2079 if (bm == null) {
2080 return;
2081 }
2082
2083 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002084 new AsyncTask<Void, Void, Void>() {
2085 @Override
2086 protected Void doInBackground(Void... unused) {
2087 Cursor cursor = null;
2088 try {
2089 // TODO: Clean this up
2090 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2091 if (cursor != null && cursor.moveToFirst()) {
2092 final ByteArrayOutputStream os =
2093 new ByteArrayOutputStream();
2094 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002095
John Reck34ef2672011-02-10 11:30:55 -08002096 ContentValues values = new ContentValues();
2097 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002098
John Reck34ef2672011-02-10 11:30:55 -08002099 do {
John Reck617fd832011-02-16 14:35:59 -08002100 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002101 cr.update(Images.CONTENT_URI, values, null, null);
2102 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002103 }
John Reck34ef2672011-02-10 11:30:55 -08002104 } catch (IllegalStateException e) {
2105 // Ignore
2106 } finally {
2107 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002108 }
John Reck34ef2672011-02-10 11:30:55 -08002109 return null;
2110 }
2111 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002112 }
2113
2114 private class Copy implements OnMenuItemClickListener {
2115 private CharSequence mText;
2116
2117 public boolean onMenuItemClick(MenuItem item) {
2118 copy(mText);
2119 return true;
2120 }
2121
2122 public Copy(CharSequence toCopy) {
2123 mText = toCopy;
2124 }
2125 }
2126
Leon Scroggins63c02662010-11-18 15:16:27 -05002127 private static class Download implements OnMenuItemClickListener {
2128 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002129 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002130 private boolean mPrivateBrowsing;
George Mount387d45d2011-10-07 15:57:53 -07002131 private static final String FALLBACK_EXTENSION = "dat";
2132 private static final String IMAGE_BASE_FORMAT = "yyyy-MM-dd-HH-mm-ss-";
Michael Kolb8233fac2010-10-26 16:08:53 -07002133
2134 public boolean onMenuItemClick(MenuItem item) {
George Mount387d45d2011-10-07 15:57:53 -07002135 if (DataUri.isDataUri(mText)) {
2136 saveDataUri();
2137 } else {
2138 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
2139 null, null, mPrivateBrowsing);
2140 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002141 return true;
2142 }
2143
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002144 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002145 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002146 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002147 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002148 }
George Mount387d45d2011-10-07 15:57:53 -07002149
2150 /**
2151 * Treats mText as a data URI and writes its contents to a file
2152 * based on the current time.
2153 */
2154 private void saveDataUri() {
2155 FileOutputStream outputStream = null;
2156 try {
2157 DataUri uri = new DataUri(mText);
2158 File target = getTarget(uri);
2159 outputStream = new FileOutputStream(target);
2160 outputStream.write(uri.getData());
2161 final DownloadManager manager =
2162 (DownloadManager) mActivity.getSystemService(Context.DOWNLOAD_SERVICE);
2163 manager.addCompletedDownload(target.getName(),
2164 mActivity.getTitle().toString(), false,
2165 uri.getMimeType(), target.getAbsolutePath(),
George Mount7501bf42011-11-17 11:17:03 -08002166 (long)uri.getData().length, true);
George Mount387d45d2011-10-07 15:57:53 -07002167 } catch (IOException e) {
2168 Log.e(LOGTAG, "Could not save data URL");
2169 } finally {
2170 if (outputStream != null) {
2171 try {
2172 outputStream.close();
2173 } catch (IOException e) {
2174 // ignore close errors
2175 }
2176 }
2177 }
2178 }
2179
2180 /**
2181 * Creates a File based on the current time stamp and uses
2182 * the mime type of the DataUri to get the extension.
2183 */
2184 private File getTarget(DataUri uri) throws IOException {
2185 File dir = mActivity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
2186 DateFormat format = new SimpleDateFormat(IMAGE_BASE_FORMAT);
2187 String nameBase = format.format(new Date());
2188 String mimeType = uri.getMimeType();
2189 MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
2190 String extension = mimeTypeMap.getExtensionFromMimeType(mimeType);
2191 if (extension == null) {
2192 Log.w(LOGTAG, "Unknown mime type in data URI" + mimeType);
2193 extension = FALLBACK_EXTENSION;
2194 }
2195 extension = "." + extension; // createTempFile needs the '.'
2196 File targetFile = File.createTempFile(nameBase, extension, dir);
2197 return targetFile;
2198 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002199 }
2200
Cary Clark8974d282010-11-22 10:46:05 -05002201 private static class SelectText implements OnMenuItemClickListener {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002202 private WebViewClassic mWebView;
Cary Clark8974d282010-11-22 10:46:05 -05002203
2204 public boolean onMenuItemClick(MenuItem item) {
2205 if (mWebView != null) {
2206 return mWebView.selectText();
2207 }
2208 return false;
2209 }
2210
2211 public SelectText(WebView webView) {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002212 mWebView = WebViewClassic.fromWebView(webView);
Cary Clark8974d282010-11-22 10:46:05 -05002213 }
2214
2215 }
2216
Michael Kolb8233fac2010-10-26 16:08:53 -07002217 /********************** TODO: UI stuff *****************************/
2218
2219 // these methods have been copied, they still need to be cleaned up
2220
2221 /****************** tabs ***************************************************/
2222
2223 // basic tab interactions:
2224
2225 // it is assumed that tabcontrol already knows about the tab
2226 protected void addTab(Tab tab) {
2227 mUi.addTab(tab);
2228 }
2229
2230 protected void removeTab(Tab tab) {
2231 mUi.removeTab(tab);
2232 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002233 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002234 }
2235
Michael Kolbf2055602011-04-09 17:20:03 -07002236 @Override
2237 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002238 // monkey protection against delayed start
2239 if (tab != null) {
2240 mTabControl.setCurrentTab(tab);
2241 // the tab is guaranteed to have a webview after setCurrentTab
2242 mUi.setActiveTab(tab);
2243 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002244 }
2245
John Reck8bcafc12011-08-29 16:43:02 -07002246 protected void closeEmptyTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002247 Tab current = mTabControl.getCurrentTab();
2248 if (current != null
2249 && current.getWebView().copyBackForwardList().getSize() == 0) {
John Reck8bcafc12011-08-29 16:43:02 -07002250 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002251 }
2252 }
2253
John Reck26b18322011-06-21 13:08:58 -07002254 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002255 // Dismiss the subwindow if applicable.
2256 dismissSubWindow(appTab);
2257 // Since we might kill the WebView, remove it from the
2258 // content view first.
2259 mUi.detachTab(appTab);
2260 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002261 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002262 // TODO: analyze why the remove and add are necessary
2263 mUi.attachTab(appTab);
2264 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002265 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002266 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002267 } else {
2268 // If the tab was the current tab, we have to attach
2269 // it to the view system again.
2270 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002271 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002272 }
2273 }
2274
2275 // Remove the sub window if it exists. Also called by TabControl when the
2276 // user clicks the 'X' to dismiss a sub window.
2277 public void dismissSubWindow(Tab tab) {
2278 removeSubWindow(tab);
2279 // dismiss the subwindow. This will destroy the WebView.
2280 tab.dismissSubWindow();
Michael Kolbe8c97572011-11-21 14:03:56 -08002281 WebView wv = getCurrentTopWebView();
2282 if (wv != null) {
2283 wv.requestFocus();
2284 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002285 }
2286
2287 @Override
2288 public void removeSubWindow(Tab t) {
2289 if (t.getSubWebView() != null) {
2290 mUi.removeSubWindow(t.getSubViewContainer());
2291 }
2292 }
2293
2294 @Override
2295 public void attachSubWindow(Tab tab) {
2296 if (tab.getSubWebView() != null) {
2297 mUi.attachSubWindow(tab.getSubViewContainer());
2298 getCurrentTopWebView().requestFocus();
2299 }
2300 }
2301
Mathew Inwood29721c22011-06-29 17:55:24 +01002302 private Tab showPreloadedTab(final UrlData urlData) {
2303 if (!urlData.isPreloaded()) {
2304 return null;
2305 }
2306 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2307 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2308 if (sbQuery != null) {
Mathew Inwood9ad1eac2011-09-15 11:29:50 +01002309 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002310 // Could not submit query. Fallback to regular tab creation
2311 tabControl.destroy();
2312 return null;
2313 }
2314 }
Michael Kolbff6a7482011-07-26 16:37:15 -07002315 // check tab count and make room for new tab
2316 if (!mTabControl.canCreateNewTab()) {
2317 Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
2318 if (leastUsed != null) {
2319 closeTab(leastUsed);
2320 }
2321 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002322 Tab t = tabControl.getTab();
Mathew Inwoode09305e2011-09-02 12:03:26 +01002323 t.refreshIdAfterPreload();
Mathew Inwood29721c22011-06-29 17:55:24 +01002324 mTabControl.addPreloadedTab(t);
2325 addTab(t);
2326 setActiveTab(t);
2327 return t;
2328 }
2329
Michael Kolb7bcafde2011-05-09 13:55:59 -07002330 // open a non inconito tab with the given url data
2331 // and set as active tab
2332 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002333 Tab tab = showPreloadedTab(urlData);
2334 if (tab == null) {
2335 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002336 if ((tab != null) && !urlData.isEmpty()) {
2337 loadUrlDataIn(tab, urlData);
2338 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002339 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002340 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002341 }
2342
Michael Kolb843510f2010-12-09 10:51:49 -08002343 @Override
2344 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002345 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002346 }
2347
Michael Kolb8233fac2010-10-26 16:08:53 -07002348 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002349 public Tab openIncognitoTab() {
2350 return openTab(INCOGNITO_URI, true, true, false);
2351 }
2352
2353 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002354 public Tab openTab(String url, boolean incognito, boolean setActive,
2355 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002356 return openTab(url, incognito, setActive, useCurrent, null);
2357 }
2358
2359 @Override
2360 public Tab openTab(String url, Tab parent, boolean setActive,
2361 boolean useCurrent) {
2362 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2363 setActive, useCurrent, parent);
2364 }
2365
2366 public Tab openTab(String url, boolean incognito, boolean setActive,
2367 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002368 Tab tab = createNewTab(incognito, setActive, useCurrent);
2369 if (tab != null) {
John Reck5949c662011-05-27 09:52:29 -07002370 if (parent != null && parent != tab) {
2371 parent.addChildTab(tab);
2372 }
Michael Kolb519d2282011-05-09 17:03:19 -07002373 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002374 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002375 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002376 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002377 return tab;
2378 }
2379
2380 // this method will attempt to create a new tab
2381 // incognito: private browsing tab
2382 // setActive: ste tab as current tab
2383 // useCurrent: if no new tab can be created, return current tab
2384 private Tab createNewTab(boolean incognito, boolean setActive,
2385 boolean useCurrent) {
2386 Tab tab = null;
2387 if (mTabControl.canCreateNewTab()) {
2388 tab = mTabControl.createNewTab(incognito);
2389 addTab(tab);
2390 if (setActive) {
2391 setActiveTab(tab);
2392 }
2393 } else {
2394 if (useCurrent) {
2395 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002396 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002397 } else {
2398 mUi.showMaxTabsWarning();
2399 }
2400 }
2401 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002402 }
2403
John Reck2bc80422011-06-30 15:11:49 -07002404 @Override
2405 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2406 SnapshotTab tab = null;
2407 if (mTabControl.canCreateNewTab()) {
2408 tab = mTabControl.createSnapshotTab(snapshotId);
2409 addTab(tab);
2410 if (setActive) {
2411 setActiveTab(tab);
2412 }
2413 } else {
2414 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07002415 }
2416 return tab;
2417 }
2418
Michael Kolb8233fac2010-10-26 16:08:53 -07002419 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002420 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002421 * @return boolean True if we successfully switched to a different tab. If
2422 * the indexth tab is null, or if that tab is the same as
2423 * the current one, return false.
2424 */
2425 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002426 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002427 Tab currentTab = mTabControl.getCurrentTab();
2428 if (tab == null || tab == currentTab) {
2429 return false;
2430 }
2431 setActiveTab(tab);
2432 return true;
2433 }
2434
2435 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002436 public void closeCurrentTab() {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002437 closeCurrentTab(false);
2438 }
2439
2440 protected void closeCurrentTab(boolean andQuit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002441 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07002442 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07002443 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08002444 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002445 return;
2446 }
Michael Kolbc831b632011-05-11 09:30:34 -07002447 final Tab current = mTabControl.getCurrentTab();
2448 final int pos = mTabControl.getCurrentPosition();
2449 Tab newTab = current.getParent();
2450 if (newTab == null) {
2451 newTab = mTabControl.getTab(pos + 1);
2452 if (newTab == null) {
2453 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002454 }
2455 }
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002456 if (andQuit) {
2457 mTabControl.setCurrentTab(newTab);
2458 closeTab(current);
2459 } else if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002460 // Close window
2461 closeTab(current);
2462 }
2463 }
2464
2465 /**
2466 * Close the tab, remove its associated title bar, and adjust mTabControl's
2467 * current tab to a valid value.
2468 */
2469 @Override
2470 public void closeTab(Tab tab) {
John Reck28263772011-10-11 17:13:42 -07002471 if (tab == mTabControl.getCurrentTab()) {
2472 closeCurrentTab();
2473 } else {
2474 removeTab(tab);
2475 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002476 }
2477
Michael Kolb8233fac2010-10-26 16:08:53 -07002478 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07002479 protected void loadUrlFromContext(String url) {
2480 Tab tab = getCurrentTab();
2481 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002482 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07002483 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002484 url = UrlUtils.smartUrlFilter(url);
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002485 if (!WebViewClassic.fromWebView(view).getWebViewClient().
2486 shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07002487 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07002488 }
2489 }
2490 }
2491
2492 /**
2493 * Load the URL into the given WebView and update the title bar
2494 * to reflect the new load. Call this instead of WebView.loadUrl
2495 * directly.
2496 * @param view The WebView used to load url.
2497 * @param url The URL to load.
2498 */
John Reck71e51422011-07-01 16:49:28 -07002499 @Override
2500 public void loadUrl(Tab tab, String url) {
John Reck26b18322011-06-21 13:08:58 -07002501 loadUrl(tab, url, null);
2502 }
2503
2504 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
2505 if (tab != null) {
2506 dismissSubWindow(tab);
2507 tab.loadUrl(url, headers);
Michael Kolba53c9892011-10-05 13:31:40 -07002508 mUi.onProgressChanged(tab);
John Reck26b18322011-06-21 13:08:58 -07002509 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002510 }
2511
2512 /**
2513 * Load UrlData into a Tab and update the title bar to reflect the new
2514 * load. Call this instead of UrlData.loadIn directly.
2515 * @param t The Tab used to load.
2516 * @param data The UrlData being loaded.
2517 */
2518 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07002519 if (data != null) {
Michael Kolb5ff5c8b2012-05-03 11:37:58 -07002520 if (data.isPreloaded()) {
Michael Kolb14612442011-06-24 13:06:29 -07002521 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07002522 } else {
2523 loadUrl(t, data.mUrl, data.mHeaders);
2524 }
2525 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002526 }
2527
John Reck30c714c2010-12-16 17:30:34 -08002528 @Override
2529 public void onUserCanceledSsl(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08002530 // TODO: Figure out the "right" behavior
John Reckef654f12011-07-12 16:42:08 -07002531 if (tab.canGoBack()) {
2532 tab.goBack();
John Reck30c714c2010-12-16 17:30:34 -08002533 } else {
John Reckef654f12011-07-12 16:42:08 -07002534 tab.loadUrl(mSettings.getHomePage(), null);
John Reck30c714c2010-12-16 17:30:34 -08002535 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002536 }
2537
2538 void goBackOnePageOrQuit() {
2539 Tab current = mTabControl.getCurrentTab();
2540 if (current == null) {
2541 /*
2542 * Instead of finishing the activity, simply push this to the back
2543 * of the stack and let ActivityManager to choose the foreground
2544 * activity. As BrowserActivity is singleTask, it will be always the
2545 * root of the task. So we can use either true or false for
2546 * moveTaskToBack().
2547 */
2548 mActivity.moveTaskToBack(true);
2549 return;
2550 }
John Reckef654f12011-07-12 16:42:08 -07002551 if (current.canGoBack()) {
2552 current.goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07002553 } else {
2554 // Check to see if we are closing a window that was created by
2555 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002556 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002557 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002558 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002559 // Now we close the other tab
2560 closeTab(current);
2561 } else {
Michael Kolbe28b3472011-08-04 16:54:31 -07002562 if ((current.getAppId() != null) || current.closeOnBack()) {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002563 closeCurrentTab(true);
Michael Kolbe28b3472011-08-04 16:54:31 -07002564 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002565 /*
2566 * Instead of finishing the activity, simply push this to the back
2567 * of the stack and let ActivityManager to choose the foreground
2568 * activity. As BrowserActivity is singleTask, it will be always the
2569 * root of the task. So we can use either true or false for
2570 * moveTaskToBack().
2571 */
2572 mActivity.moveTaskToBack(true);
2573 }
2574 }
2575 }
2576
2577 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002578 * helper method for key handler
2579 * returns the current tab if it can't advance
2580 */
Michael Kolbc831b632011-05-11 09:30:34 -07002581 private Tab getNextTab() {
Michael Kolbf5261da2011-12-15 15:07:35 -08002582 int pos = mTabControl.getCurrentPosition() + 1;
2583 if (pos >= mTabControl.getTabCount()) {
2584 pos = 0;
2585 }
2586 return mTabControl.getTab(pos);
Michael Kolb0035fad2011-03-14 13:25:28 -07002587 }
2588
2589 /**
2590 * helper method for key handler
2591 * returns the current tab if it can't advance
2592 */
Michael Kolbc831b632011-05-11 09:30:34 -07002593 private Tab getPrevTab() {
Michael Kolbf5261da2011-12-15 15:07:35 -08002594 int pos = mTabControl.getCurrentPosition() - 1;
2595 if ( pos < 0) {
2596 pos = mTabControl.getTabCount() - 1;
2597 }
2598 return mTabControl.getTab(pos);
Michael Kolb0035fad2011-03-14 13:25:28 -07002599 }
2600
John Reckbcef87f2012-02-03 14:58:34 -08002601 boolean isMenuOrCtrlKey(int keyCode) {
2602 return (KeyEvent.KEYCODE_MENU == keyCode)
2603 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2604 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode);
2605 }
2606
Michael Kolb0035fad2011-03-14 13:25:28 -07002607 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002608 * handle key events in browser
2609 *
2610 * @param keyCode
2611 * @param event
2612 * @return true if handled, false to pass to super
2613 */
2614 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002615 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002616 // Even if MENU is already held down, we need to call to super to open
2617 // the IME on long press.
John Reckbcef87f2012-02-03 14:58:34 -08002618 if (!noModifiers && isMenuOrCtrlKey(keyCode)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002619 mMenuIsDown = true;
2620 return false;
2621 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002622
Cary Clark8ff8c662010-12-29 15:03:05 -05002623 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07002624 Tab tab = getCurrentTab();
2625 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05002626
Cary Clark160bbb92011-01-10 11:17:07 -05002627 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2628 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002629
Michael Kolb8233fac2010-10-26 16:08:53 -07002630 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002631 case KeyEvent.KEYCODE_TAB:
2632 if (event.isCtrlPressed()) {
2633 if (event.isShiftPressed()) {
2634 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002635 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002636 } else {
2637 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002638 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002639 }
2640 return true;
2641 }
2642 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002643 case KeyEvent.KEYCODE_SPACE:
2644 // WebView/WebTextView handle the keys in the KeyDown. As
2645 // the Activity's shortcut keys are only handled when WebView
2646 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002647 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002648 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002649 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002650 pageDown();
2651 }
2652 return true;
2653 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002654 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002655 event.startTracking();
2656 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07002657 case KeyEvent.KEYCODE_FORWARD:
2658 if (!noModifiers) break;
2659 tab.goForward();
2660 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002661 case KeyEvent.KEYCODE_DPAD_LEFT:
2662 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002663 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05002664 return true;
2665 }
2666 break;
2667 case KeyEvent.KEYCODE_DPAD_RIGHT:
2668 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002669 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05002670 return true;
2671 }
2672 break;
2673 case KeyEvent.KEYCODE_A:
2674 if (ctrl) {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002675 WebViewClassic.fromWebView(webView).selectAll();
Cary Clark8ff8c662010-12-29 15:03:05 -05002676 return true;
2677 }
2678 break;
Michael Kolba4183062011-01-16 10:43:21 -08002679// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002680 case KeyEvent.KEYCODE_C:
2681 if (ctrl) {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002682 WebViewClassic.fromWebView(webView).copySelection();
Cary Clark8ff8c662010-12-29 15:03:05 -05002683 return true;
2684 }
2685 break;
Michael Kolba4183062011-01-16 10:43:21 -08002686// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002687// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002688// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002689// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002690// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002691// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002692// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002693// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002694// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002695// case KeyEvent.KEYCODE_M: // unused
2696// case KeyEvent.KEYCODE_N: // in Chrome: new window
2697// case KeyEvent.KEYCODE_O: // in Chrome: open file
2698// case KeyEvent.KEYCODE_P: // in Chrome: print page
2699// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002700// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002701// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2702 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002703 // we can't use the ctrl/shift flags, they check for
2704 // exclusive use of a modifier
2705 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002706 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002707 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002708 } else {
2709 openTabToHomePage();
2710 }
2711 return true;
2712 }
2713 break;
2714// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2715// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb5ae15bd2011-08-16 17:09:27 -07002716// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002717// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2718// case KeyEvent.KEYCODE_Y: // unused
2719// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002720 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002721 // it is a regular key and webview is not null
2722 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002723 }
2724
John Recke6bf4ab2011-02-24 15:48:05 -08002725 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2726 switch(keyCode) {
2727 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07002728 if (mUi.isWebShowing()) {
Michael Kolb315d5022011-10-13 12:47:11 -07002729 bookmarksOrHistoryPicker(ComboViews.History);
John Recke6bf4ab2011-02-24 15:48:05 -08002730 return true;
2731 }
2732 break;
2733 }
2734 return false;
2735 }
2736
Michael Kolb8233fac2010-10-26 16:08:53 -07002737 boolean onKeyUp(int keyCode, KeyEvent event) {
John Reckbcef87f2012-02-03 14:58:34 -08002738 if (isMenuOrCtrlKey(keyCode)) {
Michael Kolb2814a362011-05-19 15:49:41 -07002739 mMenuIsDown = false;
John Reckbcef87f2012-02-03 14:58:34 -08002740 if (KeyEvent.KEYCODE_MENU == keyCode
2741 && event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002742 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002743 }
2744 }
Cary Clark160bbb92011-01-10 11:17:07 -05002745 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002746 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002747 case KeyEvent.KEYCODE_BACK:
2748 if (event.isTracking() && !event.isCanceled()) {
2749 onBackKey();
2750 return true;
2751 }
2752 break;
2753 }
2754 return false;
2755 }
2756
2757 public boolean isMenuDown() {
2758 return mMenuIsDown;
2759 }
2760
Ben Murdoch8029a772010-11-16 11:58:21 +00002761 public void setupAutoFill(Message message) {
2762 // Open the settings activity at the AutoFill profile fragment so that
2763 // the user can create a new profile. When they return, we will dispatch
2764 // the message so that we can autofill the form using their new profile.
2765 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2766 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2767 AutoFillSettingsFragment.class.getName());
2768 mAutoFillSetupMessage = message;
2769 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2770 }
John Reckb3417f02011-01-14 11:01:05 -08002771
Michael Kolbfbc579a2011-07-07 15:59:33 -07002772 public boolean onSearchRequested() {
Michael Kolb1f9b3562012-04-24 14:38:34 -07002773 mUi.editUrl(false, true);
Michael Kolbfbc579a2011-07-07 15:59:33 -07002774 return true;
2775 }
2776
John Reck1cf4b792011-07-26 10:22:22 -07002777 @Override
2778 public boolean shouldCaptureThumbnails() {
2779 return mUi.shouldCaptureThumbnails();
2780 }
2781
Michael Kolbc3af0672011-08-09 10:24:41 -07002782 @Override
2783 public void setBlockEvents(boolean block) {
2784 mBlockEvents = block;
2785 }
2786
2787 public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002788 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002789 }
2790
2791 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002792 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002793 }
2794
2795 public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002796 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002797 }
2798
2799 public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002800 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002801 }
2802
2803 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002804 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002805 }
2806
Michael Kolb8233fac2010-10-26 16:08:53 -07002807}