blob: 2fb465c086798c9a528af7cf6276ca240ab698e4 [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) {
262 // mCrashRecoverHandler has any previously saved state.
263 mCrashRecoveryHandler.startRecovery(intent);
John Reck847b5322011-04-14 17:02:18 -0700264 }
265
George Mount3636d0a2011-11-21 09:08:21 -0800266 void doStart(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700267 // Unless the last browser usage was within 24 hours, destroy any
268 // remaining incognito tabs.
269
270 Calendar lastActiveDate = icicle != null ?
271 (Calendar) icicle.getSerializable("lastActiveDate") : null;
272 Calendar today = Calendar.getInstance();
273 Calendar yesterday = Calendar.getInstance();
274 yesterday.add(Calendar.DATE, -1);
275
Patrick Scott7d50a932011-02-04 09:27:26 -0500276 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700277 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800278 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700279
Patrick Scott7d50a932011-02-04 09:27:26 -0500280 // Find out if we will restore any state and remember the tab.
Michael Kolbc831b632011-05-11 09:30:34 -0700281 final long currentTabId =
Patrick Scott7d50a932011-02-04 09:27:26 -0500282 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000283
Michael Kolbc831b632011-05-11 09:30:34 -0700284 if (currentTabId == -1) {
Patrick Scott7d50a932011-02-04 09:27:26 -0500285 // Not able to restore so we go ahead and clear session cookies. We
286 // must do this before trying to login the user as we don't want to
287 // clear any session cookies set during login.
288 CookieManager.getInstance().removeSessionCookie();
289 }
290
Patrick Scottd43e75a2011-03-14 14:47:23 -0400291 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500292 new Runnable() {
293 @Override public void run() {
George Mount3636d0a2011-11-21 09:08:21 -0800294 onPreloginFinished(icicle, intent, currentTabId,
295 restoreIncognitoTabs);
Patrick Scott7d50a932011-02-04 09:27:26 -0500296 }
297 });
298 }
299
Michael Kolbc831b632011-05-11 09:30:34 -0700300 private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId,
George Mount3636d0a2011-11-21 09:08:21 -0800301 boolean restoreIncognitoTabs) {
Michael Kolbc831b632011-05-11 09:30:34 -0700302 if (currentTabId == -1) {
John Reck1cf4b792011-07-26 10:22:22 -0700303 BackgroundHandler.execute(new PruneThumbnails(mActivity, null));
George Mount3636d0a2011-11-21 09:08:21 -0800304 if (intent == null) {
305 // This won't happen under common scenarios. The icicle is
306 // not null, but there aren't any tabs to restore.
307 openTabToHomePage();
Michael Kolb7bcafde2011-05-09 13:55:59 -0700308 } else {
George Mount3636d0a2011-11-21 09:08:21 -0800309 final Bundle extra = intent.getExtras();
310 // Create an initial tab.
311 // If the intent is ACTION_VIEW and data is not null, the Browser is
312 // invoked to view the content by another application. In this case,
313 // the tab will be close when exit.
314 UrlData urlData = IntentHandler.getUrlDataFromIntent(intent);
315 Tab t = null;
316 if (urlData.isEmpty()) {
317 t = openTabToHomePage();
318 } else {
319 t = openTab(urlData);
320 }
321 if (t != null) {
322 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
323 }
324 WebView webView = t.getWebView();
325 if (extra != null) {
326 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
327 if (scale > 0 && scale <= 1000) {
328 webView.setInitialScale(scale);
329 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700330 }
331 }
John Reckd8c74522011-06-14 08:45:00 -0700332 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700333 } else {
Michael Kolbc831b632011-05-11 09:30:34 -0700334 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
Patrick Scott7d50a932011-02-04 09:27:26 -0500335 mUi.needsRestoreAllTabs());
John Reck1cf4b792011-07-26 10:22:22 -0700336 List<Tab> tabs = mTabControl.getTabs();
337 ArrayList<Long> restoredTabs = new ArrayList<Long>(tabs.size());
338 for (Tab t : tabs) {
339 restoredTabs.add(t.getId());
340 }
341 BackgroundHandler.execute(new PruneThumbnails(mActivity, restoredTabs));
John Reck52be4782011-08-26 15:37:29 -0700342 if (tabs.size() == 0) {
343 openTabToHomePage();
344 }
John Reck1cf4b792011-07-26 10:22:22 -0700345 mUi.updateTabs(tabs);
Michael Kolb8233fac2010-10-26 16:08:53 -0700346 // TabControl.restoreState() will create a new tab even if
347 // restoring the state fails.
348 setActiveTab(mTabControl.getCurrentTab());
George Mount3636d0a2011-11-21 09:08:21 -0800349 // Intent is non-null when framework thinks the browser should be
350 // launching with a new intent (icicle is null).
351 if (intent != null) {
John Reck9dd4a412011-10-05 14:55:30 -0700352 mIntentHandler.onNewIntent(intent);
353 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700354 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700355 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700356 String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb8233fac2010-10-26 16:08:53 -0700357 if (jsFlags.trim().length() != 0) {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +0000358 WebViewClassic.fromWebView(getCurrentWebView()).setJsFlags(jsFlags);
Michael Kolb8233fac2010-10-26 16:08:53 -0700359 }
George Mount3636d0a2011-11-21 09:08:21 -0800360 if (intent != null
361 && BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
Michael Kolb315d5022011-10-13 12:47:11 -0700362 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
John Reck439c9a52010-12-14 10:04:39 -0800363 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700364 }
365
John Reck1cf4b792011-07-26 10:22:22 -0700366 private static class PruneThumbnails implements Runnable {
367 private Context mContext;
368 private List<Long> mIds;
369
370 PruneThumbnails(Context context, List<Long> preserveIds) {
371 mContext = context.getApplicationContext();
372 mIds = preserveIds;
373 }
374
375 @Override
376 public void run() {
377 ContentResolver cr = mContext.getContentResolver();
378 if (mIds == null || mIds.size() == 0) {
379 cr.delete(Thumbnails.CONTENT_URI, null, null);
380 } else {
381 int length = mIds.size();
382 StringBuilder where = new StringBuilder();
383 where.append(Thumbnails._ID);
384 where.append(" not in (");
385 for (int i = 0; i < length; i++) {
386 where.append(mIds.get(i));
387 if (i < (length - 1)) {
388 where.append(",");
389 }
390 }
391 where.append(")");
392 cr.delete(Thumbnails.CONTENT_URI, where.toString(), null);
393 }
394 }
395
396 }
397
Michael Kolb1514bb72010-11-22 09:11:48 -0800398 @Override
399 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700400 return mFactory;
401 }
402
403 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800404 public void onSetWebView(Tab tab, WebView view) {
405 mUi.onSetWebView(tab, view);
406 }
407
408 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800409 public void createSubWindow(Tab tab) {
410 endActionMode();
411 WebView mainView = tab.getWebView();
412 WebView subView = mFactory.createWebView((mainView == null)
413 ? false
414 : mainView.isPrivateBrowsingEnabled());
415 mUi.createSubWindow(tab, subView);
416 }
417
418 @Override
Michael Kolb14612442011-06-24 13:06:29 -0700419 public Context getContext() {
420 return mActivity;
421 }
422
423 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700424 public Activity getActivity() {
425 return mActivity;
426 }
427
428 void setUi(UI ui) {
429 mUi = ui;
430 }
431
432 BrowserSettings getSettings() {
433 return mSettings;
434 }
435
436 IntentHandler getIntentHandler() {
437 return mIntentHandler;
438 }
439
440 @Override
441 public UI getUi() {
442 return mUi;
443 }
444
445 int getMaxTabs() {
446 return mActivity.getResources().getInteger(R.integer.max_tabs);
447 }
448
449 @Override
450 public TabControl getTabControl() {
451 return mTabControl;
452 }
453
Michael Kolb1bf23132010-11-19 12:55:12 -0800454 @Override
455 public List<Tab> getTabs() {
456 return mTabControl.getTabs();
457 }
458
John Reckaf262e72011-07-25 13:55:44 -0700459 // Open the icon database.
460 private void openIconDatabase() {
461 // We have to call getInstance on the UI thread
462 final WebIconDatabase instance = WebIconDatabase.getInstance();
463 BackgroundHandler.execute(new Runnable() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000464
John Reckaf262e72011-07-25 13:55:44 -0700465 @Override
466 public void run() {
467 instance.open(mActivity.getDir("icons", 0).getPath());
Michael Kolb8233fac2010-10-26 16:08:53 -0700468 }
John Reckaf262e72011-07-25 13:55:44 -0700469 });
Michael Kolb8233fac2010-10-26 16:08:53 -0700470 }
471
472 private void startHandler() {
473 mHandler = new Handler() {
474
475 @Override
476 public void handleMessage(Message msg) {
477 switch (msg.what) {
478 case OPEN_BOOKMARKS:
Michael Kolb315d5022011-10-13 12:47:11 -0700479 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
Michael Kolb8233fac2010-10-26 16:08:53 -0700480 break;
481 case FOCUS_NODE_HREF:
482 {
483 String url = (String) msg.getData().get("url");
484 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500485 String src = (String) msg.getData().get("src");
486 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700487 if (TextUtils.isEmpty(url)) {
488 break;
489 }
490 HashMap focusNodeMap = (HashMap) msg.obj;
491 WebView view = (WebView) focusNodeMap.get("webview");
492 // Only apply the action if the top window did not change.
493 if (getCurrentTopWebView() != view) {
494 break;
495 }
496 switch (msg.arg1) {
497 case R.id.open_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700498 loadUrlFromContext(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700499 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500500 case R.id.view_image_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700501 loadUrlFromContext(src);
Cary Clark043c2d62010-12-15 11:19:39 -0500502 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500503 case R.id.open_newtab_context_menu_id:
504 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -0700505 openTab(url, parent,
506 !mSettings.openInBackground(), true);
Leon Scroggins026f2542010-11-22 13:26:12 -0500507 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700508 case R.id.copy_link_context_menu_id:
509 copy(url);
510 break;
511 case R.id.save_link_context_menu_id:
512 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500513 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000514 mActivity, url, null, null, null,
515 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700516 break;
517 }
518 break;
519 }
520
521 case LOAD_URL:
John Reck26b18322011-06-21 13:08:58 -0700522 loadUrlFromContext((String) msg.obj);
Michael Kolb8233fac2010-10-26 16:08:53 -0700523 break;
524
525 case STOP_LOAD:
526 stopLoading();
527 break;
528
529 case RELEASE_WAKELOCK:
John Reckf57c0292011-07-21 18:15:39 -0700530 if (mWakeLock != null && mWakeLock.isHeld()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700531 mWakeLock.release();
532 // if we reach here, Browser should be still in the
533 // background loading after WAKELOCK_TIMEOUT (5-min).
534 // To avoid burning the battery, stop loading.
535 mTabControl.stopAllLoading();
536 }
537 break;
538
539 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800540 Tab tab = (Tab) msg.obj;
541 if (tab != null) {
542 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700543 }
544 break;
545 }
546 }
547 };
548
549 }
550
John Reckef654f12011-07-12 16:42:08 -0700551 @Override
Martijn Coenenb2f93552011-06-14 10:48:35 +0200552 public Tab getCurrentTab() {
553 return mTabControl.getCurrentTab();
554 }
555
Michael Kolbba99c5d2010-11-29 14:57:41 -0800556 @Override
557 public void shareCurrentPage() {
558 shareCurrentPage(mTabControl.getCurrentTab());
559 }
560
561 private void shareCurrentPage(Tab tab) {
562 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800563 sharePage(mActivity, tab.getTitle(),
564 tab.getUrl(), tab.getFavicon(),
565 createScreenshot(tab.getWebView(),
566 getDesiredThumbnailWidth(mActivity),
567 getDesiredThumbnailHeight(mActivity)));
568 }
569 }
570
Michael Kolb8233fac2010-10-26 16:08:53 -0700571 /**
572 * Share a page, providing the title, url, favicon, and a screenshot. Uses
573 * an {@link Intent} to launch the Activity chooser.
574 * @param c Context used to launch a new Activity.
575 * @param title Title of the page. Stored in the Intent with
576 * {@link Intent#EXTRA_SUBJECT}
577 * @param url URL of the page. Stored in the Intent with
578 * {@link Intent#EXTRA_TEXT}
579 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
580 * with {@link Browser#EXTRA_SHARE_FAVICON}
581 * @param screenshot Bitmap of a screenshot of the page. Stored in the
582 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
583 */
584 static final void sharePage(Context c, String title, String url,
585 Bitmap favicon, Bitmap screenshot) {
586 Intent send = new Intent(Intent.ACTION_SEND);
587 send.setType("text/plain");
588 send.putExtra(Intent.EXTRA_TEXT, url);
589 send.putExtra(Intent.EXTRA_SUBJECT, title);
590 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
591 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
592 try {
593 c.startActivity(Intent.createChooser(send, c.getString(
594 R.string.choosertitle_sharevia)));
595 } catch(android.content.ActivityNotFoundException ex) {
596 // if no app handles it, do nothing
597 }
598 }
599
600 private void copy(CharSequence text) {
601 ClipboardManager cm = (ClipboardManager) mActivity
602 .getSystemService(Context.CLIPBOARD_SERVICE);
603 cm.setText(text);
604 }
605
606 // lifecycle
607
608 protected void onConfgurationChanged(Configuration config) {
609 mConfigChanged = true;
Michael Kolb18f252f2012-03-06 13:36:20 -0800610 // update the menu in case of a locale change
611 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -0700612 if (mPageDialogsHandler != null) {
613 mPageDialogsHandler.onConfigurationChanged(config);
614 }
615 mUi.onConfigurationChanged(config);
616 }
617
618 @Override
619 public void handleNewIntent(Intent intent) {
Michael Kolb59e232c2011-08-18 17:19:53 -0700620 if (!mUi.isWebShowing()) {
621 mUi.showWeb(false);
622 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700623 mIntentHandler.onNewIntent(intent);
624 }
625
626 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800627 if (mUi.isCustomViewShowing()) {
628 hideCustomView();
629 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700630 if (mActivityPaused) {
631 Log.e(LOGTAG, "BrowserActivity is already paused.");
632 return;
633 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700634 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800635 Tab tab = mTabControl.getCurrentTab();
636 if (tab != null) {
637 tab.pause();
638 if (!pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700639 if (mWakeLock == null) {
640 PowerManager pm = (PowerManager) mActivity
641 .getSystemService(Context.POWER_SERVICE);
642 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
643 }
Michael Kolb70976932010-11-30 11:34:01 -0800644 mWakeLock.acquire();
645 mHandler.sendMessageDelayed(mHandler
646 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
647 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700648 }
649 mUi.onPause();
650 mNetworkHandler.onPause();
651
652 WebView.disablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100653 NfcHandler.unregister(mActivity);
John Reckd7dd9b22011-08-30 09:18:29 -0700654 if (sThumbnailBitmap != null) {
655 sThumbnailBitmap.recycle();
656 sThumbnailBitmap = null;
657 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700658 }
659
John Reck1cf4b792011-07-26 10:22:22 -0700660 void onSaveInstanceState(Bundle outState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700661 // Save all the tabs
George Mount3636d0a2011-11-21 09:08:21 -0800662 Bundle saveState = createSaveState();
663
664 // crash recovery manages all save & restore state
665 mCrashRecoveryHandler.writeState(saveState);
666 mSettings.setLastRunPaused(true);
667 }
668
669 /**
670 * Save the current state to outState. Does not write the state to
671 * disk.
672 * @return Bundle containing the current state of all tabs.
673 */
674 /* package */ Bundle createSaveState() {
675 Bundle saveState = new Bundle();
676 mTabControl.saveState(saveState);
677 if (!saveState.isEmpty()) {
John Reck24f18262011-06-17 14:47:20 -0700678 // Save time so that we know how old incognito tabs (if any) are.
George Mount3636d0a2011-11-21 09:08:21 -0800679 saveState.putSerializable("lastActiveDate", Calendar.getInstance());
John Reck24f18262011-06-17 14:47:20 -0700680 }
George Mount3636d0a2011-11-21 09:08:21 -0800681 return saveState;
Michael Kolb8233fac2010-10-26 16:08:53 -0700682 }
683
684 void onResume() {
685 if (!mActivityPaused) {
686 Log.e(LOGTAG, "BrowserActivity is already resumed.");
687 return;
688 }
George Mount3636d0a2011-11-21 09:08:21 -0800689 mSettings.setLastRunPaused(false);
Michael Kolb8233fac2010-10-26 16:08:53 -0700690 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800691 Tab current = mTabControl.getCurrentTab();
692 if (current != null) {
693 current.resume();
694 resumeWebViewTimers(current);
695 }
John Reckf57c0292011-07-21 18:15:39 -0700696 releaseWakeLock();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200697
Michael Kolb8233fac2010-10-26 16:08:53 -0700698 mUi.onResume();
699 mNetworkHandler.onResume();
700 WebView.enablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100701 NfcHandler.register(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700702 }
703
John Reckf57c0292011-07-21 18:15:39 -0700704 private void releaseWakeLock() {
705 if (mWakeLock != null && mWakeLock.isHeld()) {
706 mHandler.removeMessages(RELEASE_WAKELOCK);
707 mWakeLock.release();
708 }
709 }
710
Michael Kolb70976932010-11-30 11:34:01 -0800711 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800712 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800713 * @param tab guaranteed non-null
714 */
715 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700716 boolean inLoad = tab.inPageLoad();
717 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
718 CookieSyncManager.getInstance().startSync();
719 WebView w = tab.getWebView();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100720 WebViewTimersControl.getInstance().onBrowserActivityResume(w);
Michael Kolb8233fac2010-10-26 16:08:53 -0700721 }
722 }
723
Michael Kolb70976932010-11-30 11:34:01 -0800724 /**
725 * Pause all WebView timers using the WebView of the given tab
726 * @param tab
727 * @return true if the timers are paused or tab is null
728 */
729 private boolean pauseWebViewTimers(Tab tab) {
730 if (tab == null) {
731 return true;
732 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700733 CookieSyncManager.getInstance().stopSync();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100734 WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView());
Michael Kolb8233fac2010-10-26 16:08:53 -0700735 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700736 }
Michael Kolb70976932010-11-30 11:34:01 -0800737 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700738 }
739
740 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800741 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700742 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
743 mUploadHandler = null;
744 }
745 if (mTabControl == null) return;
746 mUi.onDestroy();
747 // Remove the current tab and sub window
748 Tab t = mTabControl.getCurrentTab();
749 if (t != null) {
750 dismissSubWindow(t);
751 removeTab(t);
752 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500753 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700754 // Destroy all the tabs
755 mTabControl.destroy();
756 WebIconDatabase.getInstance().close();
757 // Stop watching the default geolocation permissions
758 mSystemAllowGeolocationOrigins.stop();
759 mSystemAllowGeolocationOrigins = null;
760 }
761
762 protected boolean isActivityPaused() {
763 return mActivityPaused;
764 }
765
766 protected void onLowMemory() {
767 mTabControl.freeMemory();
768 }
769
770 @Override
771 public boolean shouldShowErrorConsole() {
772 return mShouldShowErrorConsole;
773 }
774
775 protected void setShouldShowErrorConsole(boolean show) {
776 if (show == mShouldShowErrorConsole) {
777 // Nothing to do.
778 return;
779 }
780 mShouldShowErrorConsole = show;
781 Tab t = mTabControl.getCurrentTab();
782 if (t == null) {
783 // There is no current tab so we cannot toggle the error console
784 return;
785 }
786 mUi.setShouldShowErrorConsole(t, show);
787 }
788
789 @Override
790 public void stopLoading() {
791 mLoadStopped = true;
792 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700793 WebView w = getCurrentTopWebView();
Michael Kolb778a4882012-04-12 15:27:28 -0700794 if (w != null) {
795 w.stopLoading();
796 mUi.onPageStopped(tab);
797 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700798 }
799
800 boolean didUserStopLoading() {
801 return mLoadStopped;
802 }
803
804 // WebViewController
805
806 @Override
John Reck324d4402011-01-11 16:56:42 -0800807 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700808
809 // We've started to load a new page. If there was a pending message
810 // to save a screenshot then we will now take the new page and save
811 // an incorrect screenshot. Therefore, remove any pending thumbnail
812 // messages from the queue.
813 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800814 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700815
816 // reset sync timer to avoid sync starts during loading a page
817 CookieSyncManager.getInstance().resetSync();
818
819 if (!mNetworkHandler.isNetworkUp()) {
820 view.setNetworkAvailable(false);
821 }
822
823 // when BrowserActivity just starts, onPageStarted may be called before
824 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
825 // to start the timer. As we won't switch tabs while an activity is in
826 // pause state, we can ensure calling resume and pause in pair.
827 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800828 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700829 }
830 mLoadStopped = false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700831 endActionMode();
832
John Reck30c714c2010-12-16 17:30:34 -0800833 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700834
John Reck324d4402011-01-11 16:56:42 -0800835 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700836 // update the bookmark database for favicon
837 maybeUpdateFavicon(tab, null, url, favicon);
838
839 Performance.tracePageStart(url);
840
841 // Performance probe
842 if (false) {
843 Performance.onPageStarted();
844 }
845
846 }
847
848 @Override
John Reck324d4402011-01-11 16:56:42 -0800849 public void onPageFinished(Tab tab) {
Michael Kolb72864272012-05-03 15:42:15 -0700850 mCrashRecoveryHandler.backupState();
John Reck30c714c2010-12-16 17:30:34 -0800851 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700852 // pause the WebView timer and release the wake lock if it is finished
853 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800854 if (mActivityPaused && pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700855 releaseWakeLock();
Michael Kolb8233fac2010-10-26 16:08:53 -0700856 }
Martijn Coenenb2f93552011-06-14 10:48:35 +0200857
Michael Kolb8233fac2010-10-26 16:08:53 -0700858 // Performance probe
859 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800860 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700861 }
862
863 Performance.tracePageFinished();
864 }
865
866 @Override
John Reck30c714c2010-12-16 17:30:34 -0800867 public void onProgressChanged(Tab tab) {
868 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700869
870 if (newProgress == 100) {
871 CookieSyncManager.getInstance().sync();
872 // onProgressChanged() may continue to be called after the main
873 // frame has finished loading, as any remaining sub frames continue
874 // to load. We'll only get called once though with newProgress as
875 // 100 when everything is loaded. (onPageFinished is called once
876 // when the main frame completes loading regardless of the state of
877 // any sub frames so calls to onProgressChanges may continue after
878 // onPageFinished has executed)
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800879 if (tab.inPageLoad()) {
880 updateInLoadMenuItems(mCachedMenu, tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700881 }
John Reckd9862372012-02-21 15:04:50 -0800882 if (!tab.isPrivateBrowsingEnabled()
883 && !TextUtils.isEmpty(tab.getUrl())
884 && !tab.isSnapshot()) {
885 // Only update the bookmark screenshot if the user did not
886 // cancel the load early and there is not already
887 // a pending update for the tab.
Michael Kolb72864272012-05-03 15:42:15 -0700888 if (tab.shouldUpdateThumbnail() &&
889 (tab.inForeground() && !didUserStopLoading()
890 || !tab.inForeground())) {
John Reckd9862372012-02-21 15:04:50 -0800891 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
892 mHandler.sendMessageDelayed(mHandler.obtainMessage(
893 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
894 500);
895 }
896 }
897 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700898 } else {
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800899 if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700900 // onPageFinished may have already been called but a subframe is
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800901 // still loading
902 // updating the progress and
Michael Kolb8233fac2010-10-26 16:08:53 -0700903 // update the menu items.
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800904 updateInLoadMenuItems(mCachedMenu, tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700905 }
906 }
John Reck30c714c2010-12-16 17:30:34 -0800907 mUi.onProgressChanged(tab);
908 }
909
910 @Override
Steve Block2466eff2011-10-03 15:33:09 +0100911 public void onUpdatedSecurityState(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800912 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700913 }
914
915 @Override
916 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800917 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800918 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800919 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700920 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
921 return;
922 }
923 // Update the title in the history database if not in private browsing mode
924 if (!tab.isPrivateBrowsingEnabled()) {
John Reckf57c0292011-07-21 18:15:39 -0700925 DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700926 }
927 }
928
929 @Override
930 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800931 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700932 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
933 }
934
935 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800936 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
937 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700938 }
939
940 @Override
941 public boolean shouldOverrideKeyEvent(KeyEvent event) {
942 if (mMenuIsDown) {
943 // only check shortcut key when MENU is held
944 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
945 event);
946 } else {
947 return false;
948 }
949 }
950
951 @Override
John Reck997b1b72012-04-19 18:08:25 -0700952 public boolean onUnhandledKeyEvent(KeyEvent event) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700953 if (!isActivityPaused()) {
954 if (event.getAction() == KeyEvent.ACTION_DOWN) {
John Reck997b1b72012-04-19 18:08:25 -0700955 return mActivity.onKeyDown(event.getKeyCode(), event);
Michael Kolb8233fac2010-10-26 16:08:53 -0700956 } else {
John Reck997b1b72012-04-19 18:08:25 -0700957 return mActivity.onKeyUp(event.getKeyCode(), event);
Michael Kolb8233fac2010-10-26 16:08:53 -0700958 }
959 }
John Reck997b1b72012-04-19 18:08:25 -0700960 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700961 }
962
963 @Override
John Reck324d4402011-01-11 16:56:42 -0800964 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700965 // Don't save anything in private browsing mode
966 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800967 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700968
John Reck324d4402011-01-11 16:56:42 -0800969 if (TextUtils.isEmpty(url)
970 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700971 return;
972 }
John Reckf57c0292011-07-21 18:15:39 -0700973 DataController.getInstance(mActivity).updateVisitedHistory(url);
John Reck6c2e2f32011-08-22 13:41:23 -0700974 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -0700975 }
976
977 @Override
978 public void getVisitedHistory(final ValueCallback<String[]> callback) {
979 AsyncTask<Void, Void, String[]> task =
980 new AsyncTask<Void, Void, String[]>() {
981 @Override
982 public String[] doInBackground(Void... unused) {
983 return Browser.getVisitedHistory(mActivity.getContentResolver());
984 }
985 @Override
986 public void onPostExecute(String[] result) {
987 callback.onReceiveValue(result);
988 }
989 };
990 task.execute();
991 }
992
993 @Override
994 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
995 final HttpAuthHandler handler, final String host,
996 final String realm) {
997 String username = null;
998 String password = null;
999
1000 boolean reuseHttpAuthUsernamePassword
1001 = handler.useHttpAuthUsernamePassword();
1002
1003 if (reuseHttpAuthUsernamePassword && view != null) {
1004 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
1005 if (credentials != null && credentials.length == 2) {
1006 username = credentials[0];
1007 password = credentials[1];
1008 }
1009 }
1010
1011 if (username != null && password != null) {
1012 handler.proceed(username, password);
1013 } else {
Ben Murdochfdd37112011-08-05 15:48:14 +01001014 if (tab.inForeground() && !handler.suppressDialog()) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001015 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
1016 } else {
1017 handler.cancel();
1018 }
1019 }
1020 }
1021
1022 @Override
1023 public void onDownloadStart(Tab tab, String url, String userAgent,
1024 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001025 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -05001026 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001027 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
1028 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001029 // This Tab was opened for the sole purpose of downloading a
1030 // file. Remove it.
1031 if (tab == mTabControl.getCurrentTab()) {
1032 // In this case, the Tab is still on top.
1033 goBackOnePageOrQuit();
1034 } else {
1035 // In this case, it is not.
1036 closeTab(tab);
1037 }
1038 }
1039 }
1040
1041 @Override
1042 public Bitmap getDefaultVideoPoster() {
1043 return mUi.getDefaultVideoPoster();
1044 }
1045
1046 @Override
1047 public View getVideoLoadingProgressView() {
1048 return mUi.getVideoLoadingProgressView();
1049 }
1050
1051 @Override
1052 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1053 SslError error) {
1054 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1055 }
1056
Patrick Scott92066772011-03-10 08:46:27 -05001057 @Override
1058 public void showAutoLogin(Tab tab) {
1059 assert tab.inForeground();
1060 // Update the title bar to show the auto-login request.
1061 mUi.showAutoLogin(tab);
1062 }
1063
1064 @Override
1065 public void hideAutoLogin(Tab tab) {
1066 assert tab.inForeground();
1067 mUi.hideAutoLogin(tab);
1068 }
1069
Michael Kolb8233fac2010-10-26 16:08:53 -07001070 // helper method
1071
1072 /*
1073 * Update the favorites icon if the private browsing isn't enabled and the
1074 * icon is valid.
1075 */
1076 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1077 final String url, Bitmap favicon) {
1078 if (favicon == null) {
1079 return;
1080 }
1081 if (!tab.isPrivateBrowsingEnabled()) {
1082 Bookmarks.updateFavicon(mActivity
1083 .getContentResolver(), originalUrl, url, favicon);
1084 }
1085 }
1086
Leon Scroggins4cd97792010-12-03 15:31:56 -05001087 @Override
1088 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001089 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001090 mUi.bookmarkedStatusHasChanged(tab);
1091 }
1092
Michael Kolb8233fac2010-10-26 16:08:53 -07001093 // end WebViewController
1094
1095 protected void pageUp() {
1096 getCurrentTopWebView().pageUp(false);
1097 }
1098
1099 protected void pageDown() {
1100 getCurrentTopWebView().pageDown(false);
1101 }
1102
1103 // callback from phone title bar
1104 public void editUrl() {
1105 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolb1f9b3562012-04-24 14:38:34 -07001106 mUi.editUrl(false, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001107 }
1108
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001109 public void showCustomView(Tab tab, View view, int requestedOrientation,
Michael Kolb8233fac2010-10-26 16:08:53 -07001110 WebChromeClient.CustomViewCallback callback) {
1111 if (tab.inForeground()) {
1112 if (mUi.isCustomViewShowing()) {
1113 callback.onCustomViewHidden();
1114 return;
1115 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001116 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001117 // Save the menu state and set it to empty while the custom
1118 // view is showing.
1119 mOldMenuState = mMenuState;
1120 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001121 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001122 }
1123 }
1124
1125 @Override
1126 public void hideCustomView() {
1127 if (mUi.isCustomViewShowing()) {
1128 mUi.onHideCustomView();
1129 // Reset the old menu state.
1130 mMenuState = mOldMenuState;
1131 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001132 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001133 }
1134 }
1135
1136 protected void onActivityResult(int requestCode, int resultCode,
1137 Intent intent) {
1138 if (getCurrentTopWebView() == null) return;
1139 switch (requestCode) {
1140 case PREFERENCES_PAGE:
1141 if (resultCode == Activity.RESULT_OK && intent != null) {
1142 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001143 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001144 mTabControl.removeParentChildRelationShips();
1145 }
1146 }
1147 break;
1148 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001149 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001150 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001151 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001152 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001153 case AUTOFILL_SETUP:
1154 // Determine whether a profile was actually set up or not
1155 // and if so, send the message back to the WebTextView to
1156 // fill the form with the new profile.
1157 if (getSettings().getAutoFillProfile() != null) {
1158 mAutoFillSetupMessage.sendToTarget();
1159 mAutoFillSetupMessage = null;
1160 }
1161 break;
John Reckd3e4d5b2011-07-13 15:48:43 -07001162 case COMBO_VIEW:
1163 if (intent == null || resultCode != Activity.RESULT_OK) {
1164 break;
1165 }
John Reck3ba45532011-08-11 16:26:53 -07001166 mUi.showWeb(false);
John Reckd3e4d5b2011-07-13 15:48:43 -07001167 if (Intent.ACTION_VIEW.equals(intent.getAction())) {
1168 Tab t = getCurrentTab();
1169 Uri uri = intent.getData();
1170 loadUrl(t, uri.toString());
1171 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
1172 String[] urls = intent.getStringArrayExtra(
1173 ComboViewActivity.EXTRA_OPEN_ALL);
1174 Tab parent = getCurrentTab();
1175 for (String url : urls) {
1176 parent = openTab(url, parent,
1177 !mSettings.openInBackground(), true);
1178 }
1179 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
1180 long id = intent.getLongExtra(
1181 ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
1182 if (id >= 0) {
1183 createNewSnapshotTab(id, true);
1184 }
1185 }
1186 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001187 default:
1188 break;
1189 }
1190 getCurrentTopWebView().requestFocus();
1191 }
1192
1193 /**
1194 * Open the Go page.
1195 * @param startWithHistory If true, open starting on the history tab.
1196 * Otherwise, start with the bookmarks tab.
1197 */
1198 @Override
Michael Kolb315d5022011-10-13 12:47:11 -07001199 public void bookmarksOrHistoryPicker(ComboViews startView) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001200 if (mTabControl.getCurrentWebView() == null) {
1201 return;
1202 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001203 // clear action mode
1204 if (isInCustomActionMode()) {
1205 endActionMode();
1206 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001207 Bundle extras = new Bundle();
1208 // Disable opening in a new window if we have maxed out the windows
1209 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1210 !mTabControl.canCreateNewTab());
Michael Kolb315d5022011-10-13 12:47:11 -07001211 mUi.showComboView(startView, extras);
Michael Kolb8233fac2010-10-26 16:08:53 -07001212 }
1213
1214 // combo view callbacks
1215
Michael Kolb8233fac2010-10-26 16:08:53 -07001216 // key handling
1217 protected void onBackKey() {
1218 if (!mUi.onBackKey()) {
1219 WebView subwindow = mTabControl.getCurrentSubWindow();
1220 if (subwindow != null) {
1221 if (subwindow.canGoBack()) {
1222 subwindow.goBack();
1223 } else {
1224 dismissSubWindow(mTabControl.getCurrentTab());
1225 }
1226 } else {
1227 goBackOnePageOrQuit();
1228 }
1229 }
1230 }
1231
Michael Kolb4bd767d2011-05-27 11:33:55 -07001232 protected boolean onMenuKey() {
1233 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001234 }
1235
Michael Kolb8233fac2010-10-26 16:08:53 -07001236 // menu handling and state
1237 // TODO: maybe put into separate handler
1238
1239 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckd73c5a22010-12-22 10:22:50 -08001240 if (mMenuState == EMPTY_MENU) {
1241 return false;
1242 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001243 MenuInflater inflater = mActivity.getMenuInflater();
1244 inflater.inflate(R.menu.browser, menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001245 return true;
1246 }
1247
1248 protected void onCreateContextMenu(ContextMenu menu, View v,
1249 ContextMenuInfo menuInfo) {
John Reck0f602f32011-07-07 15:38:43 -07001250 if (v instanceof TitleBar) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001251 return;
1252 }
1253 if (!(v instanceof WebView)) {
1254 return;
1255 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001256 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001257 WebView.HitTestResult result = webview.getHitTestResult();
1258 if (result == null) {
1259 return;
1260 }
1261
1262 int type = result.getType();
1263 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1264 Log.w(LOGTAG,
1265 "We should not show context menu when nothing is touched");
1266 return;
1267 }
1268 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1269 // let TextView handles context menu
1270 return;
1271 }
1272
1273 // Note, http://b/issue?id=1106666 is requesting that
1274 // an inflated menu can be used again. This is not available
1275 // yet, so inflate each time (yuk!)
1276 MenuInflater inflater = mActivity.getMenuInflater();
1277 inflater.inflate(R.menu.browsercontext, menu);
1278
1279 // Show the correct menu group
1280 final String extra = result.getExtra();
Michael Kolbc159c1a2011-12-15 16:06:38 -08001281 if (extra == null) return;
Michael Kolb8233fac2010-10-26 16:08:53 -07001282 menu.setGroupVisible(R.id.PHONE_MENU,
1283 type == WebView.HitTestResult.PHONE_TYPE);
1284 menu.setGroupVisible(R.id.EMAIL_MENU,
1285 type == WebView.HitTestResult.EMAIL_TYPE);
1286 menu.setGroupVisible(R.id.GEO_MENU,
1287 type == WebView.HitTestResult.GEO_TYPE);
1288 menu.setGroupVisible(R.id.IMAGE_MENU,
1289 type == WebView.HitTestResult.IMAGE_TYPE
1290 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1291 menu.setGroupVisible(R.id.ANCHOR_MENU,
1292 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1293 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001294 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1295 || type == WebView.HitTestResult.PHONE_TYPE
1296 || type == WebView.HitTestResult.EMAIL_TYPE
1297 || type == WebView.HitTestResult.GEO_TYPE;
1298 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1299 if (hitText) {
1300 menu.findItem(R.id.select_text_menu_id)
1301 .setOnMenuItemClickListener(new SelectText(webview));
1302 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001303 // Setup custom handling depending on the type
1304 switch (type) {
1305 case WebView.HitTestResult.PHONE_TYPE:
1306 menu.setHeaderTitle(Uri.decode(extra));
1307 menu.findItem(R.id.dial_context_menu_id).setIntent(
1308 new Intent(Intent.ACTION_VIEW, Uri
1309 .parse(WebView.SCHEME_TEL + extra)));
1310 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1311 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1312 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1313 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1314 addIntent);
1315 menu.findItem(R.id.copy_phone_context_menu_id)
1316 .setOnMenuItemClickListener(
1317 new Copy(extra));
1318 break;
1319
1320 case WebView.HitTestResult.EMAIL_TYPE:
1321 menu.setHeaderTitle(extra);
1322 menu.findItem(R.id.email_context_menu_id).setIntent(
1323 new Intent(Intent.ACTION_VIEW, Uri
1324 .parse(WebView.SCHEME_MAILTO + extra)));
1325 menu.findItem(R.id.copy_mail_context_menu_id)
1326 .setOnMenuItemClickListener(
1327 new Copy(extra));
1328 break;
1329
1330 case WebView.HitTestResult.GEO_TYPE:
1331 menu.setHeaderTitle(extra);
1332 menu.findItem(R.id.map_context_menu_id).setIntent(
1333 new Intent(Intent.ACTION_VIEW, Uri
1334 .parse(WebView.SCHEME_GEO
1335 + URLEncoder.encode(extra))));
1336 menu.findItem(R.id.copy_geo_context_menu_id)
1337 .setOnMenuItemClickListener(
1338 new Copy(extra));
1339 break;
1340
1341 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1342 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001343 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001344 // decide whether to show the open link in new tab option
1345 boolean showNewTab = mTabControl.canCreateNewTab();
1346 MenuItem newTabItem
1347 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001348 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001349 ? R.string.contextmenu_openlink_newwindow_background
1350 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001351 newTabItem.setVisible(showNewTab);
1352 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001353 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1354 newTabItem.setOnMenuItemClickListener(
1355 new MenuItem.OnMenuItemClickListener() {
1356 @Override
1357 public boolean onMenuItemClick(MenuItem item) {
1358 final HashMap<String, WebView> hrefMap =
1359 new HashMap<String, WebView>();
1360 hrefMap.put("webview", webview);
1361 final Message msg = mHandler.obtainMessage(
1362 FOCUS_NODE_HREF,
1363 R.id.open_newtab_context_menu_id,
1364 0, hrefMap);
1365 webview.requestFocusNodeHref(msg);
1366 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001367 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001368 });
1369 } else {
1370 newTabItem.setOnMenuItemClickListener(
1371 new MenuItem.OnMenuItemClickListener() {
1372 @Override
1373 public boolean onMenuItemClick(MenuItem item) {
1374 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001375 openTab(extra, parent,
1376 !mSettings.openInBackground(),
1377 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001378 return true;
1379 }
1380 });
1381 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001382 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001383 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1384 break;
1385 }
1386 // otherwise fall through to handle image part
1387 case WebView.HitTestResult.IMAGE_TYPE:
Victoria Lease5987b802012-03-12 13:05:23 -07001388 MenuItem shareItem = menu.findItem(R.id.share_link_context_menu_id);
1389 shareItem.setVisible(type == WebView.HitTestResult.IMAGE_TYPE);
Michael Kolb8233fac2010-10-26 16:08:53 -07001390 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1391 menu.setHeaderTitle(extra);
Victoria Lease5987b802012-03-12 13:05:23 -07001392 shareItem.setOnMenuItemClickListener(
1393 new MenuItem.OnMenuItemClickListener() {
1394 @Override
1395 public boolean onMenuItemClick(MenuItem item) {
1396 sharePage(mActivity, null, extra, null,
1397 null);
1398 return true;
1399 }
1400 }
1401 );
Michael Kolb8233fac2010-10-26 16:08:53 -07001402 }
Michael Kolb3639c4c2011-09-28 15:36:40 -07001403 menu.findItem(R.id.view_image_context_menu_id)
1404 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1405 @Override
1406 public boolean onMenuItemClick(MenuItem item) {
1407 openTab(extra, mTabControl.getCurrentTab(), true, true);
1408 return false;
1409 }
1410 });
Michael Kolb8233fac2010-10-26 16:08:53 -07001411 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001412 setOnMenuItemClickListener(
1413 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001414 menu.findItem(R.id.set_wallpaper_context_menu_id).
1415 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1416 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001417 break;
1418
1419 default:
1420 Log.w(LOGTAG, "We should not get here.");
1421 break;
1422 }
1423 //update the ui
1424 mUi.onContextMenuCreated(menu);
1425 }
1426
1427 /**
1428 * As the menu can be open when loading state changes
1429 * we must manually update the state of the stop/reload menu
1430 * item
1431 */
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001432 private void updateInLoadMenuItems(Menu menu, Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001433 if (menu == null) {
1434 return;
1435 }
1436 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolbb8337132011-11-28 15:07:39 -08001437 MenuItem src = ((tab != null) && tab.inPageLoad()) ?
Michael Kolb8233fac2010-10-26 16:08:53 -07001438 menu.findItem(R.id.stop_menu_id):
1439 menu.findItem(R.id.reload_menu_id);
1440 if (src != null) {
1441 dest.setIcon(src.getIcon());
1442 dest.setTitle(src.getTitle());
1443 }
1444 }
1445
John Reckb3417f02011-01-14 11:01:05 -08001446 boolean onPrepareOptionsMenu(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001447 updateInLoadMenuItems(menu, getCurrentTab());
John Recke1a03a32011-09-14 17:04:16 -07001448 // hold on to the menu reference here; it is used by the page callbacks
1449 // to update the menu based on loading state
1450 mCachedMenu = menu;
Michael Kolb8233fac2010-10-26 16:08:53 -07001451 // Note: setVisible will decide whether an item is visible; while
1452 // setEnabled() will decide whether an item is enabled, which also means
1453 // whether the matching shortcut key will function.
1454 switch (mMenuState) {
1455 case EMPTY_MENU:
1456 if (mCurrentMenuState != mMenuState) {
1457 menu.setGroupVisible(R.id.MAIN_MENU, false);
1458 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1459 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1460 }
1461 break;
1462 default:
1463 if (mCurrentMenuState != mMenuState) {
1464 menu.setGroupVisible(R.id.MAIN_MENU, true);
1465 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1466 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1467 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001468 updateMenuState(getCurrentTab(), menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001469 break;
1470 }
1471 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001472 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001473 }
1474
Michael Kolb4bf79712011-07-14 14:18:12 -07001475 @Override
1476 public void updateMenuState(Tab tab, Menu menu) {
1477 boolean canGoBack = false;
1478 boolean canGoForward = false;
1479 boolean isHome = false;
John Reck42229bc2011-08-19 13:26:43 -07001480 boolean isDesktopUa = false;
John Recke1a03a32011-09-14 17:04:16 -07001481 boolean isLive = false;
Michael Kolb4bf79712011-07-14 14:18:12 -07001482 if (tab != null) {
1483 canGoBack = tab.canGoBack();
1484 canGoForward = tab.canGoForward();
1485 isHome = mSettings.getHomePage().equals(tab.getUrl());
John Reck42229bc2011-08-19 13:26:43 -07001486 isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
John Recke1a03a32011-09-14 17:04:16 -07001487 isLive = !tab.isSnapshot();
Michael Kolb4bf79712011-07-14 14:18:12 -07001488 }
1489 final MenuItem back = menu.findItem(R.id.back_menu_id);
1490 back.setEnabled(canGoBack);
1491
1492 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1493 home.setEnabled(!isHome);
1494
1495 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1496 forward.setEnabled(canGoForward);
1497
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001498 final MenuItem source = menu.findItem(isInLoad() ? R.id.stop_menu_id
1499 : R.id.reload_menu_id);
Michael Kolb4bf79712011-07-14 14:18:12 -07001500 final MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolb7ab75ee2011-07-14 16:36:38 -07001501 if (source != null && dest != null) {
1502 dest.setTitle(source.getTitle());
1503 dest.setIcon(source.getIcon());
1504 }
John Recke1a03a32011-09-14 17:04:16 -07001505 menu.setGroupVisible(R.id.NAV_MENU, isLive);
Michael Kolb4bf79712011-07-14 14:18:12 -07001506
1507 // decide whether to show the share link option
1508 PackageManager pm = mActivity.getPackageManager();
1509 Intent send = new Intent(Intent.ACTION_SEND);
1510 send.setType("text/plain");
1511 ResolveInfo ri = pm.resolveActivity(send,
1512 PackageManager.MATCH_DEFAULT_ONLY);
1513 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1514
1515 boolean isNavDump = mSettings.enableNavDump();
1516 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1517 nav.setVisible(isNavDump);
1518 nav.setEnabled(isNavDump);
1519
1520 boolean showDebugSettings = mSettings.isDebugEnabled();
John Reck42229bc2011-08-19 13:26:43 -07001521 final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
1522 uaSwitcher.setChecked(isDesktopUa);
John Recke1a03a32011-09-14 17:04:16 -07001523 menu.setGroupVisible(R.id.LIVE_MENU, isLive);
1524 menu.setGroupVisible(R.id.SNAPSHOT_MENU, !isLive);
Michael Kolb315d5022011-10-13 12:47:11 -07001525 menu.setGroupVisible(R.id.COMBO_MENU, false);
Michael Kolb4bf79712011-07-14 14:18:12 -07001526
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001527 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001528 }
1529
Michael Kolb8233fac2010-10-26 16:08:53 -07001530 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001531 if (null == getCurrentTopWebView()) {
1532 return false;
1533 }
1534 if (mMenuIsDown) {
1535 // The shortcut action consumes the MENU. Even if it is still down,
1536 // it won't trigger the next shortcut action. In the case of the
1537 // shortcut action triggering a new activity, like Bookmarks, we
1538 // won't get onKeyUp for MENU. So it is important to reset it here.
1539 mMenuIsDown = false;
1540 }
Michael Kolb3ca12752011-07-20 13:52:25 -07001541 if (mUi.onOptionsItemSelected(item)) {
1542 // ui callback handled it
1543 return true;
1544 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001545 switch (item.getItemId()) {
1546 // -- Main menu
1547 case R.id.new_tab_menu_id:
1548 openTabToHomePage();
1549 break;
1550
1551 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001552 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001553 break;
1554
1555 case R.id.goto_menu_id:
1556 editUrl();
1557 break;
1558
1559 case R.id.bookmarks_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001560 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
1561 break;
1562
1563 case R.id.history_menu_id:
1564 bookmarksOrHistoryPicker(ComboViews.History);
1565 break;
1566
1567 case R.id.snapshots_menu_id:
1568 bookmarksOrHistoryPicker(ComboViews.Snapshots);
Michael Kolb8233fac2010-10-26 16:08:53 -07001569 break;
1570
Michael Kolb8233fac2010-10-26 16:08:53 -07001571 case R.id.add_bookmark_menu_id:
Michael Kolb80f75082012-04-10 10:50:06 -07001572 bookmarkCurrentPage();
Michael Kolb8233fac2010-10-26 16:08:53 -07001573 break;
1574
1575 case R.id.stop_reload_menu_id:
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001576 if (isInLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001577 stopLoading();
1578 } else {
1579 getCurrentTopWebView().reload();
1580 }
1581 break;
1582
1583 case R.id.back_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001584 getCurrentTab().goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07001585 break;
1586
1587 case R.id.forward_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001588 getCurrentTab().goForward();
Michael Kolb8233fac2010-10-26 16:08:53 -07001589 break;
1590
1591 case R.id.close_menu_id:
1592 // Close the subwindow if it exists.
1593 if (mTabControl.getCurrentSubWindow() != null) {
1594 dismissSubWindow(mTabControl.getCurrentTab());
1595 break;
1596 }
1597 closeCurrentTab();
1598 break;
1599
1600 case R.id.homepage_menu_id:
1601 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07001602 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07001603 break;
1604
1605 case R.id.preferences_menu_id:
Michael Kolb80f75082012-04-10 10:50:06 -07001606 openPreferences();
Michael Kolb8233fac2010-10-26 16:08:53 -07001607 break;
1608
1609 case R.id.find_menu_id:
Michael Kolbe11b9212012-04-13 13:39:54 -07001610 findOnPage();
Michael Kolb8233fac2010-10-26 16:08:53 -07001611 break;
1612
John Reck2bc80422011-06-30 15:11:49 -07001613 case R.id.save_snapshot_menu_id:
1614 final Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07001615 if (source == null) break;
John Reck68234a92012-04-19 15:27:12 -07001616 new SaveSnapshotTask(source).execute();
Leon Scrogginsac993842011-02-02 12:54:07 -05001617 break;
1618
Michael Kolb8233fac2010-10-26 16:08:53 -07001619 case R.id.page_info_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001620 showPageInfo();
Michael Kolb8233fac2010-10-26 16:08:53 -07001621 break;
1622
John Recke1a03a32011-09-14 17:04:16 -07001623 case R.id.snapshot_go_live:
1624 goLive();
1625 return true;
1626
Michael Kolb8233fac2010-10-26 16:08:53 -07001627 case R.id.share_page_menu_id:
1628 Tab currentTab = mTabControl.getCurrentTab();
1629 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001630 return false;
1631 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001632 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001633 break;
1634
1635 case R.id.dump_nav_menu_id:
1636 getCurrentTopWebView().debugDump();
1637 break;
1638
Michael Kolb8233fac2010-10-26 16:08:53 -07001639 case R.id.zoom_in_menu_id:
1640 getCurrentTopWebView().zoomIn();
1641 break;
1642
1643 case R.id.zoom_out_menu_id:
1644 getCurrentTopWebView().zoomOut();
1645 break;
1646
1647 case R.id.view_downloads_menu_id:
1648 viewDownloads();
1649 break;
1650
John Reck42229bc2011-08-19 13:26:43 -07001651 case R.id.ua_desktop_menu_id:
Michael Kolb80f75082012-04-10 10:50:06 -07001652 toggleUserAgent();
John Reck42229bc2011-08-19 13:26:43 -07001653 break;
1654
Michael Kolb8233fac2010-10-26 16:08:53 -07001655 case R.id.window_one_menu_id:
1656 case R.id.window_two_menu_id:
1657 case R.id.window_three_menu_id:
1658 case R.id.window_four_menu_id:
1659 case R.id.window_five_menu_id:
1660 case R.id.window_six_menu_id:
1661 case R.id.window_seven_menu_id:
1662 case R.id.window_eight_menu_id:
1663 {
1664 int menuid = item.getItemId();
1665 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1666 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1667 Tab desiredTab = mTabControl.getTab(id);
1668 if (desiredTab != null &&
1669 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001670 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001671 }
1672 break;
1673 }
1674 }
1675 }
1676 break;
1677
1678 default:
1679 return false;
1680 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001681 return true;
1682 }
1683
John Reck68234a92012-04-19 15:27:12 -07001684 private class SaveSnapshotTask extends AsyncTask<Void, Void, Long>
1685 implements OnCancelListener {
1686
1687 private Tab mTab;
1688 private Dialog mProgressDialog;
1689 private ContentValues mValues;
1690
1691 private SaveSnapshotTask(Tab tab) {
1692 mTab = tab;
1693 }
1694
1695 @Override
1696 protected void onPreExecute() {
1697 CharSequence message = mActivity.getText(R.string.saving_snapshot);
1698 mProgressDialog = ProgressDialog.show(mActivity, null, message,
1699 true, true, this);
1700 mValues = mTab.createSnapshotValues();
1701 }
1702
1703 @Override
1704 protected Long doInBackground(Void... params) {
1705 if (!mTab.saveViewState(mValues)) {
1706 return null;
1707 }
1708 if (isCancelled()) {
1709 String path = mValues.getAsString(Snapshots.VIEWSTATE_PATH);
1710 File file = mActivity.getFileStreamPath(path);
1711 if (!file.delete()) {
1712 file.deleteOnExit();
1713 }
1714 return null;
1715 }
1716 final ContentResolver cr = mActivity.getContentResolver();
1717 Uri result = cr.insert(Snapshots.CONTENT_URI, mValues);
1718 if (result == null) {
1719 return null;
1720 }
1721 long id = ContentUris.parseId(result);
1722 return id;
1723 }
1724
1725 @Override
1726 protected void onPostExecute(Long id) {
1727 if (isCancelled()) {
1728 return;
1729 }
1730 mProgressDialog.dismiss();
1731 if (id == null) {
1732 Toast.makeText(mActivity, R.string.snapshot_failed,
1733 Toast.LENGTH_SHORT).show();
1734 return;
1735 }
1736 Bundle b = new Bundle();
1737 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
1738 mUi.showComboView(ComboViews.Snapshots, b);
1739 }
1740
1741 @Override
1742 public void onCancel(DialogInterface dialog) {
1743 cancel(true);
1744 }
1745 }
1746
Michael Kolb80f75082012-04-10 10:50:06 -07001747 @Override
1748 public void toggleUserAgent() {
1749 WebView web = getCurrentWebView();
1750 mSettings.toggleDesktopUseragent(web);
1751 web.loadUrl(web.getOriginalUrl());
1752 }
1753
1754 @Override
1755 public void findOnPage() {
1756 getCurrentTopWebView().showFindDialog(null, true);
1757 }
1758
1759 @Override
1760 public void openPreferences() {
1761 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1762 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1763 getCurrentTopWebView().getUrl());
1764 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1765 }
1766
1767 @Override
1768 public void bookmarkCurrentPage() {
1769 Intent bookmarkIntent = createBookmarkCurrentPageIntent(false);
1770 if (bookmarkIntent != null) {
1771 mActivity.startActivity(bookmarkIntent);
1772 }
1773 }
1774
John Recke1a03a32011-09-14 17:04:16 -07001775 private void goLive() {
1776 Tab t = getCurrentTab();
1777 t.loadUrl(t.getUrl(), null);
1778 }
1779
Michael Kolb315d5022011-10-13 12:47:11 -07001780 @Override
1781 public void showPageInfo() {
1782 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
1783 }
1784
Michael Kolb8233fac2010-10-26 16:08:53 -07001785 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001786 // Let the History and Bookmark fragments handle menus they created.
1787 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1788 return false;
1789 }
1790
Michael Kolb8233fac2010-10-26 16:08:53 -07001791 int id = item.getItemId();
1792 boolean result = true;
1793 switch (id) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001794 // -- Browser context menu
1795 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001796 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001797 case R.id.copy_link_context_menu_id:
1798 final WebView webView = getCurrentTopWebView();
1799 if (null == webView) {
1800 result = false;
1801 break;
1802 }
1803 final HashMap<String, WebView> hrefMap =
1804 new HashMap<String, WebView>();
1805 hrefMap.put("webview", webView);
1806 final Message msg = mHandler.obtainMessage(
1807 FOCUS_NODE_HREF, id, 0, hrefMap);
1808 webView.requestFocusNodeHref(msg);
1809 break;
1810
1811 default:
1812 // For other context menus
1813 result = onOptionsItemSelected(item);
1814 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001815 return result;
1816 }
1817
1818 /**
1819 * support programmatically opening the context menu
1820 */
1821 public void openContextMenu(View view) {
1822 mActivity.openContextMenu(view);
1823 }
1824
1825 /**
1826 * programmatically open the options menu
1827 */
1828 public void openOptionsMenu() {
1829 mActivity.openOptionsMenu();
1830 }
1831
1832 public boolean onMenuOpened(int featureId, Menu menu) {
1833 if (mOptionsMenuOpen) {
1834 if (mConfigChanged) {
1835 // We do not need to make any changes to the state of the
1836 // title bar, since the only thing that happened was a
1837 // change in orientation
1838 mConfigChanged = false;
1839 } else {
1840 if (!mExtendedMenuOpen) {
1841 mExtendedMenuOpen = true;
1842 mUi.onExtendedMenuOpened();
1843 } else {
1844 // Switching the menu back to icon view, so show the
1845 // title bar once again.
1846 mExtendedMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001847 mUi.onExtendedMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001848 }
1849 }
1850 } else {
1851 // The options menu is closed, so open it, and show the title
1852 mOptionsMenuOpen = true;
1853 mConfigChanged = false;
1854 mExtendedMenuOpen = false;
1855 mUi.onOptionsMenuOpened();
1856 }
1857 return true;
1858 }
1859
1860 public void onOptionsMenuClosed(Menu menu) {
1861 mOptionsMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001862 mUi.onOptionsMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001863 }
1864
1865 public void onContextMenuClosed(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001866 mUi.onContextMenuClosed(menu, isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001867 }
1868
1869 // Helper method for getting the top window.
1870 @Override
1871 public WebView getCurrentTopWebView() {
1872 return mTabControl.getCurrentTopWebView();
1873 }
1874
1875 @Override
1876 public WebView getCurrentWebView() {
1877 return mTabControl.getCurrentWebView();
1878 }
1879
1880 /*
1881 * This method is called as a result of the user selecting the options
1882 * menu to see the download window. It shows the download window on top of
1883 * the current window.
1884 */
1885 void viewDownloads() {
1886 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1887 mActivity.startActivity(intent);
1888 }
1889
John Reck30b065e2011-07-19 10:58:05 -07001890 int getActionModeHeight() {
1891 TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
1892 new int[] { android.R.attr.actionBarSize });
1893 int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
1894 actionBarSizeTypedArray.recycle();
1895 return size;
1896 }
1897
Michael Kolb8233fac2010-10-26 16:08:53 -07001898 // action mode
1899
1900 void onActionModeStarted(ActionMode mode) {
1901 mUi.onActionModeStarted(mode);
1902 mActionMode = mode;
1903 }
1904
1905 /*
1906 * True if a custom ActionMode (i.e. find or select) is in use.
1907 */
1908 @Override
1909 public boolean isInCustomActionMode() {
1910 return mActionMode != null;
1911 }
1912
1913 /*
1914 * End the current ActionMode.
1915 */
1916 @Override
1917 public void endActionMode() {
1918 if (mActionMode != null) {
1919 mActionMode.finish();
1920 }
1921 }
1922
1923 /*
1924 * Called by find and select when they are finished. Replace title bars
1925 * as necessary.
1926 */
1927 public void onActionModeFinished(ActionMode mode) {
1928 if (!isInCustomActionMode()) return;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001929 mUi.onActionModeFinished(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001930 mActionMode = null;
1931 }
1932
1933 boolean isInLoad() {
Michael Kolbc5b0b2d2011-11-29 16:13:35 -08001934 final Tab tab = getCurrentTab();
1935 return (tab != null) && tab.inPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07001936 }
1937
1938 // bookmark handling
1939
1940 /**
1941 * add the current page as a bookmark to the given folder id
1942 * @param folderId use -1 for the default folder
John Reckd3e4d5b2011-07-13 15:48:43 -07001943 * @param editExisting If true, check to see whether the site is already
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001944 * bookmarked, and if it is, edit that bookmark. If false, and
1945 * the site is already bookmarked, do not attempt to edit the
1946 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001947 */
1948 @Override
John Reckd3e4d5b2011-07-13 15:48:43 -07001949 public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
John Recka60fffa2011-09-06 16:30:29 -07001950 WebView w = getCurrentTopWebView();
1951 if (w == null) {
1952 return null;
1953 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001954 Intent i = new Intent(mActivity,
1955 AddBookmarkPage.class);
Michael Kolb8233fac2010-10-26 16:08:53 -07001956 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1957 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1958 String touchIconUrl = w.getTouchIconUrl();
1959 if (touchIconUrl != null) {
1960 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1961 WebSettings settings = w.getSettings();
1962 if (settings != null) {
1963 i.putExtra(AddBookmarkPage.USER_AGENT,
1964 settings.getUserAgentString());
1965 }
1966 }
1967 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1968 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1969 getDesiredThumbnailHeight(mActivity)));
1970 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07001971 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001972 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1973 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001974 // Put the dialog at the upper right of the screen, covering the
1975 // star on the title bar.
1976 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07001977 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07001978 }
1979
1980 // file chooser
Ben Murdoch8cad4132012-01-11 10:56:43 +00001981 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001982 mUploadHandler = new UploadHandler(this);
Ben Murdoch8cad4132012-01-11 10:56:43 +00001983 mUploadHandler.openFileChooser(uploadMsg, acceptType, capture);
Michael Kolb8233fac2010-10-26 16:08:53 -07001984 }
1985
1986 // thumbnails
1987
1988 /**
1989 * Return the desired width for thumbnail screenshots, which are stored in
1990 * the database, and used on the bookmarks screen.
1991 * @param context Context for finding out the density of the screen.
1992 * @return desired width for thumbnail screenshot.
1993 */
1994 static int getDesiredThumbnailWidth(Context context) {
1995 return context.getResources().getDimensionPixelOffset(
1996 R.dimen.bookmarkThumbnailWidth);
1997 }
1998
1999 /**
2000 * Return the desired height for thumbnail screenshots, which are stored in
2001 * the database, and used on the bookmarks screen.
2002 * @param context Context for finding out the density of the screen.
2003 * @return desired height for thumbnail screenshot.
2004 */
2005 static int getDesiredThumbnailHeight(Context context) {
2006 return context.getResources().getDimensionPixelOffset(
2007 R.dimen.bookmarkThumbnailHeight);
2008 }
2009
John Reck8cc92352011-07-06 17:41:52 -07002010 static Bitmap createScreenshot(WebView view, int width, int height) {
John Reckd7dd9b22011-08-30 09:18:29 -07002011 if (view == null || view.getContentHeight() == 0
2012 || view.getContentWidth() == 0) {
2013 return null;
2014 }
John Reck5c6ac2f2011-01-05 10:18:03 -08002015 // We render to a bitmap 2x the desired size so that we can then
2016 // re-scale it with filtering since canvas.scale doesn't filter
2017 // This helps reduce aliasing at the cost of being slightly blurry
2018 final int filter_scale = 2;
John Reckd7dd9b22011-08-30 09:18:29 -07002019 int scaledWidth = width * filter_scale;
2020 int scaledHeight = height * filter_scale;
2021 if (sThumbnailBitmap == null || sThumbnailBitmap.getWidth() != scaledWidth
2022 || sThumbnailBitmap.getHeight() != scaledHeight) {
2023 if (sThumbnailBitmap != null) {
2024 sThumbnailBitmap.recycle();
2025 sThumbnailBitmap = null;
2026 }
2027 sThumbnailBitmap =
2028 Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.RGB_565);
Michael Kolb8233fac2010-10-26 16:08:53 -07002029 }
John Reckd7dd9b22011-08-30 09:18:29 -07002030 Canvas canvas = new Canvas(sThumbnailBitmap);
2031 int contentWidth = view.getContentWidth();
2032 float overviewScale = scaledWidth / (view.getScale() * contentWidth);
2033 if (view instanceof BrowserWebView) {
2034 int dy = -((BrowserWebView)view).getTitleHeight();
2035 canvas.translate(0, dy * overviewScale);
2036 }
2037
2038 canvas.scale(overviewScale, overviewScale);
2039
2040 if (view instanceof BrowserWebView) {
2041 ((BrowserWebView)view).drawContent(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07002042 } else {
John Reckd7dd9b22011-08-30 09:18:29 -07002043 view.draw(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07002044 }
John Reckd7dd9b22011-08-30 09:18:29 -07002045 Bitmap ret = Bitmap.createScaledBitmap(sThumbnailBitmap,
2046 width, height, true);
Dianne Hackborn43cfe8a2011-08-02 16:59:35 -07002047 canvas.setBitmap(null);
John Reck5c6ac2f2011-01-05 10:18:03 -08002048 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07002049 }
2050
John Reck34ef2672011-02-10 11:30:55 -08002051 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002052 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07002053 // FIXME: Would like to make sure there is actually something to
2054 // draw, but the API for that (WebViewCore.pictureReady()) is not
2055 // currently accessible here.
2056
John Reck34ef2672011-02-10 11:30:55 -08002057 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08002058 if (view == null) {
2059 // Tab was destroyed
2060 return;
2061 }
John Reck34ef2672011-02-10 11:30:55 -08002062 final String url = tab.getUrl();
2063 final String originalUrl = view.getOriginalUrl();
John Reck34ef2672011-02-10 11:30:55 -08002064 if (TextUtils.isEmpty(url)) {
2065 return;
2066 }
2067
2068 // Only update thumbnails for web urls (http(s)://), not for
2069 // about:, javascript:, data:, etc...
2070 // Unless it is a bookmarked site, then always update
2071 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2072 return;
2073 }
2074
Michael Kolb8233fac2010-10-26 16:08:53 -07002075 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2076 getDesiredThumbnailHeight(mActivity));
2077 if (bm == null) {
2078 return;
2079 }
2080
2081 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002082 new AsyncTask<Void, Void, Void>() {
2083 @Override
2084 protected Void doInBackground(Void... unused) {
2085 Cursor cursor = null;
2086 try {
2087 // TODO: Clean this up
2088 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2089 if (cursor != null && cursor.moveToFirst()) {
2090 final ByteArrayOutputStream os =
2091 new ByteArrayOutputStream();
2092 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002093
John Reck34ef2672011-02-10 11:30:55 -08002094 ContentValues values = new ContentValues();
2095 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002096
John Reck34ef2672011-02-10 11:30:55 -08002097 do {
John Reck617fd832011-02-16 14:35:59 -08002098 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002099 cr.update(Images.CONTENT_URI, values, null, null);
2100 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002101 }
John Reck34ef2672011-02-10 11:30:55 -08002102 } catch (IllegalStateException e) {
2103 // Ignore
2104 } finally {
2105 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002106 }
John Reck34ef2672011-02-10 11:30:55 -08002107 return null;
2108 }
2109 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002110 }
2111
2112 private class Copy implements OnMenuItemClickListener {
2113 private CharSequence mText;
2114
2115 public boolean onMenuItemClick(MenuItem item) {
2116 copy(mText);
2117 return true;
2118 }
2119
2120 public Copy(CharSequence toCopy) {
2121 mText = toCopy;
2122 }
2123 }
2124
Leon Scroggins63c02662010-11-18 15:16:27 -05002125 private static class Download implements OnMenuItemClickListener {
2126 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002127 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002128 private boolean mPrivateBrowsing;
George Mount387d45d2011-10-07 15:57:53 -07002129 private static final String FALLBACK_EXTENSION = "dat";
2130 private static final String IMAGE_BASE_FORMAT = "yyyy-MM-dd-HH-mm-ss-";
Michael Kolb8233fac2010-10-26 16:08:53 -07002131
2132 public boolean onMenuItemClick(MenuItem item) {
George Mount387d45d2011-10-07 15:57:53 -07002133 if (DataUri.isDataUri(mText)) {
2134 saveDataUri();
2135 } else {
2136 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
2137 null, null, mPrivateBrowsing);
2138 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002139 return true;
2140 }
2141
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002142 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002143 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002144 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002145 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002146 }
George Mount387d45d2011-10-07 15:57:53 -07002147
2148 /**
2149 * Treats mText as a data URI and writes its contents to a file
2150 * based on the current time.
2151 */
2152 private void saveDataUri() {
2153 FileOutputStream outputStream = null;
2154 try {
2155 DataUri uri = new DataUri(mText);
2156 File target = getTarget(uri);
2157 outputStream = new FileOutputStream(target);
2158 outputStream.write(uri.getData());
2159 final DownloadManager manager =
2160 (DownloadManager) mActivity.getSystemService(Context.DOWNLOAD_SERVICE);
2161 manager.addCompletedDownload(target.getName(),
2162 mActivity.getTitle().toString(), false,
2163 uri.getMimeType(), target.getAbsolutePath(),
George Mount7501bf42011-11-17 11:17:03 -08002164 (long)uri.getData().length, true);
George Mount387d45d2011-10-07 15:57:53 -07002165 } catch (IOException e) {
2166 Log.e(LOGTAG, "Could not save data URL");
2167 } finally {
2168 if (outputStream != null) {
2169 try {
2170 outputStream.close();
2171 } catch (IOException e) {
2172 // ignore close errors
2173 }
2174 }
2175 }
2176 }
2177
2178 /**
2179 * Creates a File based on the current time stamp and uses
2180 * the mime type of the DataUri to get the extension.
2181 */
2182 private File getTarget(DataUri uri) throws IOException {
2183 File dir = mActivity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
2184 DateFormat format = new SimpleDateFormat(IMAGE_BASE_FORMAT);
2185 String nameBase = format.format(new Date());
2186 String mimeType = uri.getMimeType();
2187 MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
2188 String extension = mimeTypeMap.getExtensionFromMimeType(mimeType);
2189 if (extension == null) {
2190 Log.w(LOGTAG, "Unknown mime type in data URI" + mimeType);
2191 extension = FALLBACK_EXTENSION;
2192 }
2193 extension = "." + extension; // createTempFile needs the '.'
2194 File targetFile = File.createTempFile(nameBase, extension, dir);
2195 return targetFile;
2196 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002197 }
2198
Cary Clark8974d282010-11-22 10:46:05 -05002199 private static class SelectText implements OnMenuItemClickListener {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002200 private WebViewClassic mWebView;
Cary Clark8974d282010-11-22 10:46:05 -05002201
2202 public boolean onMenuItemClick(MenuItem item) {
2203 if (mWebView != null) {
2204 return mWebView.selectText();
2205 }
2206 return false;
2207 }
2208
2209 public SelectText(WebView webView) {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002210 mWebView = WebViewClassic.fromWebView(webView);
Cary Clark8974d282010-11-22 10:46:05 -05002211 }
2212
2213 }
2214
Michael Kolb8233fac2010-10-26 16:08:53 -07002215 /********************** TODO: UI stuff *****************************/
2216
2217 // these methods have been copied, they still need to be cleaned up
2218
2219 /****************** tabs ***************************************************/
2220
2221 // basic tab interactions:
2222
2223 // it is assumed that tabcontrol already knows about the tab
2224 protected void addTab(Tab tab) {
2225 mUi.addTab(tab);
2226 }
2227
2228 protected void removeTab(Tab tab) {
2229 mUi.removeTab(tab);
2230 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002231 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002232 }
2233
Michael Kolbf2055602011-04-09 17:20:03 -07002234 @Override
2235 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002236 // monkey protection against delayed start
2237 if (tab != null) {
2238 mTabControl.setCurrentTab(tab);
2239 // the tab is guaranteed to have a webview after setCurrentTab
2240 mUi.setActiveTab(tab);
2241 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002242 }
2243
John Reck8bcafc12011-08-29 16:43:02 -07002244 protected void closeEmptyTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002245 Tab current = mTabControl.getCurrentTab();
2246 if (current != null
2247 && current.getWebView().copyBackForwardList().getSize() == 0) {
John Reck8bcafc12011-08-29 16:43:02 -07002248 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002249 }
2250 }
2251
John Reck26b18322011-06-21 13:08:58 -07002252 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002253 // Dismiss the subwindow if applicable.
2254 dismissSubWindow(appTab);
2255 // Since we might kill the WebView, remove it from the
2256 // content view first.
2257 mUi.detachTab(appTab);
2258 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002259 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002260 // TODO: analyze why the remove and add are necessary
2261 mUi.attachTab(appTab);
2262 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002263 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002264 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002265 } else {
2266 // If the tab was the current tab, we have to attach
2267 // it to the view system again.
2268 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002269 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002270 }
2271 }
2272
2273 // Remove the sub window if it exists. Also called by TabControl when the
2274 // user clicks the 'X' to dismiss a sub window.
2275 public void dismissSubWindow(Tab tab) {
2276 removeSubWindow(tab);
2277 // dismiss the subwindow. This will destroy the WebView.
2278 tab.dismissSubWindow();
Michael Kolbe8c97572011-11-21 14:03:56 -08002279 WebView wv = getCurrentTopWebView();
2280 if (wv != null) {
2281 wv.requestFocus();
2282 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002283 }
2284
2285 @Override
2286 public void removeSubWindow(Tab t) {
2287 if (t.getSubWebView() != null) {
2288 mUi.removeSubWindow(t.getSubViewContainer());
2289 }
2290 }
2291
2292 @Override
2293 public void attachSubWindow(Tab tab) {
2294 if (tab.getSubWebView() != null) {
2295 mUi.attachSubWindow(tab.getSubViewContainer());
2296 getCurrentTopWebView().requestFocus();
2297 }
2298 }
2299
Mathew Inwood29721c22011-06-29 17:55:24 +01002300 private Tab showPreloadedTab(final UrlData urlData) {
2301 if (!urlData.isPreloaded()) {
2302 return null;
2303 }
2304 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2305 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2306 if (sbQuery != null) {
Mathew Inwood9ad1eac2011-09-15 11:29:50 +01002307 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002308 // Could not submit query. Fallback to regular tab creation
2309 tabControl.destroy();
2310 return null;
2311 }
2312 }
Michael Kolbff6a7482011-07-26 16:37:15 -07002313 // check tab count and make room for new tab
2314 if (!mTabControl.canCreateNewTab()) {
2315 Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
2316 if (leastUsed != null) {
2317 closeTab(leastUsed);
2318 }
2319 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002320 Tab t = tabControl.getTab();
Mathew Inwoode09305e2011-09-02 12:03:26 +01002321 t.refreshIdAfterPreload();
Mathew Inwood29721c22011-06-29 17:55:24 +01002322 mTabControl.addPreloadedTab(t);
2323 addTab(t);
2324 setActiveTab(t);
2325 return t;
2326 }
2327
Michael Kolb7bcafde2011-05-09 13:55:59 -07002328 // open a non inconito tab with the given url data
2329 // and set as active tab
2330 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002331 Tab tab = showPreloadedTab(urlData);
2332 if (tab == null) {
2333 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002334 if ((tab != null) && !urlData.isEmpty()) {
2335 loadUrlDataIn(tab, urlData);
2336 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002337 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002338 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002339 }
2340
Michael Kolb843510f2010-12-09 10:51:49 -08002341 @Override
2342 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002343 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002344 }
2345
Michael Kolb8233fac2010-10-26 16:08:53 -07002346 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002347 public Tab openIncognitoTab() {
2348 return openTab(INCOGNITO_URI, true, true, false);
2349 }
2350
2351 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002352 public Tab openTab(String url, boolean incognito, boolean setActive,
2353 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002354 return openTab(url, incognito, setActive, useCurrent, null);
2355 }
2356
2357 @Override
2358 public Tab openTab(String url, Tab parent, boolean setActive,
2359 boolean useCurrent) {
2360 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2361 setActive, useCurrent, parent);
2362 }
2363
2364 public Tab openTab(String url, boolean incognito, boolean setActive,
2365 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002366 Tab tab = createNewTab(incognito, setActive, useCurrent);
2367 if (tab != null) {
John Reck5949c662011-05-27 09:52:29 -07002368 if (parent != null && parent != tab) {
2369 parent.addChildTab(tab);
2370 }
Michael Kolb519d2282011-05-09 17:03:19 -07002371 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002372 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002373 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002374 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002375 return tab;
2376 }
2377
2378 // this method will attempt to create a new tab
2379 // incognito: private browsing tab
2380 // setActive: ste tab as current tab
2381 // useCurrent: if no new tab can be created, return current tab
2382 private Tab createNewTab(boolean incognito, boolean setActive,
2383 boolean useCurrent) {
2384 Tab tab = null;
2385 if (mTabControl.canCreateNewTab()) {
2386 tab = mTabControl.createNewTab(incognito);
2387 addTab(tab);
2388 if (setActive) {
2389 setActiveTab(tab);
2390 }
2391 } else {
2392 if (useCurrent) {
2393 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002394 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002395 } else {
2396 mUi.showMaxTabsWarning();
2397 }
2398 }
2399 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002400 }
2401
John Reck2bc80422011-06-30 15:11:49 -07002402 @Override
2403 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2404 SnapshotTab tab = null;
2405 if (mTabControl.canCreateNewTab()) {
2406 tab = mTabControl.createSnapshotTab(snapshotId);
2407 addTab(tab);
2408 if (setActive) {
2409 setActiveTab(tab);
2410 }
2411 } else {
2412 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07002413 }
2414 return tab;
2415 }
2416
Michael Kolb8233fac2010-10-26 16:08:53 -07002417 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002418 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002419 * @return boolean True if we successfully switched to a different tab. If
2420 * the indexth tab is null, or if that tab is the same as
2421 * the current one, return false.
2422 */
2423 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002424 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002425 Tab currentTab = mTabControl.getCurrentTab();
2426 if (tab == null || tab == currentTab) {
2427 return false;
2428 }
2429 setActiveTab(tab);
2430 return true;
2431 }
2432
2433 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002434 public void closeCurrentTab() {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002435 closeCurrentTab(false);
2436 }
2437
2438 protected void closeCurrentTab(boolean andQuit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002439 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07002440 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07002441 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08002442 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002443 return;
2444 }
Michael Kolbc831b632011-05-11 09:30:34 -07002445 final Tab current = mTabControl.getCurrentTab();
2446 final int pos = mTabControl.getCurrentPosition();
2447 Tab newTab = current.getParent();
2448 if (newTab == null) {
2449 newTab = mTabControl.getTab(pos + 1);
2450 if (newTab == null) {
2451 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002452 }
2453 }
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002454 if (andQuit) {
2455 mTabControl.setCurrentTab(newTab);
2456 closeTab(current);
2457 } else if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002458 // Close window
2459 closeTab(current);
2460 }
2461 }
2462
2463 /**
2464 * Close the tab, remove its associated title bar, and adjust mTabControl's
2465 * current tab to a valid value.
2466 */
2467 @Override
2468 public void closeTab(Tab tab) {
John Reck28263772011-10-11 17:13:42 -07002469 if (tab == mTabControl.getCurrentTab()) {
2470 closeCurrentTab();
2471 } else {
2472 removeTab(tab);
2473 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002474 }
2475
Michael Kolb8233fac2010-10-26 16:08:53 -07002476 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07002477 protected void loadUrlFromContext(String url) {
2478 Tab tab = getCurrentTab();
2479 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002480 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07002481 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002482 url = UrlUtils.smartUrlFilter(url);
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002483 if (!WebViewClassic.fromWebView(view).getWebViewClient().
2484 shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07002485 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07002486 }
2487 }
2488 }
2489
2490 /**
2491 * Load the URL into the given WebView and update the title bar
2492 * to reflect the new load. Call this instead of WebView.loadUrl
2493 * directly.
2494 * @param view The WebView used to load url.
2495 * @param url The URL to load.
2496 */
John Reck71e51422011-07-01 16:49:28 -07002497 @Override
2498 public void loadUrl(Tab tab, String url) {
John Reck26b18322011-06-21 13:08:58 -07002499 loadUrl(tab, url, null);
2500 }
2501
2502 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
2503 if (tab != null) {
2504 dismissSubWindow(tab);
2505 tab.loadUrl(url, headers);
Michael Kolba53c9892011-10-05 13:31:40 -07002506 mUi.onProgressChanged(tab);
John Reck26b18322011-06-21 13:08:58 -07002507 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002508 }
2509
2510 /**
2511 * Load UrlData into a Tab and update the title bar to reflect the new
2512 * load. Call this instead of UrlData.loadIn directly.
2513 * @param t The Tab used to load.
2514 * @param data The UrlData being loaded.
2515 */
2516 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07002517 if (data != null) {
Michael Kolb5ff5c8b2012-05-03 11:37:58 -07002518 if (data.isPreloaded()) {
Michael Kolb14612442011-06-24 13:06:29 -07002519 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07002520 } else {
2521 loadUrl(t, data.mUrl, data.mHeaders);
2522 }
2523 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002524 }
2525
John Reck30c714c2010-12-16 17:30:34 -08002526 @Override
2527 public void onUserCanceledSsl(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08002528 // TODO: Figure out the "right" behavior
John Reckef654f12011-07-12 16:42:08 -07002529 if (tab.canGoBack()) {
2530 tab.goBack();
John Reck30c714c2010-12-16 17:30:34 -08002531 } else {
John Reckef654f12011-07-12 16:42:08 -07002532 tab.loadUrl(mSettings.getHomePage(), null);
John Reck30c714c2010-12-16 17:30:34 -08002533 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002534 }
2535
2536 void goBackOnePageOrQuit() {
2537 Tab current = mTabControl.getCurrentTab();
2538 if (current == null) {
2539 /*
2540 * Instead of finishing the activity, simply push this to the back
2541 * of the stack and let ActivityManager to choose the foreground
2542 * activity. As BrowserActivity is singleTask, it will be always the
2543 * root of the task. So we can use either true or false for
2544 * moveTaskToBack().
2545 */
2546 mActivity.moveTaskToBack(true);
2547 return;
2548 }
John Reckef654f12011-07-12 16:42:08 -07002549 if (current.canGoBack()) {
2550 current.goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07002551 } else {
2552 // Check to see if we are closing a window that was created by
2553 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002554 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002555 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002556 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002557 // Now we close the other tab
2558 closeTab(current);
2559 } else {
Michael Kolbe28b3472011-08-04 16:54:31 -07002560 if ((current.getAppId() != null) || current.closeOnBack()) {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002561 closeCurrentTab(true);
Michael Kolbe28b3472011-08-04 16:54:31 -07002562 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002563 /*
2564 * Instead of finishing the activity, simply push this to the back
2565 * of the stack and let ActivityManager to choose the foreground
2566 * activity. As BrowserActivity is singleTask, it will be always the
2567 * root of the task. So we can use either true or false for
2568 * moveTaskToBack().
2569 */
2570 mActivity.moveTaskToBack(true);
2571 }
2572 }
2573 }
2574
2575 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002576 * helper method for key handler
2577 * returns the current tab if it can't advance
2578 */
Michael Kolbc831b632011-05-11 09:30:34 -07002579 private Tab getNextTab() {
Michael Kolbf5261da2011-12-15 15:07:35 -08002580 int pos = mTabControl.getCurrentPosition() + 1;
2581 if (pos >= mTabControl.getTabCount()) {
2582 pos = 0;
2583 }
2584 return mTabControl.getTab(pos);
Michael Kolb0035fad2011-03-14 13:25:28 -07002585 }
2586
2587 /**
2588 * helper method for key handler
2589 * returns the current tab if it can't advance
2590 */
Michael Kolbc831b632011-05-11 09:30:34 -07002591 private Tab getPrevTab() {
Michael Kolbf5261da2011-12-15 15:07:35 -08002592 int pos = mTabControl.getCurrentPosition() - 1;
2593 if ( pos < 0) {
2594 pos = mTabControl.getTabCount() - 1;
2595 }
2596 return mTabControl.getTab(pos);
Michael Kolb0035fad2011-03-14 13:25:28 -07002597 }
2598
John Reckbcef87f2012-02-03 14:58:34 -08002599 boolean isMenuOrCtrlKey(int keyCode) {
2600 return (KeyEvent.KEYCODE_MENU == keyCode)
2601 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2602 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode);
2603 }
2604
Michael Kolb0035fad2011-03-14 13:25:28 -07002605 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002606 * handle key events in browser
2607 *
2608 * @param keyCode
2609 * @param event
2610 * @return true if handled, false to pass to super
2611 */
2612 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002613 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002614 // Even if MENU is already held down, we need to call to super to open
2615 // the IME on long press.
John Reckbcef87f2012-02-03 14:58:34 -08002616 if (!noModifiers && isMenuOrCtrlKey(keyCode)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002617 mMenuIsDown = true;
2618 return false;
2619 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002620
Cary Clark8ff8c662010-12-29 15:03:05 -05002621 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07002622 Tab tab = getCurrentTab();
2623 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05002624
Cary Clark160bbb92011-01-10 11:17:07 -05002625 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2626 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002627
Michael Kolb8233fac2010-10-26 16:08:53 -07002628 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002629 case KeyEvent.KEYCODE_TAB:
2630 if (event.isCtrlPressed()) {
2631 if (event.isShiftPressed()) {
2632 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002633 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002634 } else {
2635 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002636 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002637 }
2638 return true;
2639 }
2640 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002641 case KeyEvent.KEYCODE_SPACE:
2642 // WebView/WebTextView handle the keys in the KeyDown. As
2643 // the Activity's shortcut keys are only handled when WebView
2644 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002645 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002646 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002647 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002648 pageDown();
2649 }
2650 return true;
2651 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002652 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002653 event.startTracking();
2654 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07002655 case KeyEvent.KEYCODE_FORWARD:
2656 if (!noModifiers) break;
2657 tab.goForward();
2658 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002659 case KeyEvent.KEYCODE_DPAD_LEFT:
2660 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002661 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05002662 return true;
2663 }
2664 break;
2665 case KeyEvent.KEYCODE_DPAD_RIGHT:
2666 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002667 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05002668 return true;
2669 }
2670 break;
2671 case KeyEvent.KEYCODE_A:
2672 if (ctrl) {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002673 WebViewClassic.fromWebView(webView).selectAll();
Cary Clark8ff8c662010-12-29 15:03:05 -05002674 return true;
2675 }
2676 break;
Michael Kolba4183062011-01-16 10:43:21 -08002677// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002678 case KeyEvent.KEYCODE_C:
2679 if (ctrl) {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002680 WebViewClassic.fromWebView(webView).copySelection();
Cary Clark8ff8c662010-12-29 15:03:05 -05002681 return true;
2682 }
2683 break;
Michael Kolba4183062011-01-16 10:43:21 -08002684// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002685// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002686// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002687// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002688// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002689// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002690// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002691// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002692// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002693// case KeyEvent.KEYCODE_M: // unused
2694// case KeyEvent.KEYCODE_N: // in Chrome: new window
2695// case KeyEvent.KEYCODE_O: // in Chrome: open file
2696// case KeyEvent.KEYCODE_P: // in Chrome: print page
2697// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002698// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002699// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2700 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002701 // we can't use the ctrl/shift flags, they check for
2702 // exclusive use of a modifier
2703 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002704 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002705 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002706 } else {
2707 openTabToHomePage();
2708 }
2709 return true;
2710 }
2711 break;
2712// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2713// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb5ae15bd2011-08-16 17:09:27 -07002714// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002715// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2716// case KeyEvent.KEYCODE_Y: // unused
2717// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002718 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002719 // it is a regular key and webview is not null
2720 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002721 }
2722
John Recke6bf4ab2011-02-24 15:48:05 -08002723 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2724 switch(keyCode) {
2725 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07002726 if (mUi.isWebShowing()) {
Michael Kolb315d5022011-10-13 12:47:11 -07002727 bookmarksOrHistoryPicker(ComboViews.History);
John Recke6bf4ab2011-02-24 15:48:05 -08002728 return true;
2729 }
2730 break;
2731 }
2732 return false;
2733 }
2734
Michael Kolb8233fac2010-10-26 16:08:53 -07002735 boolean onKeyUp(int keyCode, KeyEvent event) {
John Reckbcef87f2012-02-03 14:58:34 -08002736 if (isMenuOrCtrlKey(keyCode)) {
Michael Kolb2814a362011-05-19 15:49:41 -07002737 mMenuIsDown = false;
John Reckbcef87f2012-02-03 14:58:34 -08002738 if (KeyEvent.KEYCODE_MENU == keyCode
2739 && event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002740 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002741 }
2742 }
Cary Clark160bbb92011-01-10 11:17:07 -05002743 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002744 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002745 case KeyEvent.KEYCODE_BACK:
2746 if (event.isTracking() && !event.isCanceled()) {
2747 onBackKey();
2748 return true;
2749 }
2750 break;
2751 }
2752 return false;
2753 }
2754
2755 public boolean isMenuDown() {
2756 return mMenuIsDown;
2757 }
2758
Ben Murdoch8029a772010-11-16 11:58:21 +00002759 public void setupAutoFill(Message message) {
2760 // Open the settings activity at the AutoFill profile fragment so that
2761 // the user can create a new profile. When they return, we will dispatch
2762 // the message so that we can autofill the form using their new profile.
2763 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2764 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2765 AutoFillSettingsFragment.class.getName());
2766 mAutoFillSetupMessage = message;
2767 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2768 }
John Reckb3417f02011-01-14 11:01:05 -08002769
Michael Kolbfbc579a2011-07-07 15:59:33 -07002770 public boolean onSearchRequested() {
Michael Kolb1f9b3562012-04-24 14:38:34 -07002771 mUi.editUrl(false, true);
Michael Kolbfbc579a2011-07-07 15:59:33 -07002772 return true;
2773 }
2774
John Reck1cf4b792011-07-26 10:22:22 -07002775 @Override
2776 public boolean shouldCaptureThumbnails() {
2777 return mUi.shouldCaptureThumbnails();
2778 }
2779
Michael Kolbc3af0672011-08-09 10:24:41 -07002780 @Override
2781 public void setBlockEvents(boolean block) {
2782 mBlockEvents = block;
2783 }
2784
2785 public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002786 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002787 }
2788
2789 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002790 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002791 }
2792
2793 public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002794 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002795 }
2796
2797 public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002798 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002799 }
2800
2801 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002802 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002803 }
2804
Michael Kolb8233fac2010-10-26 16:08:53 -07002805}