blob: ba74e5624cbc7a15046d26172129247217775756 [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) {
John Reck30c714c2010-12-16 17:30:34 -0800850 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700851 // pause the WebView timer and release the wake lock if it is finished
852 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800853 if (mActivityPaused && pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700854 releaseWakeLock();
Michael Kolb8233fac2010-10-26 16:08:53 -0700855 }
Martijn Coenenb2f93552011-06-14 10:48:35 +0200856
Michael Kolb8233fac2010-10-26 16:08:53 -0700857 // Performance probe
858 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800859 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700860 }
861
862 Performance.tracePageFinished();
863 }
864
865 @Override
John Reck30c714c2010-12-16 17:30:34 -0800866 public void onProgressChanged(Tab tab) {
John Reck6c2e2f32011-08-22 13:41:23 -0700867 mCrashRecoveryHandler.backupState();
John Reck30c714c2010-12-16 17:30:34 -0800868 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.
888 if (tab.inForeground() && !didUserStopLoading()
889 || !tab.inForeground()) {
890 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
891 mHandler.sendMessageDelayed(mHandler.obtainMessage(
892 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
893 500);
894 }
895 }
896 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700897 } else {
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800898 if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700899 // onPageFinished may have already been called but a subframe is
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800900 // still loading
901 // updating the progress and
Michael Kolb8233fac2010-10-26 16:08:53 -0700902 // update the menu items.
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800903 updateInLoadMenuItems(mCachedMenu, tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700904 }
905 }
John Reck30c714c2010-12-16 17:30:34 -0800906 mUi.onProgressChanged(tab);
907 }
908
909 @Override
Steve Block2466eff2011-10-03 15:33:09 +0100910 public void onUpdatedSecurityState(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800911 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700912 }
913
914 @Override
915 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800916 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800917 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800918 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700919 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
920 return;
921 }
922 // Update the title in the history database if not in private browsing mode
923 if (!tab.isPrivateBrowsingEnabled()) {
John Reckf57c0292011-07-21 18:15:39 -0700924 DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700925 }
926 }
927
928 @Override
929 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800930 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700931 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
932 }
933
934 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800935 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
936 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700937 }
938
939 @Override
940 public boolean shouldOverrideKeyEvent(KeyEvent event) {
941 if (mMenuIsDown) {
942 // only check shortcut key when MENU is held
943 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
944 event);
945 } else {
946 return false;
947 }
948 }
949
950 @Override
John Reck997b1b72012-04-19 18:08:25 -0700951 public boolean onUnhandledKeyEvent(KeyEvent event) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700952 if (!isActivityPaused()) {
953 if (event.getAction() == KeyEvent.ACTION_DOWN) {
John Reck997b1b72012-04-19 18:08:25 -0700954 return mActivity.onKeyDown(event.getKeyCode(), event);
Michael Kolb8233fac2010-10-26 16:08:53 -0700955 } else {
John Reck997b1b72012-04-19 18:08:25 -0700956 return mActivity.onKeyUp(event.getKeyCode(), event);
Michael Kolb8233fac2010-10-26 16:08:53 -0700957 }
958 }
John Reck997b1b72012-04-19 18:08:25 -0700959 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700960 }
961
962 @Override
John Reck324d4402011-01-11 16:56:42 -0800963 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700964 // Don't save anything in private browsing mode
965 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800966 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700967
John Reck324d4402011-01-11 16:56:42 -0800968 if (TextUtils.isEmpty(url)
969 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700970 return;
971 }
John Reckf57c0292011-07-21 18:15:39 -0700972 DataController.getInstance(mActivity).updateVisitedHistory(url);
John Reck6c2e2f32011-08-22 13:41:23 -0700973 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -0700974 }
975
976 @Override
977 public void getVisitedHistory(final ValueCallback<String[]> callback) {
978 AsyncTask<Void, Void, String[]> task =
979 new AsyncTask<Void, Void, String[]>() {
980 @Override
981 public String[] doInBackground(Void... unused) {
982 return Browser.getVisitedHistory(mActivity.getContentResolver());
983 }
984 @Override
985 public void onPostExecute(String[] result) {
986 callback.onReceiveValue(result);
987 }
988 };
989 task.execute();
990 }
991
992 @Override
993 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
994 final HttpAuthHandler handler, final String host,
995 final String realm) {
996 String username = null;
997 String password = null;
998
999 boolean reuseHttpAuthUsernamePassword
1000 = handler.useHttpAuthUsernamePassword();
1001
1002 if (reuseHttpAuthUsernamePassword && view != null) {
1003 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
1004 if (credentials != null && credentials.length == 2) {
1005 username = credentials[0];
1006 password = credentials[1];
1007 }
1008 }
1009
1010 if (username != null && password != null) {
1011 handler.proceed(username, password);
1012 } else {
Ben Murdochfdd37112011-08-05 15:48:14 +01001013 if (tab.inForeground() && !handler.suppressDialog()) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001014 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
1015 } else {
1016 handler.cancel();
1017 }
1018 }
1019 }
1020
1021 @Override
1022 public void onDownloadStart(Tab tab, String url, String userAgent,
1023 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001024 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -05001025 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001026 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
1027 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001028 // This Tab was opened for the sole purpose of downloading a
1029 // file. Remove it.
1030 if (tab == mTabControl.getCurrentTab()) {
1031 // In this case, the Tab is still on top.
1032 goBackOnePageOrQuit();
1033 } else {
1034 // In this case, it is not.
1035 closeTab(tab);
1036 }
1037 }
1038 }
1039
1040 @Override
1041 public Bitmap getDefaultVideoPoster() {
1042 return mUi.getDefaultVideoPoster();
1043 }
1044
1045 @Override
1046 public View getVideoLoadingProgressView() {
1047 return mUi.getVideoLoadingProgressView();
1048 }
1049
1050 @Override
1051 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1052 SslError error) {
1053 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1054 }
1055
Patrick Scott92066772011-03-10 08:46:27 -05001056 @Override
1057 public void showAutoLogin(Tab tab) {
1058 assert tab.inForeground();
1059 // Update the title bar to show the auto-login request.
1060 mUi.showAutoLogin(tab);
1061 }
1062
1063 @Override
1064 public void hideAutoLogin(Tab tab) {
1065 assert tab.inForeground();
1066 mUi.hideAutoLogin(tab);
1067 }
1068
Michael Kolb8233fac2010-10-26 16:08:53 -07001069 // helper method
1070
1071 /*
1072 * Update the favorites icon if the private browsing isn't enabled and the
1073 * icon is valid.
1074 */
1075 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1076 final String url, Bitmap favicon) {
1077 if (favicon == null) {
1078 return;
1079 }
1080 if (!tab.isPrivateBrowsingEnabled()) {
1081 Bookmarks.updateFavicon(mActivity
1082 .getContentResolver(), originalUrl, url, favicon);
1083 }
1084 }
1085
Leon Scroggins4cd97792010-12-03 15:31:56 -05001086 @Override
1087 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001088 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001089 mUi.bookmarkedStatusHasChanged(tab);
1090 }
1091
Michael Kolb8233fac2010-10-26 16:08:53 -07001092 // end WebViewController
1093
1094 protected void pageUp() {
1095 getCurrentTopWebView().pageUp(false);
1096 }
1097
1098 protected void pageDown() {
1099 getCurrentTopWebView().pageDown(false);
1100 }
1101
1102 // callback from phone title bar
1103 public void editUrl() {
1104 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolb1f9b3562012-04-24 14:38:34 -07001105 mUi.editUrl(false, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001106 }
1107
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001108 public void showCustomView(Tab tab, View view, int requestedOrientation,
Michael Kolb8233fac2010-10-26 16:08:53 -07001109 WebChromeClient.CustomViewCallback callback) {
1110 if (tab.inForeground()) {
1111 if (mUi.isCustomViewShowing()) {
1112 callback.onCustomViewHidden();
1113 return;
1114 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001115 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001116 // Save the menu state and set it to empty while the custom
1117 // view is showing.
1118 mOldMenuState = mMenuState;
1119 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001120 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001121 }
1122 }
1123
1124 @Override
1125 public void hideCustomView() {
1126 if (mUi.isCustomViewShowing()) {
1127 mUi.onHideCustomView();
1128 // Reset the old menu state.
1129 mMenuState = mOldMenuState;
1130 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001131 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001132 }
1133 }
1134
1135 protected void onActivityResult(int requestCode, int resultCode,
1136 Intent intent) {
1137 if (getCurrentTopWebView() == null) return;
1138 switch (requestCode) {
1139 case PREFERENCES_PAGE:
1140 if (resultCode == Activity.RESULT_OK && intent != null) {
1141 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001142 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001143 mTabControl.removeParentChildRelationShips();
1144 }
1145 }
1146 break;
1147 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001148 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001149 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001150 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001151 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001152 case AUTOFILL_SETUP:
1153 // Determine whether a profile was actually set up or not
1154 // and if so, send the message back to the WebTextView to
1155 // fill the form with the new profile.
1156 if (getSettings().getAutoFillProfile() != null) {
1157 mAutoFillSetupMessage.sendToTarget();
1158 mAutoFillSetupMessage = null;
1159 }
1160 break;
John Reckd3e4d5b2011-07-13 15:48:43 -07001161 case COMBO_VIEW:
1162 if (intent == null || resultCode != Activity.RESULT_OK) {
1163 break;
1164 }
John Reck3ba45532011-08-11 16:26:53 -07001165 mUi.showWeb(false);
John Reckd3e4d5b2011-07-13 15:48:43 -07001166 if (Intent.ACTION_VIEW.equals(intent.getAction())) {
1167 Tab t = getCurrentTab();
1168 Uri uri = intent.getData();
1169 loadUrl(t, uri.toString());
1170 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
1171 String[] urls = intent.getStringArrayExtra(
1172 ComboViewActivity.EXTRA_OPEN_ALL);
1173 Tab parent = getCurrentTab();
1174 for (String url : urls) {
1175 parent = openTab(url, parent,
1176 !mSettings.openInBackground(), true);
1177 }
1178 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
1179 long id = intent.getLongExtra(
1180 ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
1181 if (id >= 0) {
1182 createNewSnapshotTab(id, true);
1183 }
1184 }
1185 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001186 default:
1187 break;
1188 }
1189 getCurrentTopWebView().requestFocus();
1190 }
1191
1192 /**
1193 * Open the Go page.
1194 * @param startWithHistory If true, open starting on the history tab.
1195 * Otherwise, start with the bookmarks tab.
1196 */
1197 @Override
Michael Kolb315d5022011-10-13 12:47:11 -07001198 public void bookmarksOrHistoryPicker(ComboViews startView) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001199 if (mTabControl.getCurrentWebView() == null) {
1200 return;
1201 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001202 // clear action mode
1203 if (isInCustomActionMode()) {
1204 endActionMode();
1205 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001206 Bundle extras = new Bundle();
1207 // Disable opening in a new window if we have maxed out the windows
1208 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1209 !mTabControl.canCreateNewTab());
Michael Kolb315d5022011-10-13 12:47:11 -07001210 mUi.showComboView(startView, extras);
Michael Kolb8233fac2010-10-26 16:08:53 -07001211 }
1212
1213 // combo view callbacks
1214
Michael Kolb8233fac2010-10-26 16:08:53 -07001215 // key handling
1216 protected void onBackKey() {
1217 if (!mUi.onBackKey()) {
1218 WebView subwindow = mTabControl.getCurrentSubWindow();
1219 if (subwindow != null) {
1220 if (subwindow.canGoBack()) {
1221 subwindow.goBack();
1222 } else {
1223 dismissSubWindow(mTabControl.getCurrentTab());
1224 }
1225 } else {
1226 goBackOnePageOrQuit();
1227 }
1228 }
1229 }
1230
Michael Kolb4bd767d2011-05-27 11:33:55 -07001231 protected boolean onMenuKey() {
1232 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001233 }
1234
Michael Kolb8233fac2010-10-26 16:08:53 -07001235 // menu handling and state
1236 // TODO: maybe put into separate handler
1237
1238 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckd73c5a22010-12-22 10:22:50 -08001239 if (mMenuState == EMPTY_MENU) {
1240 return false;
1241 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001242 MenuInflater inflater = mActivity.getMenuInflater();
1243 inflater.inflate(R.menu.browser, menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001244 return true;
1245 }
1246
1247 protected void onCreateContextMenu(ContextMenu menu, View v,
1248 ContextMenuInfo menuInfo) {
John Reck0f602f32011-07-07 15:38:43 -07001249 if (v instanceof TitleBar) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001250 return;
1251 }
1252 if (!(v instanceof WebView)) {
1253 return;
1254 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001255 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001256 WebView.HitTestResult result = webview.getHitTestResult();
1257 if (result == null) {
1258 return;
1259 }
1260
1261 int type = result.getType();
1262 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1263 Log.w(LOGTAG,
1264 "We should not show context menu when nothing is touched");
1265 return;
1266 }
1267 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1268 // let TextView handles context menu
1269 return;
1270 }
1271
1272 // Note, http://b/issue?id=1106666 is requesting that
1273 // an inflated menu can be used again. This is not available
1274 // yet, so inflate each time (yuk!)
1275 MenuInflater inflater = mActivity.getMenuInflater();
1276 inflater.inflate(R.menu.browsercontext, menu);
1277
1278 // Show the correct menu group
1279 final String extra = result.getExtra();
Michael Kolbc159c1a2011-12-15 16:06:38 -08001280 if (extra == null) return;
Michael Kolb8233fac2010-10-26 16:08:53 -07001281 menu.setGroupVisible(R.id.PHONE_MENU,
1282 type == WebView.HitTestResult.PHONE_TYPE);
1283 menu.setGroupVisible(R.id.EMAIL_MENU,
1284 type == WebView.HitTestResult.EMAIL_TYPE);
1285 menu.setGroupVisible(R.id.GEO_MENU,
1286 type == WebView.HitTestResult.GEO_TYPE);
1287 menu.setGroupVisible(R.id.IMAGE_MENU,
1288 type == WebView.HitTestResult.IMAGE_TYPE
1289 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1290 menu.setGroupVisible(R.id.ANCHOR_MENU,
1291 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1292 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001293 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1294 || type == WebView.HitTestResult.PHONE_TYPE
1295 || type == WebView.HitTestResult.EMAIL_TYPE
1296 || type == WebView.HitTestResult.GEO_TYPE;
1297 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1298 if (hitText) {
1299 menu.findItem(R.id.select_text_menu_id)
1300 .setOnMenuItemClickListener(new SelectText(webview));
1301 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001302 // Setup custom handling depending on the type
1303 switch (type) {
1304 case WebView.HitTestResult.PHONE_TYPE:
1305 menu.setHeaderTitle(Uri.decode(extra));
1306 menu.findItem(R.id.dial_context_menu_id).setIntent(
1307 new Intent(Intent.ACTION_VIEW, Uri
1308 .parse(WebView.SCHEME_TEL + extra)));
1309 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1310 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1311 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1312 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1313 addIntent);
1314 menu.findItem(R.id.copy_phone_context_menu_id)
1315 .setOnMenuItemClickListener(
1316 new Copy(extra));
1317 break;
1318
1319 case WebView.HitTestResult.EMAIL_TYPE:
1320 menu.setHeaderTitle(extra);
1321 menu.findItem(R.id.email_context_menu_id).setIntent(
1322 new Intent(Intent.ACTION_VIEW, Uri
1323 .parse(WebView.SCHEME_MAILTO + extra)));
1324 menu.findItem(R.id.copy_mail_context_menu_id)
1325 .setOnMenuItemClickListener(
1326 new Copy(extra));
1327 break;
1328
1329 case WebView.HitTestResult.GEO_TYPE:
1330 menu.setHeaderTitle(extra);
1331 menu.findItem(R.id.map_context_menu_id).setIntent(
1332 new Intent(Intent.ACTION_VIEW, Uri
1333 .parse(WebView.SCHEME_GEO
1334 + URLEncoder.encode(extra))));
1335 menu.findItem(R.id.copy_geo_context_menu_id)
1336 .setOnMenuItemClickListener(
1337 new Copy(extra));
1338 break;
1339
1340 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1341 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001342 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001343 // decide whether to show the open link in new tab option
1344 boolean showNewTab = mTabControl.canCreateNewTab();
1345 MenuItem newTabItem
1346 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001347 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001348 ? R.string.contextmenu_openlink_newwindow_background
1349 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001350 newTabItem.setVisible(showNewTab);
1351 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001352 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1353 newTabItem.setOnMenuItemClickListener(
1354 new MenuItem.OnMenuItemClickListener() {
1355 @Override
1356 public boolean onMenuItemClick(MenuItem item) {
1357 final HashMap<String, WebView> hrefMap =
1358 new HashMap<String, WebView>();
1359 hrefMap.put("webview", webview);
1360 final Message msg = mHandler.obtainMessage(
1361 FOCUS_NODE_HREF,
1362 R.id.open_newtab_context_menu_id,
1363 0, hrefMap);
1364 webview.requestFocusNodeHref(msg);
1365 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001366 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001367 });
1368 } else {
1369 newTabItem.setOnMenuItemClickListener(
1370 new MenuItem.OnMenuItemClickListener() {
1371 @Override
1372 public boolean onMenuItemClick(MenuItem item) {
1373 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001374 openTab(extra, parent,
1375 !mSettings.openInBackground(),
1376 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001377 return true;
1378 }
1379 });
1380 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001381 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001382 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1383 break;
1384 }
1385 // otherwise fall through to handle image part
1386 case WebView.HitTestResult.IMAGE_TYPE:
Victoria Lease5987b802012-03-12 13:05:23 -07001387 MenuItem shareItem = menu.findItem(R.id.share_link_context_menu_id);
1388 shareItem.setVisible(type == WebView.HitTestResult.IMAGE_TYPE);
Michael Kolb8233fac2010-10-26 16:08:53 -07001389 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1390 menu.setHeaderTitle(extra);
Victoria Lease5987b802012-03-12 13:05:23 -07001391 shareItem.setOnMenuItemClickListener(
1392 new MenuItem.OnMenuItemClickListener() {
1393 @Override
1394 public boolean onMenuItemClick(MenuItem item) {
1395 sharePage(mActivity, null, extra, null,
1396 null);
1397 return true;
1398 }
1399 }
1400 );
Michael Kolb8233fac2010-10-26 16:08:53 -07001401 }
Michael Kolb3639c4c2011-09-28 15:36:40 -07001402 menu.findItem(R.id.view_image_context_menu_id)
1403 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1404 @Override
1405 public boolean onMenuItemClick(MenuItem item) {
1406 openTab(extra, mTabControl.getCurrentTab(), true, true);
1407 return false;
1408 }
1409 });
Michael Kolb8233fac2010-10-26 16:08:53 -07001410 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001411 setOnMenuItemClickListener(
1412 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001413 menu.findItem(R.id.set_wallpaper_context_menu_id).
1414 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1415 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001416 break;
1417
1418 default:
1419 Log.w(LOGTAG, "We should not get here.");
1420 break;
1421 }
1422 //update the ui
1423 mUi.onContextMenuCreated(menu);
1424 }
1425
1426 /**
1427 * As the menu can be open when loading state changes
1428 * we must manually update the state of the stop/reload menu
1429 * item
1430 */
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001431 private void updateInLoadMenuItems(Menu menu, Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001432 if (menu == null) {
1433 return;
1434 }
1435 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolbb8337132011-11-28 15:07:39 -08001436 MenuItem src = ((tab != null) && tab.inPageLoad()) ?
Michael Kolb8233fac2010-10-26 16:08:53 -07001437 menu.findItem(R.id.stop_menu_id):
1438 menu.findItem(R.id.reload_menu_id);
1439 if (src != null) {
1440 dest.setIcon(src.getIcon());
1441 dest.setTitle(src.getTitle());
1442 }
1443 }
1444
John Reckb3417f02011-01-14 11:01:05 -08001445 boolean onPrepareOptionsMenu(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001446 updateInLoadMenuItems(menu, getCurrentTab());
John Recke1a03a32011-09-14 17:04:16 -07001447 // hold on to the menu reference here; it is used by the page callbacks
1448 // to update the menu based on loading state
1449 mCachedMenu = menu;
Michael Kolb8233fac2010-10-26 16:08:53 -07001450 // Note: setVisible will decide whether an item is visible; while
1451 // setEnabled() will decide whether an item is enabled, which also means
1452 // whether the matching shortcut key will function.
1453 switch (mMenuState) {
1454 case EMPTY_MENU:
1455 if (mCurrentMenuState != mMenuState) {
1456 menu.setGroupVisible(R.id.MAIN_MENU, false);
1457 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1458 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1459 }
1460 break;
1461 default:
1462 if (mCurrentMenuState != mMenuState) {
1463 menu.setGroupVisible(R.id.MAIN_MENU, true);
1464 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1465 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1466 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001467 updateMenuState(getCurrentTab(), menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001468 break;
1469 }
1470 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001471 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001472 }
1473
Michael Kolb4bf79712011-07-14 14:18:12 -07001474 @Override
1475 public void updateMenuState(Tab tab, Menu menu) {
1476 boolean canGoBack = false;
1477 boolean canGoForward = false;
1478 boolean isHome = false;
John Reck42229bc2011-08-19 13:26:43 -07001479 boolean isDesktopUa = false;
John Recke1a03a32011-09-14 17:04:16 -07001480 boolean isLive = false;
Michael Kolb4bf79712011-07-14 14:18:12 -07001481 if (tab != null) {
1482 canGoBack = tab.canGoBack();
1483 canGoForward = tab.canGoForward();
1484 isHome = mSettings.getHomePage().equals(tab.getUrl());
John Reck42229bc2011-08-19 13:26:43 -07001485 isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
John Recke1a03a32011-09-14 17:04:16 -07001486 isLive = !tab.isSnapshot();
Michael Kolb4bf79712011-07-14 14:18:12 -07001487 }
1488 final MenuItem back = menu.findItem(R.id.back_menu_id);
1489 back.setEnabled(canGoBack);
1490
1491 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1492 home.setEnabled(!isHome);
1493
1494 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1495 forward.setEnabled(canGoForward);
1496
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001497 final MenuItem source = menu.findItem(isInLoad() ? R.id.stop_menu_id
1498 : R.id.reload_menu_id);
Michael Kolb4bf79712011-07-14 14:18:12 -07001499 final MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolb7ab75ee2011-07-14 16:36:38 -07001500 if (source != null && dest != null) {
1501 dest.setTitle(source.getTitle());
1502 dest.setIcon(source.getIcon());
1503 }
John Recke1a03a32011-09-14 17:04:16 -07001504 menu.setGroupVisible(R.id.NAV_MENU, isLive);
Michael Kolb4bf79712011-07-14 14:18:12 -07001505
1506 // decide whether to show the share link option
1507 PackageManager pm = mActivity.getPackageManager();
1508 Intent send = new Intent(Intent.ACTION_SEND);
1509 send.setType("text/plain");
1510 ResolveInfo ri = pm.resolveActivity(send,
1511 PackageManager.MATCH_DEFAULT_ONLY);
1512 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1513
1514 boolean isNavDump = mSettings.enableNavDump();
1515 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1516 nav.setVisible(isNavDump);
1517 nav.setEnabled(isNavDump);
1518
1519 boolean showDebugSettings = mSettings.isDebugEnabled();
John Reck42229bc2011-08-19 13:26:43 -07001520 final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
1521 uaSwitcher.setChecked(isDesktopUa);
John Recke1a03a32011-09-14 17:04:16 -07001522 menu.setGroupVisible(R.id.LIVE_MENU, isLive);
1523 menu.setGroupVisible(R.id.SNAPSHOT_MENU, !isLive);
Michael Kolb315d5022011-10-13 12:47:11 -07001524 menu.setGroupVisible(R.id.COMBO_MENU, false);
Michael Kolb4bf79712011-07-14 14:18:12 -07001525
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001526 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001527 }
1528
Michael Kolb8233fac2010-10-26 16:08:53 -07001529 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001530 if (null == getCurrentTopWebView()) {
1531 return false;
1532 }
1533 if (mMenuIsDown) {
1534 // The shortcut action consumes the MENU. Even if it is still down,
1535 // it won't trigger the next shortcut action. In the case of the
1536 // shortcut action triggering a new activity, like Bookmarks, we
1537 // won't get onKeyUp for MENU. So it is important to reset it here.
1538 mMenuIsDown = false;
1539 }
Michael Kolb3ca12752011-07-20 13:52:25 -07001540 if (mUi.onOptionsItemSelected(item)) {
1541 // ui callback handled it
1542 return true;
1543 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001544 switch (item.getItemId()) {
1545 // -- Main menu
1546 case R.id.new_tab_menu_id:
1547 openTabToHomePage();
1548 break;
1549
1550 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001551 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001552 break;
1553
1554 case R.id.goto_menu_id:
1555 editUrl();
1556 break;
1557
1558 case R.id.bookmarks_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001559 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
1560 break;
1561
1562 case R.id.history_menu_id:
1563 bookmarksOrHistoryPicker(ComboViews.History);
1564 break;
1565
1566 case R.id.snapshots_menu_id:
1567 bookmarksOrHistoryPicker(ComboViews.Snapshots);
Michael Kolb8233fac2010-10-26 16:08:53 -07001568 break;
1569
Michael Kolb8233fac2010-10-26 16:08:53 -07001570 case R.id.add_bookmark_menu_id:
Michael Kolb80f75082012-04-10 10:50:06 -07001571 bookmarkCurrentPage();
Michael Kolb8233fac2010-10-26 16:08:53 -07001572 break;
1573
1574 case R.id.stop_reload_menu_id:
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001575 if (isInLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001576 stopLoading();
1577 } else {
1578 getCurrentTopWebView().reload();
1579 }
1580 break;
1581
1582 case R.id.back_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001583 getCurrentTab().goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07001584 break;
1585
1586 case R.id.forward_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001587 getCurrentTab().goForward();
Michael Kolb8233fac2010-10-26 16:08:53 -07001588 break;
1589
1590 case R.id.close_menu_id:
1591 // Close the subwindow if it exists.
1592 if (mTabControl.getCurrentSubWindow() != null) {
1593 dismissSubWindow(mTabControl.getCurrentTab());
1594 break;
1595 }
1596 closeCurrentTab();
1597 break;
1598
1599 case R.id.homepage_menu_id:
1600 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07001601 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07001602 break;
1603
1604 case R.id.preferences_menu_id:
Michael Kolb80f75082012-04-10 10:50:06 -07001605 openPreferences();
Michael Kolb8233fac2010-10-26 16:08:53 -07001606 break;
1607
1608 case R.id.find_menu_id:
Michael Kolbe11b9212012-04-13 13:39:54 -07001609 findOnPage();
Michael Kolb8233fac2010-10-26 16:08:53 -07001610 break;
1611
John Reck2bc80422011-06-30 15:11:49 -07001612 case R.id.save_snapshot_menu_id:
1613 final Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07001614 if (source == null) break;
John Reck68234a92012-04-19 15:27:12 -07001615 new SaveSnapshotTask(source).execute();
Leon Scrogginsac993842011-02-02 12:54:07 -05001616 break;
1617
Michael Kolb8233fac2010-10-26 16:08:53 -07001618 case R.id.page_info_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001619 showPageInfo();
Michael Kolb8233fac2010-10-26 16:08:53 -07001620 break;
1621
John Recke1a03a32011-09-14 17:04:16 -07001622 case R.id.snapshot_go_live:
1623 goLive();
1624 return true;
1625
Michael Kolb8233fac2010-10-26 16:08:53 -07001626 case R.id.share_page_menu_id:
1627 Tab currentTab = mTabControl.getCurrentTab();
1628 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001629 return false;
1630 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001631 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001632 break;
1633
1634 case R.id.dump_nav_menu_id:
1635 getCurrentTopWebView().debugDump();
1636 break;
1637
Michael Kolb8233fac2010-10-26 16:08:53 -07001638 case R.id.zoom_in_menu_id:
1639 getCurrentTopWebView().zoomIn();
1640 break;
1641
1642 case R.id.zoom_out_menu_id:
1643 getCurrentTopWebView().zoomOut();
1644 break;
1645
1646 case R.id.view_downloads_menu_id:
1647 viewDownloads();
1648 break;
1649
John Reck42229bc2011-08-19 13:26:43 -07001650 case R.id.ua_desktop_menu_id:
Michael Kolb80f75082012-04-10 10:50:06 -07001651 toggleUserAgent();
John Reck42229bc2011-08-19 13:26:43 -07001652 break;
1653
Michael Kolb8233fac2010-10-26 16:08:53 -07001654 case R.id.window_one_menu_id:
1655 case R.id.window_two_menu_id:
1656 case R.id.window_three_menu_id:
1657 case R.id.window_four_menu_id:
1658 case R.id.window_five_menu_id:
1659 case R.id.window_six_menu_id:
1660 case R.id.window_seven_menu_id:
1661 case R.id.window_eight_menu_id:
1662 {
1663 int menuid = item.getItemId();
1664 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1665 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1666 Tab desiredTab = mTabControl.getTab(id);
1667 if (desiredTab != null &&
1668 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001669 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001670 }
1671 break;
1672 }
1673 }
1674 }
1675 break;
1676
1677 default:
1678 return false;
1679 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001680 return true;
1681 }
1682
John Reck68234a92012-04-19 15:27:12 -07001683 private class SaveSnapshotTask extends AsyncTask<Void, Void, Long>
1684 implements OnCancelListener {
1685
1686 private Tab mTab;
1687 private Dialog mProgressDialog;
1688 private ContentValues mValues;
1689
1690 private SaveSnapshotTask(Tab tab) {
1691 mTab = tab;
1692 }
1693
1694 @Override
1695 protected void onPreExecute() {
1696 CharSequence message = mActivity.getText(R.string.saving_snapshot);
1697 mProgressDialog = ProgressDialog.show(mActivity, null, message,
1698 true, true, this);
1699 mValues = mTab.createSnapshotValues();
1700 }
1701
1702 @Override
1703 protected Long doInBackground(Void... params) {
1704 if (!mTab.saveViewState(mValues)) {
1705 return null;
1706 }
1707 if (isCancelled()) {
1708 String path = mValues.getAsString(Snapshots.VIEWSTATE_PATH);
1709 File file = mActivity.getFileStreamPath(path);
1710 if (!file.delete()) {
1711 file.deleteOnExit();
1712 }
1713 return null;
1714 }
1715 final ContentResolver cr = mActivity.getContentResolver();
1716 Uri result = cr.insert(Snapshots.CONTENT_URI, mValues);
1717 if (result == null) {
1718 return null;
1719 }
1720 long id = ContentUris.parseId(result);
1721 return id;
1722 }
1723
1724 @Override
1725 protected void onPostExecute(Long id) {
1726 if (isCancelled()) {
1727 return;
1728 }
1729 mProgressDialog.dismiss();
1730 if (id == null) {
1731 Toast.makeText(mActivity, R.string.snapshot_failed,
1732 Toast.LENGTH_SHORT).show();
1733 return;
1734 }
1735 Bundle b = new Bundle();
1736 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
1737 mUi.showComboView(ComboViews.Snapshots, b);
1738 }
1739
1740 @Override
1741 public void onCancel(DialogInterface dialog) {
1742 cancel(true);
1743 }
1744 }
1745
Michael Kolb80f75082012-04-10 10:50:06 -07001746 @Override
1747 public void toggleUserAgent() {
1748 WebView web = getCurrentWebView();
1749 mSettings.toggleDesktopUseragent(web);
1750 web.loadUrl(web.getOriginalUrl());
1751 }
1752
1753 @Override
1754 public void findOnPage() {
1755 getCurrentTopWebView().showFindDialog(null, true);
1756 }
1757
1758 @Override
1759 public void openPreferences() {
1760 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1761 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1762 getCurrentTopWebView().getUrl());
1763 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1764 }
1765
1766 @Override
1767 public void bookmarkCurrentPage() {
1768 Intent bookmarkIntent = createBookmarkCurrentPageIntent(false);
1769 if (bookmarkIntent != null) {
1770 mActivity.startActivity(bookmarkIntent);
1771 }
1772 }
1773
John Recke1a03a32011-09-14 17:04:16 -07001774 private void goLive() {
1775 Tab t = getCurrentTab();
1776 t.loadUrl(t.getUrl(), null);
1777 }
1778
Michael Kolb315d5022011-10-13 12:47:11 -07001779 @Override
1780 public void showPageInfo() {
1781 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
1782 }
1783
Michael Kolb8233fac2010-10-26 16:08:53 -07001784 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001785 // Let the History and Bookmark fragments handle menus they created.
1786 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1787 return false;
1788 }
1789
Michael Kolb8233fac2010-10-26 16:08:53 -07001790 int id = item.getItemId();
1791 boolean result = true;
1792 switch (id) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001793 // -- Browser context menu
1794 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001795 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001796 case R.id.copy_link_context_menu_id:
1797 final WebView webView = getCurrentTopWebView();
1798 if (null == webView) {
1799 result = false;
1800 break;
1801 }
1802 final HashMap<String, WebView> hrefMap =
1803 new HashMap<String, WebView>();
1804 hrefMap.put("webview", webView);
1805 final Message msg = mHandler.obtainMessage(
1806 FOCUS_NODE_HREF, id, 0, hrefMap);
1807 webView.requestFocusNodeHref(msg);
1808 break;
1809
1810 default:
1811 // For other context menus
1812 result = onOptionsItemSelected(item);
1813 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001814 return result;
1815 }
1816
1817 /**
1818 * support programmatically opening the context menu
1819 */
1820 public void openContextMenu(View view) {
1821 mActivity.openContextMenu(view);
1822 }
1823
1824 /**
1825 * programmatically open the options menu
1826 */
1827 public void openOptionsMenu() {
1828 mActivity.openOptionsMenu();
1829 }
1830
1831 public boolean onMenuOpened(int featureId, Menu menu) {
1832 if (mOptionsMenuOpen) {
1833 if (mConfigChanged) {
1834 // We do not need to make any changes to the state of the
1835 // title bar, since the only thing that happened was a
1836 // change in orientation
1837 mConfigChanged = false;
1838 } else {
1839 if (!mExtendedMenuOpen) {
1840 mExtendedMenuOpen = true;
1841 mUi.onExtendedMenuOpened();
1842 } else {
1843 // Switching the menu back to icon view, so show the
1844 // title bar once again.
1845 mExtendedMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001846 mUi.onExtendedMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001847 }
1848 }
1849 } else {
1850 // The options menu is closed, so open it, and show the title
1851 mOptionsMenuOpen = true;
1852 mConfigChanged = false;
1853 mExtendedMenuOpen = false;
1854 mUi.onOptionsMenuOpened();
1855 }
1856 return true;
1857 }
1858
1859 public void onOptionsMenuClosed(Menu menu) {
1860 mOptionsMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001861 mUi.onOptionsMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001862 }
1863
1864 public void onContextMenuClosed(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001865 mUi.onContextMenuClosed(menu, isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001866 }
1867
1868 // Helper method for getting the top window.
1869 @Override
1870 public WebView getCurrentTopWebView() {
1871 return mTabControl.getCurrentTopWebView();
1872 }
1873
1874 @Override
1875 public WebView getCurrentWebView() {
1876 return mTabControl.getCurrentWebView();
1877 }
1878
1879 /*
1880 * This method is called as a result of the user selecting the options
1881 * menu to see the download window. It shows the download window on top of
1882 * the current window.
1883 */
1884 void viewDownloads() {
1885 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1886 mActivity.startActivity(intent);
1887 }
1888
John Reck30b065e2011-07-19 10:58:05 -07001889 int getActionModeHeight() {
1890 TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
1891 new int[] { android.R.attr.actionBarSize });
1892 int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
1893 actionBarSizeTypedArray.recycle();
1894 return size;
1895 }
1896
Michael Kolb8233fac2010-10-26 16:08:53 -07001897 // action mode
1898
1899 void onActionModeStarted(ActionMode mode) {
1900 mUi.onActionModeStarted(mode);
1901 mActionMode = mode;
1902 }
1903
1904 /*
1905 * True if a custom ActionMode (i.e. find or select) is in use.
1906 */
1907 @Override
1908 public boolean isInCustomActionMode() {
1909 return mActionMode != null;
1910 }
1911
1912 /*
1913 * End the current ActionMode.
1914 */
1915 @Override
1916 public void endActionMode() {
1917 if (mActionMode != null) {
1918 mActionMode.finish();
1919 }
1920 }
1921
1922 /*
1923 * Called by find and select when they are finished. Replace title bars
1924 * as necessary.
1925 */
1926 public void onActionModeFinished(ActionMode mode) {
1927 if (!isInCustomActionMode()) return;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001928 mUi.onActionModeFinished(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001929 mActionMode = null;
1930 }
1931
1932 boolean isInLoad() {
Michael Kolbc5b0b2d2011-11-29 16:13:35 -08001933 final Tab tab = getCurrentTab();
1934 return (tab != null) && tab.inPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07001935 }
1936
1937 // bookmark handling
1938
1939 /**
1940 * add the current page as a bookmark to the given folder id
1941 * @param folderId use -1 for the default folder
John Reckd3e4d5b2011-07-13 15:48:43 -07001942 * @param editExisting If true, check to see whether the site is already
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001943 * bookmarked, and if it is, edit that bookmark. If false, and
1944 * the site is already bookmarked, do not attempt to edit the
1945 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001946 */
1947 @Override
John Reckd3e4d5b2011-07-13 15:48:43 -07001948 public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
John Recka60fffa2011-09-06 16:30:29 -07001949 WebView w = getCurrentTopWebView();
1950 if (w == null) {
1951 return null;
1952 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001953 Intent i = new Intent(mActivity,
1954 AddBookmarkPage.class);
Michael Kolb8233fac2010-10-26 16:08:53 -07001955 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1956 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1957 String touchIconUrl = w.getTouchIconUrl();
1958 if (touchIconUrl != null) {
1959 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1960 WebSettings settings = w.getSettings();
1961 if (settings != null) {
1962 i.putExtra(AddBookmarkPage.USER_AGENT,
1963 settings.getUserAgentString());
1964 }
1965 }
1966 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1967 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1968 getDesiredThumbnailHeight(mActivity)));
1969 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07001970 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001971 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1972 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001973 // Put the dialog at the upper right of the screen, covering the
1974 // star on the title bar.
1975 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07001976 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07001977 }
1978
1979 // file chooser
Ben Murdoch8cad4132012-01-11 10:56:43 +00001980 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001981 mUploadHandler = new UploadHandler(this);
Ben Murdoch8cad4132012-01-11 10:56:43 +00001982 mUploadHandler.openFileChooser(uploadMsg, acceptType, capture);
Michael Kolb8233fac2010-10-26 16:08:53 -07001983 }
1984
1985 // thumbnails
1986
1987 /**
1988 * Return the desired width for thumbnail screenshots, which are stored in
1989 * the database, and used on the bookmarks screen.
1990 * @param context Context for finding out the density of the screen.
1991 * @return desired width for thumbnail screenshot.
1992 */
1993 static int getDesiredThumbnailWidth(Context context) {
1994 return context.getResources().getDimensionPixelOffset(
1995 R.dimen.bookmarkThumbnailWidth);
1996 }
1997
1998 /**
1999 * Return the desired height for thumbnail screenshots, which are stored in
2000 * the database, and used on the bookmarks screen.
2001 * @param context Context for finding out the density of the screen.
2002 * @return desired height for thumbnail screenshot.
2003 */
2004 static int getDesiredThumbnailHeight(Context context) {
2005 return context.getResources().getDimensionPixelOffset(
2006 R.dimen.bookmarkThumbnailHeight);
2007 }
2008
John Reck8cc92352011-07-06 17:41:52 -07002009 static Bitmap createScreenshot(WebView view, int width, int height) {
John Reckd7dd9b22011-08-30 09:18:29 -07002010 if (view == null || view.getContentHeight() == 0
2011 || view.getContentWidth() == 0) {
2012 return null;
2013 }
John Reck5c6ac2f2011-01-05 10:18:03 -08002014 // We render to a bitmap 2x the desired size so that we can then
2015 // re-scale it with filtering since canvas.scale doesn't filter
2016 // This helps reduce aliasing at the cost of being slightly blurry
2017 final int filter_scale = 2;
John Reckd7dd9b22011-08-30 09:18:29 -07002018 int scaledWidth = width * filter_scale;
2019 int scaledHeight = height * filter_scale;
2020 if (sThumbnailBitmap == null || sThumbnailBitmap.getWidth() != scaledWidth
2021 || sThumbnailBitmap.getHeight() != scaledHeight) {
2022 if (sThumbnailBitmap != null) {
2023 sThumbnailBitmap.recycle();
2024 sThumbnailBitmap = null;
2025 }
2026 sThumbnailBitmap =
2027 Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.RGB_565);
Michael Kolb8233fac2010-10-26 16:08:53 -07002028 }
John Reckd7dd9b22011-08-30 09:18:29 -07002029 Canvas canvas = new Canvas(sThumbnailBitmap);
2030 int contentWidth = view.getContentWidth();
2031 float overviewScale = scaledWidth / (view.getScale() * contentWidth);
2032 if (view instanceof BrowserWebView) {
2033 int dy = -((BrowserWebView)view).getTitleHeight();
2034 canvas.translate(0, dy * overviewScale);
2035 }
2036
2037 canvas.scale(overviewScale, overviewScale);
2038
2039 if (view instanceof BrowserWebView) {
2040 ((BrowserWebView)view).drawContent(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07002041 } else {
John Reckd7dd9b22011-08-30 09:18:29 -07002042 view.draw(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07002043 }
John Reckd7dd9b22011-08-30 09:18:29 -07002044 Bitmap ret = Bitmap.createScaledBitmap(sThumbnailBitmap,
2045 width, height, true);
Dianne Hackborn43cfe8a2011-08-02 16:59:35 -07002046 canvas.setBitmap(null);
John Reck5c6ac2f2011-01-05 10:18:03 -08002047 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07002048 }
2049
John Reck34ef2672011-02-10 11:30:55 -08002050 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002051 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07002052 // FIXME: Would like to make sure there is actually something to
2053 // draw, but the API for that (WebViewCore.pictureReady()) is not
2054 // currently accessible here.
2055
John Reck34ef2672011-02-10 11:30:55 -08002056 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08002057 if (view == null) {
2058 // Tab was destroyed
2059 return;
2060 }
John Reck34ef2672011-02-10 11:30:55 -08002061 final String url = tab.getUrl();
2062 final String originalUrl = view.getOriginalUrl();
John Reck34ef2672011-02-10 11:30:55 -08002063 if (TextUtils.isEmpty(url)) {
2064 return;
2065 }
2066
2067 // Only update thumbnails for web urls (http(s)://), not for
2068 // about:, javascript:, data:, etc...
2069 // Unless it is a bookmarked site, then always update
2070 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2071 return;
2072 }
2073
Michael Kolb8233fac2010-10-26 16:08:53 -07002074 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2075 getDesiredThumbnailHeight(mActivity));
2076 if (bm == null) {
2077 return;
2078 }
2079
2080 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002081 new AsyncTask<Void, Void, Void>() {
2082 @Override
2083 protected Void doInBackground(Void... unused) {
2084 Cursor cursor = null;
2085 try {
2086 // TODO: Clean this up
2087 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2088 if (cursor != null && cursor.moveToFirst()) {
2089 final ByteArrayOutputStream os =
2090 new ByteArrayOutputStream();
2091 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002092
John Reck34ef2672011-02-10 11:30:55 -08002093 ContentValues values = new ContentValues();
2094 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002095
John Reck34ef2672011-02-10 11:30:55 -08002096 do {
John Reck617fd832011-02-16 14:35:59 -08002097 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002098 cr.update(Images.CONTENT_URI, values, null, null);
2099 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002100 }
John Reck34ef2672011-02-10 11:30:55 -08002101 } catch (IllegalStateException e) {
2102 // Ignore
2103 } finally {
2104 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002105 }
John Reck34ef2672011-02-10 11:30:55 -08002106 return null;
2107 }
2108 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002109 }
2110
2111 private class Copy implements OnMenuItemClickListener {
2112 private CharSequence mText;
2113
2114 public boolean onMenuItemClick(MenuItem item) {
2115 copy(mText);
2116 return true;
2117 }
2118
2119 public Copy(CharSequence toCopy) {
2120 mText = toCopy;
2121 }
2122 }
2123
Leon Scroggins63c02662010-11-18 15:16:27 -05002124 private static class Download implements OnMenuItemClickListener {
2125 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002126 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002127 private boolean mPrivateBrowsing;
George Mount387d45d2011-10-07 15:57:53 -07002128 private static final String FALLBACK_EXTENSION = "dat";
2129 private static final String IMAGE_BASE_FORMAT = "yyyy-MM-dd-HH-mm-ss-";
Michael Kolb8233fac2010-10-26 16:08:53 -07002130
2131 public boolean onMenuItemClick(MenuItem item) {
George Mount387d45d2011-10-07 15:57:53 -07002132 if (DataUri.isDataUri(mText)) {
2133 saveDataUri();
2134 } else {
2135 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
2136 null, null, mPrivateBrowsing);
2137 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002138 return true;
2139 }
2140
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002141 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002142 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002143 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002144 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002145 }
George Mount387d45d2011-10-07 15:57:53 -07002146
2147 /**
2148 * Treats mText as a data URI and writes its contents to a file
2149 * based on the current time.
2150 */
2151 private void saveDataUri() {
2152 FileOutputStream outputStream = null;
2153 try {
2154 DataUri uri = new DataUri(mText);
2155 File target = getTarget(uri);
2156 outputStream = new FileOutputStream(target);
2157 outputStream.write(uri.getData());
2158 final DownloadManager manager =
2159 (DownloadManager) mActivity.getSystemService(Context.DOWNLOAD_SERVICE);
2160 manager.addCompletedDownload(target.getName(),
2161 mActivity.getTitle().toString(), false,
2162 uri.getMimeType(), target.getAbsolutePath(),
George Mount7501bf42011-11-17 11:17:03 -08002163 (long)uri.getData().length, true);
George Mount387d45d2011-10-07 15:57:53 -07002164 } catch (IOException e) {
2165 Log.e(LOGTAG, "Could not save data URL");
2166 } finally {
2167 if (outputStream != null) {
2168 try {
2169 outputStream.close();
2170 } catch (IOException e) {
2171 // ignore close errors
2172 }
2173 }
2174 }
2175 }
2176
2177 /**
2178 * Creates a File based on the current time stamp and uses
2179 * the mime type of the DataUri to get the extension.
2180 */
2181 private File getTarget(DataUri uri) throws IOException {
2182 File dir = mActivity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
2183 DateFormat format = new SimpleDateFormat(IMAGE_BASE_FORMAT);
2184 String nameBase = format.format(new Date());
2185 String mimeType = uri.getMimeType();
2186 MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
2187 String extension = mimeTypeMap.getExtensionFromMimeType(mimeType);
2188 if (extension == null) {
2189 Log.w(LOGTAG, "Unknown mime type in data URI" + mimeType);
2190 extension = FALLBACK_EXTENSION;
2191 }
2192 extension = "." + extension; // createTempFile needs the '.'
2193 File targetFile = File.createTempFile(nameBase, extension, dir);
2194 return targetFile;
2195 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002196 }
2197
Cary Clark8974d282010-11-22 10:46:05 -05002198 private static class SelectText implements OnMenuItemClickListener {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002199 private WebViewClassic mWebView;
Cary Clark8974d282010-11-22 10:46:05 -05002200
2201 public boolean onMenuItemClick(MenuItem item) {
2202 if (mWebView != null) {
2203 return mWebView.selectText();
2204 }
2205 return false;
2206 }
2207
2208 public SelectText(WebView webView) {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002209 mWebView = WebViewClassic.fromWebView(webView);
Cary Clark8974d282010-11-22 10:46:05 -05002210 }
2211
2212 }
2213
Michael Kolb8233fac2010-10-26 16:08:53 -07002214 /********************** TODO: UI stuff *****************************/
2215
2216 // these methods have been copied, they still need to be cleaned up
2217
2218 /****************** tabs ***************************************************/
2219
2220 // basic tab interactions:
2221
2222 // it is assumed that tabcontrol already knows about the tab
2223 protected void addTab(Tab tab) {
2224 mUi.addTab(tab);
2225 }
2226
2227 protected void removeTab(Tab tab) {
2228 mUi.removeTab(tab);
2229 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002230 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002231 }
2232
Michael Kolbf2055602011-04-09 17:20:03 -07002233 @Override
2234 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002235 // monkey protection against delayed start
2236 if (tab != null) {
2237 mTabControl.setCurrentTab(tab);
2238 // the tab is guaranteed to have a webview after setCurrentTab
2239 mUi.setActiveTab(tab);
2240 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002241 }
2242
John Reck8bcafc12011-08-29 16:43:02 -07002243 protected void closeEmptyTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002244 Tab current = mTabControl.getCurrentTab();
2245 if (current != null
2246 && current.getWebView().copyBackForwardList().getSize() == 0) {
John Reck8bcafc12011-08-29 16:43:02 -07002247 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002248 }
2249 }
2250
John Reck26b18322011-06-21 13:08:58 -07002251 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002252 // Dismiss the subwindow if applicable.
2253 dismissSubWindow(appTab);
2254 // Since we might kill the WebView, remove it from the
2255 // content view first.
2256 mUi.detachTab(appTab);
2257 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002258 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002259 // TODO: analyze why the remove and add are necessary
2260 mUi.attachTab(appTab);
2261 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002262 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002263 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002264 } else {
2265 // If the tab was the current tab, we have to attach
2266 // it to the view system again.
2267 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002268 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002269 }
2270 }
2271
2272 // Remove the sub window if it exists. Also called by TabControl when the
2273 // user clicks the 'X' to dismiss a sub window.
2274 public void dismissSubWindow(Tab tab) {
2275 removeSubWindow(tab);
2276 // dismiss the subwindow. This will destroy the WebView.
2277 tab.dismissSubWindow();
Michael Kolbe8c97572011-11-21 14:03:56 -08002278 WebView wv = getCurrentTopWebView();
2279 if (wv != null) {
2280 wv.requestFocus();
2281 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002282 }
2283
2284 @Override
2285 public void removeSubWindow(Tab t) {
2286 if (t.getSubWebView() != null) {
2287 mUi.removeSubWindow(t.getSubViewContainer());
2288 }
2289 }
2290
2291 @Override
2292 public void attachSubWindow(Tab tab) {
2293 if (tab.getSubWebView() != null) {
2294 mUi.attachSubWindow(tab.getSubViewContainer());
2295 getCurrentTopWebView().requestFocus();
2296 }
2297 }
2298
Mathew Inwood29721c22011-06-29 17:55:24 +01002299 private Tab showPreloadedTab(final UrlData urlData) {
2300 if (!urlData.isPreloaded()) {
2301 return null;
2302 }
2303 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2304 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2305 if (sbQuery != null) {
Mathew Inwood9ad1eac2011-09-15 11:29:50 +01002306 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002307 // Could not submit query. Fallback to regular tab creation
2308 tabControl.destroy();
2309 return null;
2310 }
2311 }
Michael Kolbff6a7482011-07-26 16:37:15 -07002312 // check tab count and make room for new tab
2313 if (!mTabControl.canCreateNewTab()) {
2314 Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
2315 if (leastUsed != null) {
2316 closeTab(leastUsed);
2317 }
2318 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002319 Tab t = tabControl.getTab();
Mathew Inwoode09305e2011-09-02 12:03:26 +01002320 t.refreshIdAfterPreload();
Mathew Inwood29721c22011-06-29 17:55:24 +01002321 mTabControl.addPreloadedTab(t);
2322 addTab(t);
2323 setActiveTab(t);
2324 return t;
2325 }
2326
Michael Kolb7bcafde2011-05-09 13:55:59 -07002327 // open a non inconito tab with the given url data
2328 // and set as active tab
2329 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002330 Tab tab = showPreloadedTab(urlData);
2331 if (tab == null) {
2332 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002333 if ((tab != null) && !urlData.isEmpty()) {
2334 loadUrlDataIn(tab, urlData);
2335 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002336 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002337 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002338 }
2339
Michael Kolb843510f2010-12-09 10:51:49 -08002340 @Override
2341 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002342 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002343 }
2344
Michael Kolb8233fac2010-10-26 16:08:53 -07002345 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002346 public Tab openIncognitoTab() {
2347 return openTab(INCOGNITO_URI, true, true, false);
2348 }
2349
2350 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002351 public Tab openTab(String url, boolean incognito, boolean setActive,
2352 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002353 return openTab(url, incognito, setActive, useCurrent, null);
2354 }
2355
2356 @Override
2357 public Tab openTab(String url, Tab parent, boolean setActive,
2358 boolean useCurrent) {
2359 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2360 setActive, useCurrent, parent);
2361 }
2362
2363 public Tab openTab(String url, boolean incognito, boolean setActive,
2364 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002365 Tab tab = createNewTab(incognito, setActive, useCurrent);
2366 if (tab != null) {
John Reck5949c662011-05-27 09:52:29 -07002367 if (parent != null && parent != tab) {
2368 parent.addChildTab(tab);
2369 }
Michael Kolb519d2282011-05-09 17:03:19 -07002370 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002371 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002372 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002373 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002374 return tab;
2375 }
2376
2377 // this method will attempt to create a new tab
2378 // incognito: private browsing tab
2379 // setActive: ste tab as current tab
2380 // useCurrent: if no new tab can be created, return current tab
2381 private Tab createNewTab(boolean incognito, boolean setActive,
2382 boolean useCurrent) {
2383 Tab tab = null;
2384 if (mTabControl.canCreateNewTab()) {
2385 tab = mTabControl.createNewTab(incognito);
2386 addTab(tab);
2387 if (setActive) {
2388 setActiveTab(tab);
2389 }
2390 } else {
2391 if (useCurrent) {
2392 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002393 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002394 } else {
2395 mUi.showMaxTabsWarning();
2396 }
2397 }
2398 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002399 }
2400
John Reck2bc80422011-06-30 15:11:49 -07002401 @Override
2402 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2403 SnapshotTab tab = null;
2404 if (mTabControl.canCreateNewTab()) {
2405 tab = mTabControl.createSnapshotTab(snapshotId);
2406 addTab(tab);
2407 if (setActive) {
2408 setActiveTab(tab);
2409 }
2410 } else {
2411 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07002412 }
2413 return tab;
2414 }
2415
Michael Kolb8233fac2010-10-26 16:08:53 -07002416 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002417 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002418 * @return boolean True if we successfully switched to a different tab. If
2419 * the indexth tab is null, or if that tab is the same as
2420 * the current one, return false.
2421 */
2422 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002423 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002424 Tab currentTab = mTabControl.getCurrentTab();
2425 if (tab == null || tab == currentTab) {
2426 return false;
2427 }
2428 setActiveTab(tab);
2429 return true;
2430 }
2431
2432 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002433 public void closeCurrentTab() {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002434 closeCurrentTab(false);
2435 }
2436
2437 protected void closeCurrentTab(boolean andQuit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002438 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07002439 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07002440 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08002441 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002442 return;
2443 }
Michael Kolbc831b632011-05-11 09:30:34 -07002444 final Tab current = mTabControl.getCurrentTab();
2445 final int pos = mTabControl.getCurrentPosition();
2446 Tab newTab = current.getParent();
2447 if (newTab == null) {
2448 newTab = mTabControl.getTab(pos + 1);
2449 if (newTab == null) {
2450 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002451 }
2452 }
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002453 if (andQuit) {
2454 mTabControl.setCurrentTab(newTab);
2455 closeTab(current);
2456 } else if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002457 // Close window
2458 closeTab(current);
2459 }
2460 }
2461
2462 /**
2463 * Close the tab, remove its associated title bar, and adjust mTabControl's
2464 * current tab to a valid value.
2465 */
2466 @Override
2467 public void closeTab(Tab tab) {
John Reck28263772011-10-11 17:13:42 -07002468 if (tab == mTabControl.getCurrentTab()) {
2469 closeCurrentTab();
2470 } else {
2471 removeTab(tab);
2472 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002473 }
2474
Michael Kolb8233fac2010-10-26 16:08:53 -07002475 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07002476 protected void loadUrlFromContext(String url) {
2477 Tab tab = getCurrentTab();
2478 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002479 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07002480 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002481 url = UrlUtils.smartUrlFilter(url);
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002482 if (!WebViewClassic.fromWebView(view).getWebViewClient().
2483 shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07002484 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07002485 }
2486 }
2487 }
2488
2489 /**
2490 * Load the URL into the given WebView and update the title bar
2491 * to reflect the new load. Call this instead of WebView.loadUrl
2492 * directly.
2493 * @param view The WebView used to load url.
2494 * @param url The URL to load.
2495 */
John Reck71e51422011-07-01 16:49:28 -07002496 @Override
2497 public void loadUrl(Tab tab, String url) {
John Reck26b18322011-06-21 13:08:58 -07002498 loadUrl(tab, url, null);
2499 }
2500
2501 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
2502 if (tab != null) {
2503 dismissSubWindow(tab);
2504 tab.loadUrl(url, headers);
Michael Kolba53c9892011-10-05 13:31:40 -07002505 mUi.onProgressChanged(tab);
John Reck26b18322011-06-21 13:08:58 -07002506 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002507 }
2508
2509 /**
2510 * Load UrlData into a Tab and update the title bar to reflect the new
2511 * load. Call this instead of UrlData.loadIn directly.
2512 * @param t The Tab used to load.
2513 * @param data The UrlData being loaded.
2514 */
2515 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07002516 if (data != null) {
Michael Kolb5ff5c8b2012-05-03 11:37:58 -07002517 if (data.isPreloaded()) {
Michael Kolb14612442011-06-24 13:06:29 -07002518 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07002519 } else {
2520 loadUrl(t, data.mUrl, data.mHeaders);
2521 }
2522 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002523 }
2524
John Reck30c714c2010-12-16 17:30:34 -08002525 @Override
2526 public void onUserCanceledSsl(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08002527 // TODO: Figure out the "right" behavior
John Reckef654f12011-07-12 16:42:08 -07002528 if (tab.canGoBack()) {
2529 tab.goBack();
John Reck30c714c2010-12-16 17:30:34 -08002530 } else {
John Reckef654f12011-07-12 16:42:08 -07002531 tab.loadUrl(mSettings.getHomePage(), null);
John Reck30c714c2010-12-16 17:30:34 -08002532 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002533 }
2534
2535 void goBackOnePageOrQuit() {
2536 Tab current = mTabControl.getCurrentTab();
2537 if (current == null) {
2538 /*
2539 * Instead of finishing the activity, simply push this to the back
2540 * of the stack and let ActivityManager to choose the foreground
2541 * activity. As BrowserActivity is singleTask, it will be always the
2542 * root of the task. So we can use either true or false for
2543 * moveTaskToBack().
2544 */
2545 mActivity.moveTaskToBack(true);
2546 return;
2547 }
John Reckef654f12011-07-12 16:42:08 -07002548 if (current.canGoBack()) {
2549 current.goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07002550 } else {
2551 // Check to see if we are closing a window that was created by
2552 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002553 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002554 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002555 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002556 // Now we close the other tab
2557 closeTab(current);
2558 } else {
Michael Kolbe28b3472011-08-04 16:54:31 -07002559 if ((current.getAppId() != null) || current.closeOnBack()) {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002560 closeCurrentTab(true);
Michael Kolbe28b3472011-08-04 16:54:31 -07002561 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002562 /*
2563 * Instead of finishing the activity, simply push this to the back
2564 * of the stack and let ActivityManager to choose the foreground
2565 * activity. As BrowserActivity is singleTask, it will be always the
2566 * root of the task. So we can use either true or false for
2567 * moveTaskToBack().
2568 */
2569 mActivity.moveTaskToBack(true);
2570 }
2571 }
2572 }
2573
2574 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002575 * helper method for key handler
2576 * returns the current tab if it can't advance
2577 */
Michael Kolbc831b632011-05-11 09:30:34 -07002578 private Tab getNextTab() {
Michael Kolbf5261da2011-12-15 15:07:35 -08002579 int pos = mTabControl.getCurrentPosition() + 1;
2580 if (pos >= mTabControl.getTabCount()) {
2581 pos = 0;
2582 }
2583 return mTabControl.getTab(pos);
Michael Kolb0035fad2011-03-14 13:25:28 -07002584 }
2585
2586 /**
2587 * helper method for key handler
2588 * returns the current tab if it can't advance
2589 */
Michael Kolbc831b632011-05-11 09:30:34 -07002590 private Tab getPrevTab() {
Michael Kolbf5261da2011-12-15 15:07:35 -08002591 int pos = mTabControl.getCurrentPosition() - 1;
2592 if ( pos < 0) {
2593 pos = mTabControl.getTabCount() - 1;
2594 }
2595 return mTabControl.getTab(pos);
Michael Kolb0035fad2011-03-14 13:25:28 -07002596 }
2597
John Reckbcef87f2012-02-03 14:58:34 -08002598 boolean isMenuOrCtrlKey(int keyCode) {
2599 return (KeyEvent.KEYCODE_MENU == keyCode)
2600 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2601 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode);
2602 }
2603
Michael Kolb0035fad2011-03-14 13:25:28 -07002604 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002605 * handle key events in browser
2606 *
2607 * @param keyCode
2608 * @param event
2609 * @return true if handled, false to pass to super
2610 */
2611 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002612 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002613 // Even if MENU is already held down, we need to call to super to open
2614 // the IME on long press.
John Reckbcef87f2012-02-03 14:58:34 -08002615 if (!noModifiers && isMenuOrCtrlKey(keyCode)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002616 mMenuIsDown = true;
2617 return false;
2618 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002619
Cary Clark8ff8c662010-12-29 15:03:05 -05002620 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07002621 Tab tab = getCurrentTab();
2622 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05002623
Cary Clark160bbb92011-01-10 11:17:07 -05002624 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2625 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002626
Michael Kolb8233fac2010-10-26 16:08:53 -07002627 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002628 case KeyEvent.KEYCODE_TAB:
2629 if (event.isCtrlPressed()) {
2630 if (event.isShiftPressed()) {
2631 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002632 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002633 } else {
2634 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002635 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002636 }
2637 return true;
2638 }
2639 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002640 case KeyEvent.KEYCODE_SPACE:
2641 // WebView/WebTextView handle the keys in the KeyDown. As
2642 // the Activity's shortcut keys are only handled when WebView
2643 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002644 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002645 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002646 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002647 pageDown();
2648 }
2649 return true;
2650 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002651 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002652 event.startTracking();
2653 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07002654 case KeyEvent.KEYCODE_FORWARD:
2655 if (!noModifiers) break;
2656 tab.goForward();
2657 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002658 case KeyEvent.KEYCODE_DPAD_LEFT:
2659 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002660 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05002661 return true;
2662 }
2663 break;
2664 case KeyEvent.KEYCODE_DPAD_RIGHT:
2665 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002666 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05002667 return true;
2668 }
2669 break;
2670 case KeyEvent.KEYCODE_A:
2671 if (ctrl) {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002672 WebViewClassic.fromWebView(webView).selectAll();
Cary Clark8ff8c662010-12-29 15:03:05 -05002673 return true;
2674 }
2675 break;
Michael Kolba4183062011-01-16 10:43:21 -08002676// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002677 case KeyEvent.KEYCODE_C:
2678 if (ctrl) {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002679 WebViewClassic.fromWebView(webView).copySelection();
Cary Clark8ff8c662010-12-29 15:03:05 -05002680 return true;
2681 }
2682 break;
Michael Kolba4183062011-01-16 10:43:21 -08002683// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002684// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002685// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002686// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002687// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002688// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002689// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002690// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002691// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002692// case KeyEvent.KEYCODE_M: // unused
2693// case KeyEvent.KEYCODE_N: // in Chrome: new window
2694// case KeyEvent.KEYCODE_O: // in Chrome: open file
2695// case KeyEvent.KEYCODE_P: // in Chrome: print page
2696// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002697// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002698// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2699 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002700 // we can't use the ctrl/shift flags, they check for
2701 // exclusive use of a modifier
2702 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002703 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002704 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002705 } else {
2706 openTabToHomePage();
2707 }
2708 return true;
2709 }
2710 break;
2711// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2712// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb5ae15bd2011-08-16 17:09:27 -07002713// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002714// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2715// case KeyEvent.KEYCODE_Y: // unused
2716// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002717 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002718 // it is a regular key and webview is not null
2719 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002720 }
2721
John Recke6bf4ab2011-02-24 15:48:05 -08002722 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2723 switch(keyCode) {
2724 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07002725 if (mUi.isWebShowing()) {
Michael Kolb315d5022011-10-13 12:47:11 -07002726 bookmarksOrHistoryPicker(ComboViews.History);
John Recke6bf4ab2011-02-24 15:48:05 -08002727 return true;
2728 }
2729 break;
2730 }
2731 return false;
2732 }
2733
Michael Kolb8233fac2010-10-26 16:08:53 -07002734 boolean onKeyUp(int keyCode, KeyEvent event) {
John Reckbcef87f2012-02-03 14:58:34 -08002735 if (isMenuOrCtrlKey(keyCode)) {
Michael Kolb2814a362011-05-19 15:49:41 -07002736 mMenuIsDown = false;
John Reckbcef87f2012-02-03 14:58:34 -08002737 if (KeyEvent.KEYCODE_MENU == keyCode
2738 && event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002739 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002740 }
2741 }
Cary Clark160bbb92011-01-10 11:17:07 -05002742 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002743 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002744 case KeyEvent.KEYCODE_BACK:
2745 if (event.isTracking() && !event.isCanceled()) {
2746 onBackKey();
2747 return true;
2748 }
2749 break;
2750 }
2751 return false;
2752 }
2753
2754 public boolean isMenuDown() {
2755 return mMenuIsDown;
2756 }
2757
Ben Murdoch8029a772010-11-16 11:58:21 +00002758 public void setupAutoFill(Message message) {
2759 // Open the settings activity at the AutoFill profile fragment so that
2760 // the user can create a new profile. When they return, we will dispatch
2761 // the message so that we can autofill the form using their new profile.
2762 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2763 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2764 AutoFillSettingsFragment.class.getName());
2765 mAutoFillSetupMessage = message;
2766 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2767 }
John Reckb3417f02011-01-14 11:01:05 -08002768
Michael Kolbfbc579a2011-07-07 15:59:33 -07002769 public boolean onSearchRequested() {
Michael Kolb1f9b3562012-04-24 14:38:34 -07002770 mUi.editUrl(false, true);
Michael Kolbfbc579a2011-07-07 15:59:33 -07002771 return true;
2772 }
2773
John Reck1cf4b792011-07-26 10:22:22 -07002774 @Override
2775 public boolean shouldCaptureThumbnails() {
2776 return mUi.shouldCaptureThumbnails();
2777 }
2778
Michael Kolbc3af0672011-08-09 10:24:41 -07002779 @Override
2780 public void setBlockEvents(boolean block) {
2781 mBlockEvents = block;
2782 }
2783
2784 public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002785 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002786 }
2787
2788 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002789 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002790 }
2791
2792 public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002793 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002794 }
2795
2796 public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002797 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002798 }
2799
2800 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002801 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002802 }
2803
Michael Kolb8233fac2010-10-26 16:08:53 -07002804}