blob: 493583d4d45f7f819b79be6aead4702a345497f8 [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
Michael Kolbaf63dba2012-05-16 12:58:05 -0700432 @Override
433 public BrowserSettings getSettings() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700434 return mSettings;
435 }
436
437 IntentHandler getIntentHandler() {
438 return mIntentHandler;
439 }
440
441 @Override
442 public UI getUi() {
443 return mUi;
444 }
445
446 int getMaxTabs() {
447 return mActivity.getResources().getInteger(R.integer.max_tabs);
448 }
449
450 @Override
451 public TabControl getTabControl() {
452 return mTabControl;
453 }
454
Michael Kolb1bf23132010-11-19 12:55:12 -0800455 @Override
456 public List<Tab> getTabs() {
457 return mTabControl.getTabs();
458 }
459
John Reckaf262e72011-07-25 13:55:44 -0700460 // Open the icon database.
461 private void openIconDatabase() {
462 // We have to call getInstance on the UI thread
463 final WebIconDatabase instance = WebIconDatabase.getInstance();
464 BackgroundHandler.execute(new Runnable() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000465
John Reckaf262e72011-07-25 13:55:44 -0700466 @Override
467 public void run() {
468 instance.open(mActivity.getDir("icons", 0).getPath());
Michael Kolb8233fac2010-10-26 16:08:53 -0700469 }
John Reckaf262e72011-07-25 13:55:44 -0700470 });
Michael Kolb8233fac2010-10-26 16:08:53 -0700471 }
472
473 private void startHandler() {
474 mHandler = new Handler() {
475
476 @Override
477 public void handleMessage(Message msg) {
478 switch (msg.what) {
479 case OPEN_BOOKMARKS:
Michael Kolb315d5022011-10-13 12:47:11 -0700480 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
Michael Kolb8233fac2010-10-26 16:08:53 -0700481 break;
482 case FOCUS_NODE_HREF:
483 {
484 String url = (String) msg.getData().get("url");
485 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500486 String src = (String) msg.getData().get("src");
487 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700488 if (TextUtils.isEmpty(url)) {
489 break;
490 }
491 HashMap focusNodeMap = (HashMap) msg.obj;
492 WebView view = (WebView) focusNodeMap.get("webview");
493 // Only apply the action if the top window did not change.
494 if (getCurrentTopWebView() != view) {
495 break;
496 }
497 switch (msg.arg1) {
498 case R.id.open_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700499 loadUrlFromContext(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700500 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500501 case R.id.view_image_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700502 loadUrlFromContext(src);
Cary Clark043c2d62010-12-15 11:19:39 -0500503 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500504 case R.id.open_newtab_context_menu_id:
505 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -0700506 openTab(url, parent,
507 !mSettings.openInBackground(), true);
Leon Scroggins026f2542010-11-22 13:26:12 -0500508 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700509 case R.id.copy_link_context_menu_id:
510 copy(url);
511 break;
512 case R.id.save_link_context_menu_id:
513 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500514 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000515 mActivity, url, null, null, null,
516 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700517 break;
518 }
519 break;
520 }
521
522 case LOAD_URL:
John Reck26b18322011-06-21 13:08:58 -0700523 loadUrlFromContext((String) msg.obj);
Michael Kolb8233fac2010-10-26 16:08:53 -0700524 break;
525
526 case STOP_LOAD:
527 stopLoading();
528 break;
529
530 case RELEASE_WAKELOCK:
John Reckf57c0292011-07-21 18:15:39 -0700531 if (mWakeLock != null && mWakeLock.isHeld()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700532 mWakeLock.release();
533 // if we reach here, Browser should be still in the
534 // background loading after WAKELOCK_TIMEOUT (5-min).
535 // To avoid burning the battery, stop loading.
536 mTabControl.stopAllLoading();
537 }
538 break;
539
540 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800541 Tab tab = (Tab) msg.obj;
542 if (tab != null) {
543 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700544 }
545 break;
546 }
547 }
548 };
549
550 }
551
John Reckef654f12011-07-12 16:42:08 -0700552 @Override
Martijn Coenenb2f93552011-06-14 10:48:35 +0200553 public Tab getCurrentTab() {
554 return mTabControl.getCurrentTab();
555 }
556
Michael Kolbba99c5d2010-11-29 14:57:41 -0800557 @Override
558 public void shareCurrentPage() {
559 shareCurrentPage(mTabControl.getCurrentTab());
560 }
561
562 private void shareCurrentPage(Tab tab) {
563 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800564 sharePage(mActivity, tab.getTitle(),
565 tab.getUrl(), tab.getFavicon(),
566 createScreenshot(tab.getWebView(),
567 getDesiredThumbnailWidth(mActivity),
568 getDesiredThumbnailHeight(mActivity)));
569 }
570 }
571
Michael Kolb8233fac2010-10-26 16:08:53 -0700572 /**
573 * Share a page, providing the title, url, favicon, and a screenshot. Uses
574 * an {@link Intent} to launch the Activity chooser.
575 * @param c Context used to launch a new Activity.
576 * @param title Title of the page. Stored in the Intent with
577 * {@link Intent#EXTRA_SUBJECT}
578 * @param url URL of the page. Stored in the Intent with
579 * {@link Intent#EXTRA_TEXT}
580 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
581 * with {@link Browser#EXTRA_SHARE_FAVICON}
582 * @param screenshot Bitmap of a screenshot of the page. Stored in the
583 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
584 */
585 static final void sharePage(Context c, String title, String url,
586 Bitmap favicon, Bitmap screenshot) {
587 Intent send = new Intent(Intent.ACTION_SEND);
588 send.setType("text/plain");
589 send.putExtra(Intent.EXTRA_TEXT, url);
590 send.putExtra(Intent.EXTRA_SUBJECT, title);
591 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
592 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
593 try {
594 c.startActivity(Intent.createChooser(send, c.getString(
595 R.string.choosertitle_sharevia)));
596 } catch(android.content.ActivityNotFoundException ex) {
597 // if no app handles it, do nothing
598 }
599 }
600
601 private void copy(CharSequence text) {
602 ClipboardManager cm = (ClipboardManager) mActivity
603 .getSystemService(Context.CLIPBOARD_SERVICE);
604 cm.setText(text);
605 }
606
607 // lifecycle
608
609 protected void onConfgurationChanged(Configuration config) {
610 mConfigChanged = true;
Michael Kolb18f252f2012-03-06 13:36:20 -0800611 // update the menu in case of a locale change
612 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -0700613 if (mPageDialogsHandler != null) {
614 mPageDialogsHandler.onConfigurationChanged(config);
615 }
616 mUi.onConfigurationChanged(config);
617 }
618
619 @Override
620 public void handleNewIntent(Intent intent) {
Michael Kolb59e232c2011-08-18 17:19:53 -0700621 if (!mUi.isWebShowing()) {
622 mUi.showWeb(false);
623 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700624 mIntentHandler.onNewIntent(intent);
625 }
626
627 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800628 if (mUi.isCustomViewShowing()) {
629 hideCustomView();
630 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700631 if (mActivityPaused) {
632 Log.e(LOGTAG, "BrowserActivity is already paused.");
633 return;
634 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700635 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800636 Tab tab = mTabControl.getCurrentTab();
637 if (tab != null) {
638 tab.pause();
639 if (!pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700640 if (mWakeLock == null) {
641 PowerManager pm = (PowerManager) mActivity
642 .getSystemService(Context.POWER_SERVICE);
643 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
644 }
Michael Kolb70976932010-11-30 11:34:01 -0800645 mWakeLock.acquire();
646 mHandler.sendMessageDelayed(mHandler
647 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
648 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700649 }
650 mUi.onPause();
651 mNetworkHandler.onPause();
652
653 WebView.disablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100654 NfcHandler.unregister(mActivity);
John Reckd7dd9b22011-08-30 09:18:29 -0700655 if (sThumbnailBitmap != null) {
656 sThumbnailBitmap.recycle();
657 sThumbnailBitmap = null;
658 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700659 }
660
John Reck1cf4b792011-07-26 10:22:22 -0700661 void onSaveInstanceState(Bundle outState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700662 // Save all the tabs
George Mount3636d0a2011-11-21 09:08:21 -0800663 Bundle saveState = createSaveState();
664
665 // crash recovery manages all save & restore state
666 mCrashRecoveryHandler.writeState(saveState);
667 mSettings.setLastRunPaused(true);
668 }
669
670 /**
671 * Save the current state to outState. Does not write the state to
672 * disk.
673 * @return Bundle containing the current state of all tabs.
674 */
675 /* package */ Bundle createSaveState() {
676 Bundle saveState = new Bundle();
677 mTabControl.saveState(saveState);
678 if (!saveState.isEmpty()) {
John Reck24f18262011-06-17 14:47:20 -0700679 // Save time so that we know how old incognito tabs (if any) are.
George Mount3636d0a2011-11-21 09:08:21 -0800680 saveState.putSerializable("lastActiveDate", Calendar.getInstance());
John Reck24f18262011-06-17 14:47:20 -0700681 }
George Mount3636d0a2011-11-21 09:08:21 -0800682 return saveState;
Michael Kolb8233fac2010-10-26 16:08:53 -0700683 }
684
685 void onResume() {
686 if (!mActivityPaused) {
687 Log.e(LOGTAG, "BrowserActivity is already resumed.");
688 return;
689 }
George Mount3636d0a2011-11-21 09:08:21 -0800690 mSettings.setLastRunPaused(false);
Michael Kolb8233fac2010-10-26 16:08:53 -0700691 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800692 Tab current = mTabControl.getCurrentTab();
693 if (current != null) {
694 current.resume();
695 resumeWebViewTimers(current);
696 }
John Reckf57c0292011-07-21 18:15:39 -0700697 releaseWakeLock();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200698
Michael Kolb8233fac2010-10-26 16:08:53 -0700699 mUi.onResume();
700 mNetworkHandler.onResume();
701 WebView.enablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100702 NfcHandler.register(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700703 }
704
John Reckf57c0292011-07-21 18:15:39 -0700705 private void releaseWakeLock() {
706 if (mWakeLock != null && mWakeLock.isHeld()) {
707 mHandler.removeMessages(RELEASE_WAKELOCK);
708 mWakeLock.release();
709 }
710 }
711
Michael Kolb70976932010-11-30 11:34:01 -0800712 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800713 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800714 * @param tab guaranteed non-null
715 */
716 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700717 boolean inLoad = tab.inPageLoad();
718 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
719 CookieSyncManager.getInstance().startSync();
720 WebView w = tab.getWebView();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100721 WebViewTimersControl.getInstance().onBrowserActivityResume(w);
Michael Kolb8233fac2010-10-26 16:08:53 -0700722 }
723 }
724
Michael Kolb70976932010-11-30 11:34:01 -0800725 /**
726 * Pause all WebView timers using the WebView of the given tab
727 * @param tab
728 * @return true if the timers are paused or tab is null
729 */
730 private boolean pauseWebViewTimers(Tab tab) {
731 if (tab == null) {
732 return true;
733 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700734 CookieSyncManager.getInstance().stopSync();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100735 WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView());
Michael Kolb8233fac2010-10-26 16:08:53 -0700736 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700737 }
Michael Kolb70976932010-11-30 11:34:01 -0800738 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700739 }
740
741 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800742 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700743 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
744 mUploadHandler = null;
745 }
746 if (mTabControl == null) return;
747 mUi.onDestroy();
748 // Remove the current tab and sub window
749 Tab t = mTabControl.getCurrentTab();
750 if (t != null) {
751 dismissSubWindow(t);
752 removeTab(t);
753 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500754 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700755 // Destroy all the tabs
756 mTabControl.destroy();
757 WebIconDatabase.getInstance().close();
758 // Stop watching the default geolocation permissions
759 mSystemAllowGeolocationOrigins.stop();
760 mSystemAllowGeolocationOrigins = null;
761 }
762
763 protected boolean isActivityPaused() {
764 return mActivityPaused;
765 }
766
767 protected void onLowMemory() {
768 mTabControl.freeMemory();
769 }
770
771 @Override
772 public boolean shouldShowErrorConsole() {
773 return mShouldShowErrorConsole;
774 }
775
776 protected void setShouldShowErrorConsole(boolean show) {
777 if (show == mShouldShowErrorConsole) {
778 // Nothing to do.
779 return;
780 }
781 mShouldShowErrorConsole = show;
782 Tab t = mTabControl.getCurrentTab();
783 if (t == null) {
784 // There is no current tab so we cannot toggle the error console
785 return;
786 }
787 mUi.setShouldShowErrorConsole(t, show);
788 }
789
790 @Override
791 public void stopLoading() {
792 mLoadStopped = true;
793 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700794 WebView w = getCurrentTopWebView();
Michael Kolb778a4882012-04-12 15:27:28 -0700795 if (w != null) {
796 w.stopLoading();
797 mUi.onPageStopped(tab);
798 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700799 }
800
801 boolean didUserStopLoading() {
802 return mLoadStopped;
803 }
804
805 // WebViewController
806
807 @Override
John Reck324d4402011-01-11 16:56:42 -0800808 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700809
810 // We've started to load a new page. If there was a pending message
811 // to save a screenshot then we will now take the new page and save
812 // an incorrect screenshot. Therefore, remove any pending thumbnail
813 // messages from the queue.
814 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800815 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700816
817 // reset sync timer to avoid sync starts during loading a page
818 CookieSyncManager.getInstance().resetSync();
819
820 if (!mNetworkHandler.isNetworkUp()) {
821 view.setNetworkAvailable(false);
822 }
823
824 // when BrowserActivity just starts, onPageStarted may be called before
825 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
826 // to start the timer. As we won't switch tabs while an activity is in
827 // pause state, we can ensure calling resume and pause in pair.
828 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800829 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700830 }
831 mLoadStopped = false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700832 endActionMode();
833
John Reck30c714c2010-12-16 17:30:34 -0800834 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700835
John Reck324d4402011-01-11 16:56:42 -0800836 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700837 // update the bookmark database for favicon
838 maybeUpdateFavicon(tab, null, url, favicon);
839
840 Performance.tracePageStart(url);
841
842 // Performance probe
843 if (false) {
844 Performance.onPageStarted();
845 }
846
847 }
848
849 @Override
John Reck324d4402011-01-11 16:56:42 -0800850 public void onPageFinished(Tab tab) {
Michael Kolb72864272012-05-03 15:42:15 -0700851 mCrashRecoveryHandler.backupState();
John Reck30c714c2010-12-16 17:30:34 -0800852 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700853 // pause the WebView timer and release the wake lock if it is finished
854 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800855 if (mActivityPaused && pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700856 releaseWakeLock();
Michael Kolb8233fac2010-10-26 16:08:53 -0700857 }
Martijn Coenenb2f93552011-06-14 10:48:35 +0200858
Michael Kolb8233fac2010-10-26 16:08:53 -0700859 // Performance probe
860 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800861 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700862 }
863
864 Performance.tracePageFinished();
865 }
866
867 @Override
John Reck30c714c2010-12-16 17:30:34 -0800868 public void onProgressChanged(Tab tab) {
869 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700870
871 if (newProgress == 100) {
872 CookieSyncManager.getInstance().sync();
873 // onProgressChanged() may continue to be called after the main
874 // frame has finished loading, as any remaining sub frames continue
875 // to load. We'll only get called once though with newProgress as
876 // 100 when everything is loaded. (onPageFinished is called once
877 // when the main frame completes loading regardless of the state of
878 // any sub frames so calls to onProgressChanges may continue after
879 // onPageFinished has executed)
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800880 if (tab.inPageLoad()) {
881 updateInLoadMenuItems(mCachedMenu, tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700882 }
John Reckd9862372012-02-21 15:04:50 -0800883 if (!tab.isPrivateBrowsingEnabled()
884 && !TextUtils.isEmpty(tab.getUrl())
885 && !tab.isSnapshot()) {
886 // Only update the bookmark screenshot if the user did not
887 // cancel the load early and there is not already
888 // a pending update for the tab.
Michael Kolb72864272012-05-03 15:42:15 -0700889 if (tab.shouldUpdateThumbnail() &&
890 (tab.inForeground() && !didUserStopLoading()
891 || !tab.inForeground())) {
John Reckd9862372012-02-21 15:04:50 -0800892 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
893 mHandler.sendMessageDelayed(mHandler.obtainMessage(
894 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
895 500);
896 }
897 }
898 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700899 } else {
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800900 if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700901 // onPageFinished may have already been called but a subframe is
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800902 // still loading
903 // updating the progress and
Michael Kolb8233fac2010-10-26 16:08:53 -0700904 // update the menu items.
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800905 updateInLoadMenuItems(mCachedMenu, tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700906 }
907 }
John Reck30c714c2010-12-16 17:30:34 -0800908 mUi.onProgressChanged(tab);
909 }
910
911 @Override
Steve Block2466eff2011-10-03 15:33:09 +0100912 public void onUpdatedSecurityState(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800913 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700914 }
915
916 @Override
917 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800918 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800919 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800920 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700921 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
922 return;
923 }
924 // Update the title in the history database if not in private browsing mode
925 if (!tab.isPrivateBrowsingEnabled()) {
John Reckf57c0292011-07-21 18:15:39 -0700926 DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700927 }
928 }
929
930 @Override
931 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800932 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700933 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
934 }
935
936 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800937 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
938 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700939 }
940
941 @Override
942 public boolean shouldOverrideKeyEvent(KeyEvent event) {
943 if (mMenuIsDown) {
944 // only check shortcut key when MENU is held
945 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
946 event);
947 } else {
948 return false;
949 }
950 }
951
952 @Override
John Reck997b1b72012-04-19 18:08:25 -0700953 public boolean onUnhandledKeyEvent(KeyEvent event) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700954 if (!isActivityPaused()) {
955 if (event.getAction() == KeyEvent.ACTION_DOWN) {
John Reck997b1b72012-04-19 18:08:25 -0700956 return mActivity.onKeyDown(event.getKeyCode(), event);
Michael Kolb8233fac2010-10-26 16:08:53 -0700957 } else {
John Reck997b1b72012-04-19 18:08:25 -0700958 return mActivity.onKeyUp(event.getKeyCode(), event);
Michael Kolb8233fac2010-10-26 16:08:53 -0700959 }
960 }
John Reck997b1b72012-04-19 18:08:25 -0700961 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700962 }
963
964 @Override
John Reck324d4402011-01-11 16:56:42 -0800965 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700966 // Don't save anything in private browsing mode
967 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800968 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700969
John Reck324d4402011-01-11 16:56:42 -0800970 if (TextUtils.isEmpty(url)
971 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700972 return;
973 }
John Reckf57c0292011-07-21 18:15:39 -0700974 DataController.getInstance(mActivity).updateVisitedHistory(url);
John Reck6c2e2f32011-08-22 13:41:23 -0700975 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -0700976 }
977
978 @Override
979 public void getVisitedHistory(final ValueCallback<String[]> callback) {
980 AsyncTask<Void, Void, String[]> task =
981 new AsyncTask<Void, Void, String[]>() {
982 @Override
983 public String[] doInBackground(Void... unused) {
984 return Browser.getVisitedHistory(mActivity.getContentResolver());
985 }
986 @Override
987 public void onPostExecute(String[] result) {
988 callback.onReceiveValue(result);
989 }
990 };
991 task.execute();
992 }
993
994 @Override
995 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
996 final HttpAuthHandler handler, final String host,
997 final String realm) {
998 String username = null;
999 String password = null;
1000
1001 boolean reuseHttpAuthUsernamePassword
1002 = handler.useHttpAuthUsernamePassword();
1003
1004 if (reuseHttpAuthUsernamePassword && view != null) {
1005 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
1006 if (credentials != null && credentials.length == 2) {
1007 username = credentials[0];
1008 password = credentials[1];
1009 }
1010 }
1011
1012 if (username != null && password != null) {
1013 handler.proceed(username, password);
1014 } else {
Ben Murdochfdd37112011-08-05 15:48:14 +01001015 if (tab.inForeground() && !handler.suppressDialog()) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001016 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
1017 } else {
1018 handler.cancel();
1019 }
1020 }
1021 }
1022
1023 @Override
1024 public void onDownloadStart(Tab tab, String url, String userAgent,
1025 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001026 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -05001027 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001028 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
1029 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001030 // This Tab was opened for the sole purpose of downloading a
1031 // file. Remove it.
1032 if (tab == mTabControl.getCurrentTab()) {
1033 // In this case, the Tab is still on top.
1034 goBackOnePageOrQuit();
1035 } else {
1036 // In this case, it is not.
1037 closeTab(tab);
1038 }
1039 }
1040 }
1041
1042 @Override
1043 public Bitmap getDefaultVideoPoster() {
1044 return mUi.getDefaultVideoPoster();
1045 }
1046
1047 @Override
1048 public View getVideoLoadingProgressView() {
1049 return mUi.getVideoLoadingProgressView();
1050 }
1051
1052 @Override
1053 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1054 SslError error) {
1055 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1056 }
1057
Patrick Scott92066772011-03-10 08:46:27 -05001058 @Override
1059 public void showAutoLogin(Tab tab) {
1060 assert tab.inForeground();
1061 // Update the title bar to show the auto-login request.
1062 mUi.showAutoLogin(tab);
1063 }
1064
1065 @Override
1066 public void hideAutoLogin(Tab tab) {
1067 assert tab.inForeground();
1068 mUi.hideAutoLogin(tab);
1069 }
1070
Michael Kolb8233fac2010-10-26 16:08:53 -07001071 // helper method
1072
1073 /*
1074 * Update the favorites icon if the private browsing isn't enabled and the
1075 * icon is valid.
1076 */
1077 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1078 final String url, Bitmap favicon) {
1079 if (favicon == null) {
1080 return;
1081 }
1082 if (!tab.isPrivateBrowsingEnabled()) {
1083 Bookmarks.updateFavicon(mActivity
1084 .getContentResolver(), originalUrl, url, favicon);
1085 }
1086 }
1087
Leon Scroggins4cd97792010-12-03 15:31:56 -05001088 @Override
1089 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001090 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001091 mUi.bookmarkedStatusHasChanged(tab);
1092 }
1093
Michael Kolb8233fac2010-10-26 16:08:53 -07001094 // end WebViewController
1095
1096 protected void pageUp() {
1097 getCurrentTopWebView().pageUp(false);
1098 }
1099
1100 protected void pageDown() {
1101 getCurrentTopWebView().pageDown(false);
1102 }
1103
1104 // callback from phone title bar
1105 public void editUrl() {
1106 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolb1f9b3562012-04-24 14:38:34 -07001107 mUi.editUrl(false, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001108 }
1109
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001110 public void showCustomView(Tab tab, View view, int requestedOrientation,
Michael Kolb8233fac2010-10-26 16:08:53 -07001111 WebChromeClient.CustomViewCallback callback) {
1112 if (tab.inForeground()) {
1113 if (mUi.isCustomViewShowing()) {
1114 callback.onCustomViewHidden();
1115 return;
1116 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001117 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001118 // Save the menu state and set it to empty while the custom
1119 // view is showing.
1120 mOldMenuState = mMenuState;
1121 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001122 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001123 }
1124 }
1125
1126 @Override
1127 public void hideCustomView() {
1128 if (mUi.isCustomViewShowing()) {
1129 mUi.onHideCustomView();
1130 // Reset the old menu state.
1131 mMenuState = mOldMenuState;
1132 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001133 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001134 }
1135 }
1136
1137 protected void onActivityResult(int requestCode, int resultCode,
1138 Intent intent) {
1139 if (getCurrentTopWebView() == null) return;
1140 switch (requestCode) {
1141 case PREFERENCES_PAGE:
1142 if (resultCode == Activity.RESULT_OK && intent != null) {
1143 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001144 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001145 mTabControl.removeParentChildRelationShips();
1146 }
1147 }
1148 break;
1149 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001150 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001151 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001152 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001153 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001154 case AUTOFILL_SETUP:
1155 // Determine whether a profile was actually set up or not
1156 // and if so, send the message back to the WebTextView to
1157 // fill the form with the new profile.
1158 if (getSettings().getAutoFillProfile() != null) {
1159 mAutoFillSetupMessage.sendToTarget();
1160 mAutoFillSetupMessage = null;
1161 }
1162 break;
John Reckd3e4d5b2011-07-13 15:48:43 -07001163 case COMBO_VIEW:
1164 if (intent == null || resultCode != Activity.RESULT_OK) {
1165 break;
1166 }
John Reck3ba45532011-08-11 16:26:53 -07001167 mUi.showWeb(false);
John Reckd3e4d5b2011-07-13 15:48:43 -07001168 if (Intent.ACTION_VIEW.equals(intent.getAction())) {
1169 Tab t = getCurrentTab();
1170 Uri uri = intent.getData();
1171 loadUrl(t, uri.toString());
1172 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
1173 String[] urls = intent.getStringArrayExtra(
1174 ComboViewActivity.EXTRA_OPEN_ALL);
1175 Tab parent = getCurrentTab();
1176 for (String url : urls) {
1177 parent = openTab(url, parent,
1178 !mSettings.openInBackground(), true);
1179 }
1180 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
1181 long id = intent.getLongExtra(
1182 ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
1183 if (id >= 0) {
1184 createNewSnapshotTab(id, true);
1185 }
1186 }
1187 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001188 default:
1189 break;
1190 }
1191 getCurrentTopWebView().requestFocus();
1192 }
1193
1194 /**
1195 * Open the Go page.
1196 * @param startWithHistory If true, open starting on the history tab.
1197 * Otherwise, start with the bookmarks tab.
1198 */
1199 @Override
Michael Kolb315d5022011-10-13 12:47:11 -07001200 public void bookmarksOrHistoryPicker(ComboViews startView) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001201 if (mTabControl.getCurrentWebView() == null) {
1202 return;
1203 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001204 // clear action mode
1205 if (isInCustomActionMode()) {
1206 endActionMode();
1207 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001208 Bundle extras = new Bundle();
1209 // Disable opening in a new window if we have maxed out the windows
1210 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1211 !mTabControl.canCreateNewTab());
Michael Kolb315d5022011-10-13 12:47:11 -07001212 mUi.showComboView(startView, extras);
Michael Kolb8233fac2010-10-26 16:08:53 -07001213 }
1214
1215 // combo view callbacks
1216
Michael Kolb8233fac2010-10-26 16:08:53 -07001217 // key handling
1218 protected void onBackKey() {
1219 if (!mUi.onBackKey()) {
1220 WebView subwindow = mTabControl.getCurrentSubWindow();
1221 if (subwindow != null) {
1222 if (subwindow.canGoBack()) {
1223 subwindow.goBack();
1224 } else {
1225 dismissSubWindow(mTabControl.getCurrentTab());
1226 }
1227 } else {
1228 goBackOnePageOrQuit();
1229 }
1230 }
1231 }
1232
Michael Kolb4bd767d2011-05-27 11:33:55 -07001233 protected boolean onMenuKey() {
1234 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001235 }
1236
Michael Kolb8233fac2010-10-26 16:08:53 -07001237 // menu handling and state
1238 // TODO: maybe put into separate handler
1239
1240 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckd73c5a22010-12-22 10:22:50 -08001241 if (mMenuState == EMPTY_MENU) {
1242 return false;
1243 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001244 MenuInflater inflater = mActivity.getMenuInflater();
1245 inflater.inflate(R.menu.browser, menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001246 return true;
1247 }
1248
1249 protected void onCreateContextMenu(ContextMenu menu, View v,
1250 ContextMenuInfo menuInfo) {
John Reck0f602f32011-07-07 15:38:43 -07001251 if (v instanceof TitleBar) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001252 return;
1253 }
1254 if (!(v instanceof WebView)) {
1255 return;
1256 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001257 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001258 WebView.HitTestResult result = webview.getHitTestResult();
1259 if (result == null) {
1260 return;
1261 }
1262
1263 int type = result.getType();
1264 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1265 Log.w(LOGTAG,
1266 "We should not show context menu when nothing is touched");
1267 return;
1268 }
1269 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1270 // let TextView handles context menu
1271 return;
1272 }
1273
1274 // Note, http://b/issue?id=1106666 is requesting that
1275 // an inflated menu can be used again. This is not available
1276 // yet, so inflate each time (yuk!)
1277 MenuInflater inflater = mActivity.getMenuInflater();
1278 inflater.inflate(R.menu.browsercontext, menu);
1279
1280 // Show the correct menu group
1281 final String extra = result.getExtra();
Michael Kolbc159c1a2011-12-15 16:06:38 -08001282 if (extra == null) return;
Michael Kolb8233fac2010-10-26 16:08:53 -07001283 menu.setGroupVisible(R.id.PHONE_MENU,
1284 type == WebView.HitTestResult.PHONE_TYPE);
1285 menu.setGroupVisible(R.id.EMAIL_MENU,
1286 type == WebView.HitTestResult.EMAIL_TYPE);
1287 menu.setGroupVisible(R.id.GEO_MENU,
1288 type == WebView.HitTestResult.GEO_TYPE);
1289 menu.setGroupVisible(R.id.IMAGE_MENU,
1290 type == WebView.HitTestResult.IMAGE_TYPE
1291 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1292 menu.setGroupVisible(R.id.ANCHOR_MENU,
1293 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1294 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001295 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1296 || type == WebView.HitTestResult.PHONE_TYPE
1297 || type == WebView.HitTestResult.EMAIL_TYPE
1298 || type == WebView.HitTestResult.GEO_TYPE;
1299 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1300 if (hitText) {
1301 menu.findItem(R.id.select_text_menu_id)
1302 .setOnMenuItemClickListener(new SelectText(webview));
1303 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001304 // Setup custom handling depending on the type
1305 switch (type) {
1306 case WebView.HitTestResult.PHONE_TYPE:
1307 menu.setHeaderTitle(Uri.decode(extra));
1308 menu.findItem(R.id.dial_context_menu_id).setIntent(
1309 new Intent(Intent.ACTION_VIEW, Uri
1310 .parse(WebView.SCHEME_TEL + extra)));
1311 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1312 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1313 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1314 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1315 addIntent);
1316 menu.findItem(R.id.copy_phone_context_menu_id)
1317 .setOnMenuItemClickListener(
1318 new Copy(extra));
1319 break;
1320
1321 case WebView.HitTestResult.EMAIL_TYPE:
1322 menu.setHeaderTitle(extra);
1323 menu.findItem(R.id.email_context_menu_id).setIntent(
1324 new Intent(Intent.ACTION_VIEW, Uri
1325 .parse(WebView.SCHEME_MAILTO + extra)));
1326 menu.findItem(R.id.copy_mail_context_menu_id)
1327 .setOnMenuItemClickListener(
1328 new Copy(extra));
1329 break;
1330
1331 case WebView.HitTestResult.GEO_TYPE:
1332 menu.setHeaderTitle(extra);
1333 menu.findItem(R.id.map_context_menu_id).setIntent(
1334 new Intent(Intent.ACTION_VIEW, Uri
1335 .parse(WebView.SCHEME_GEO
1336 + URLEncoder.encode(extra))));
1337 menu.findItem(R.id.copy_geo_context_menu_id)
1338 .setOnMenuItemClickListener(
1339 new Copy(extra));
1340 break;
1341
1342 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1343 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001344 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001345 // decide whether to show the open link in new tab option
1346 boolean showNewTab = mTabControl.canCreateNewTab();
1347 MenuItem newTabItem
1348 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001349 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001350 ? R.string.contextmenu_openlink_newwindow_background
1351 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001352 newTabItem.setVisible(showNewTab);
1353 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001354 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1355 newTabItem.setOnMenuItemClickListener(
1356 new MenuItem.OnMenuItemClickListener() {
1357 @Override
1358 public boolean onMenuItemClick(MenuItem item) {
1359 final HashMap<String, WebView> hrefMap =
1360 new HashMap<String, WebView>();
1361 hrefMap.put("webview", webview);
1362 final Message msg = mHandler.obtainMessage(
1363 FOCUS_NODE_HREF,
1364 R.id.open_newtab_context_menu_id,
1365 0, hrefMap);
1366 webview.requestFocusNodeHref(msg);
1367 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001368 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001369 });
1370 } else {
1371 newTabItem.setOnMenuItemClickListener(
1372 new MenuItem.OnMenuItemClickListener() {
1373 @Override
1374 public boolean onMenuItemClick(MenuItem item) {
1375 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001376 openTab(extra, parent,
1377 !mSettings.openInBackground(),
1378 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001379 return true;
1380 }
1381 });
1382 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001383 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001384 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1385 break;
1386 }
1387 // otherwise fall through to handle image part
1388 case WebView.HitTestResult.IMAGE_TYPE:
Victoria Lease5987b802012-03-12 13:05:23 -07001389 MenuItem shareItem = menu.findItem(R.id.share_link_context_menu_id);
1390 shareItem.setVisible(type == WebView.HitTestResult.IMAGE_TYPE);
Michael Kolb8233fac2010-10-26 16:08:53 -07001391 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1392 menu.setHeaderTitle(extra);
Victoria Lease5987b802012-03-12 13:05:23 -07001393 shareItem.setOnMenuItemClickListener(
1394 new MenuItem.OnMenuItemClickListener() {
1395 @Override
1396 public boolean onMenuItemClick(MenuItem item) {
1397 sharePage(mActivity, null, extra, null,
1398 null);
1399 return true;
1400 }
1401 }
1402 );
Michael Kolb8233fac2010-10-26 16:08:53 -07001403 }
Michael Kolb3639c4c2011-09-28 15:36:40 -07001404 menu.findItem(R.id.view_image_context_menu_id)
1405 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1406 @Override
1407 public boolean onMenuItemClick(MenuItem item) {
1408 openTab(extra, mTabControl.getCurrentTab(), true, true);
1409 return false;
1410 }
1411 });
Michael Kolb8233fac2010-10-26 16:08:53 -07001412 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001413 setOnMenuItemClickListener(
1414 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001415 menu.findItem(R.id.set_wallpaper_context_menu_id).
1416 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1417 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001418 break;
1419
1420 default:
1421 Log.w(LOGTAG, "We should not get here.");
1422 break;
1423 }
1424 //update the ui
1425 mUi.onContextMenuCreated(menu);
1426 }
1427
1428 /**
1429 * As the menu can be open when loading state changes
1430 * we must manually update the state of the stop/reload menu
1431 * item
1432 */
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001433 private void updateInLoadMenuItems(Menu menu, Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001434 if (menu == null) {
1435 return;
1436 }
1437 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolbb8337132011-11-28 15:07:39 -08001438 MenuItem src = ((tab != null) && tab.inPageLoad()) ?
Michael Kolb8233fac2010-10-26 16:08:53 -07001439 menu.findItem(R.id.stop_menu_id):
1440 menu.findItem(R.id.reload_menu_id);
1441 if (src != null) {
1442 dest.setIcon(src.getIcon());
1443 dest.setTitle(src.getTitle());
1444 }
1445 }
1446
John Reckb3417f02011-01-14 11:01:05 -08001447 boolean onPrepareOptionsMenu(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001448 updateInLoadMenuItems(menu, getCurrentTab());
John Recke1a03a32011-09-14 17:04:16 -07001449 // hold on to the menu reference here; it is used by the page callbacks
1450 // to update the menu based on loading state
1451 mCachedMenu = menu;
Michael Kolb8233fac2010-10-26 16:08:53 -07001452 // Note: setVisible will decide whether an item is visible; while
1453 // setEnabled() will decide whether an item is enabled, which also means
1454 // whether the matching shortcut key will function.
1455 switch (mMenuState) {
1456 case EMPTY_MENU:
1457 if (mCurrentMenuState != mMenuState) {
1458 menu.setGroupVisible(R.id.MAIN_MENU, false);
1459 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1460 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1461 }
1462 break;
1463 default:
1464 if (mCurrentMenuState != mMenuState) {
1465 menu.setGroupVisible(R.id.MAIN_MENU, true);
1466 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1467 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1468 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001469 updateMenuState(getCurrentTab(), menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001470 break;
1471 }
1472 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001473 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001474 }
1475
Michael Kolb4bf79712011-07-14 14:18:12 -07001476 @Override
1477 public void updateMenuState(Tab tab, Menu menu) {
1478 boolean canGoBack = false;
1479 boolean canGoForward = false;
1480 boolean isHome = false;
John Reck42229bc2011-08-19 13:26:43 -07001481 boolean isDesktopUa = false;
John Recke1a03a32011-09-14 17:04:16 -07001482 boolean isLive = false;
Michael Kolb4bf79712011-07-14 14:18:12 -07001483 if (tab != null) {
1484 canGoBack = tab.canGoBack();
1485 canGoForward = tab.canGoForward();
1486 isHome = mSettings.getHomePage().equals(tab.getUrl());
John Reck42229bc2011-08-19 13:26:43 -07001487 isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
John Recke1a03a32011-09-14 17:04:16 -07001488 isLive = !tab.isSnapshot();
Michael Kolb4bf79712011-07-14 14:18:12 -07001489 }
1490 final MenuItem back = menu.findItem(R.id.back_menu_id);
1491 back.setEnabled(canGoBack);
1492
1493 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1494 home.setEnabled(!isHome);
1495
1496 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1497 forward.setEnabled(canGoForward);
1498
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001499 final MenuItem source = menu.findItem(isInLoad() ? R.id.stop_menu_id
1500 : R.id.reload_menu_id);
Michael Kolb4bf79712011-07-14 14:18:12 -07001501 final MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolb7ab75ee2011-07-14 16:36:38 -07001502 if (source != null && dest != null) {
1503 dest.setTitle(source.getTitle());
1504 dest.setIcon(source.getIcon());
1505 }
John Recke1a03a32011-09-14 17:04:16 -07001506 menu.setGroupVisible(R.id.NAV_MENU, isLive);
Michael Kolb4bf79712011-07-14 14:18:12 -07001507
1508 // decide whether to show the share link option
1509 PackageManager pm = mActivity.getPackageManager();
1510 Intent send = new Intent(Intent.ACTION_SEND);
1511 send.setType("text/plain");
1512 ResolveInfo ri = pm.resolveActivity(send,
1513 PackageManager.MATCH_DEFAULT_ONLY);
1514 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1515
1516 boolean isNavDump = mSettings.enableNavDump();
1517 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1518 nav.setVisible(isNavDump);
1519 nav.setEnabled(isNavDump);
1520
1521 boolean showDebugSettings = mSettings.isDebugEnabled();
John Reck42229bc2011-08-19 13:26:43 -07001522 final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
1523 uaSwitcher.setChecked(isDesktopUa);
John Recke1a03a32011-09-14 17:04:16 -07001524 menu.setGroupVisible(R.id.LIVE_MENU, isLive);
1525 menu.setGroupVisible(R.id.SNAPSHOT_MENU, !isLive);
Michael Kolb315d5022011-10-13 12:47:11 -07001526 menu.setGroupVisible(R.id.COMBO_MENU, false);
Michael Kolb4bf79712011-07-14 14:18:12 -07001527
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001528 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001529 }
1530
Michael Kolb8233fac2010-10-26 16:08:53 -07001531 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001532 if (null == getCurrentTopWebView()) {
1533 return false;
1534 }
1535 if (mMenuIsDown) {
1536 // The shortcut action consumes the MENU. Even if it is still down,
1537 // it won't trigger the next shortcut action. In the case of the
1538 // shortcut action triggering a new activity, like Bookmarks, we
1539 // won't get onKeyUp for MENU. So it is important to reset it here.
1540 mMenuIsDown = false;
1541 }
Michael Kolb3ca12752011-07-20 13:52:25 -07001542 if (mUi.onOptionsItemSelected(item)) {
1543 // ui callback handled it
1544 return true;
1545 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001546 switch (item.getItemId()) {
1547 // -- Main menu
1548 case R.id.new_tab_menu_id:
1549 openTabToHomePage();
1550 break;
1551
1552 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001553 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001554 break;
1555
1556 case R.id.goto_menu_id:
1557 editUrl();
1558 break;
1559
1560 case R.id.bookmarks_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001561 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
1562 break;
1563
1564 case R.id.history_menu_id:
1565 bookmarksOrHistoryPicker(ComboViews.History);
1566 break;
1567
1568 case R.id.snapshots_menu_id:
1569 bookmarksOrHistoryPicker(ComboViews.Snapshots);
Michael Kolb8233fac2010-10-26 16:08:53 -07001570 break;
1571
Michael Kolb8233fac2010-10-26 16:08:53 -07001572 case R.id.add_bookmark_menu_id:
Michael Kolb80f75082012-04-10 10:50:06 -07001573 bookmarkCurrentPage();
Michael Kolb8233fac2010-10-26 16:08:53 -07001574 break;
1575
1576 case R.id.stop_reload_menu_id:
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001577 if (isInLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001578 stopLoading();
1579 } else {
1580 getCurrentTopWebView().reload();
1581 }
1582 break;
1583
1584 case R.id.back_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001585 getCurrentTab().goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07001586 break;
1587
1588 case R.id.forward_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001589 getCurrentTab().goForward();
Michael Kolb8233fac2010-10-26 16:08:53 -07001590 break;
1591
1592 case R.id.close_menu_id:
1593 // Close the subwindow if it exists.
1594 if (mTabControl.getCurrentSubWindow() != null) {
1595 dismissSubWindow(mTabControl.getCurrentTab());
1596 break;
1597 }
1598 closeCurrentTab();
1599 break;
1600
1601 case R.id.homepage_menu_id:
1602 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07001603 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07001604 break;
1605
1606 case R.id.preferences_menu_id:
Michael Kolb80f75082012-04-10 10:50:06 -07001607 openPreferences();
Michael Kolb8233fac2010-10-26 16:08:53 -07001608 break;
1609
1610 case R.id.find_menu_id:
Michael Kolbe11b9212012-04-13 13:39:54 -07001611 findOnPage();
Michael Kolb8233fac2010-10-26 16:08:53 -07001612 break;
1613
John Reck2bc80422011-06-30 15:11:49 -07001614 case R.id.save_snapshot_menu_id:
1615 final Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07001616 if (source == null) break;
John Reck68234a92012-04-19 15:27:12 -07001617 new SaveSnapshotTask(source).execute();
Leon Scrogginsac993842011-02-02 12:54:07 -05001618 break;
1619
Michael Kolb8233fac2010-10-26 16:08:53 -07001620 case R.id.page_info_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001621 showPageInfo();
Michael Kolb8233fac2010-10-26 16:08:53 -07001622 break;
1623
John Recke1a03a32011-09-14 17:04:16 -07001624 case R.id.snapshot_go_live:
1625 goLive();
1626 return true;
1627
Michael Kolb8233fac2010-10-26 16:08:53 -07001628 case R.id.share_page_menu_id:
1629 Tab currentTab = mTabControl.getCurrentTab();
1630 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001631 return false;
1632 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001633 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001634 break;
1635
1636 case R.id.dump_nav_menu_id:
1637 getCurrentTopWebView().debugDump();
1638 break;
1639
Michael Kolb8233fac2010-10-26 16:08:53 -07001640 case R.id.zoom_in_menu_id:
1641 getCurrentTopWebView().zoomIn();
1642 break;
1643
1644 case R.id.zoom_out_menu_id:
1645 getCurrentTopWebView().zoomOut();
1646 break;
1647
1648 case R.id.view_downloads_menu_id:
1649 viewDownloads();
1650 break;
1651
John Reck42229bc2011-08-19 13:26:43 -07001652 case R.id.ua_desktop_menu_id:
Michael Kolb80f75082012-04-10 10:50:06 -07001653 toggleUserAgent();
John Reck42229bc2011-08-19 13:26:43 -07001654 break;
1655
Michael Kolb8233fac2010-10-26 16:08:53 -07001656 case R.id.window_one_menu_id:
1657 case R.id.window_two_menu_id:
1658 case R.id.window_three_menu_id:
1659 case R.id.window_four_menu_id:
1660 case R.id.window_five_menu_id:
1661 case R.id.window_six_menu_id:
1662 case R.id.window_seven_menu_id:
1663 case R.id.window_eight_menu_id:
1664 {
1665 int menuid = item.getItemId();
1666 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1667 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1668 Tab desiredTab = mTabControl.getTab(id);
1669 if (desiredTab != null &&
1670 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001671 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001672 }
1673 break;
1674 }
1675 }
1676 }
1677 break;
1678
1679 default:
1680 return false;
1681 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001682 return true;
1683 }
1684
John Reck68234a92012-04-19 15:27:12 -07001685 private class SaveSnapshotTask extends AsyncTask<Void, Void, Long>
1686 implements OnCancelListener {
1687
1688 private Tab mTab;
1689 private Dialog mProgressDialog;
1690 private ContentValues mValues;
1691
1692 private SaveSnapshotTask(Tab tab) {
1693 mTab = tab;
1694 }
1695
1696 @Override
1697 protected void onPreExecute() {
1698 CharSequence message = mActivity.getText(R.string.saving_snapshot);
1699 mProgressDialog = ProgressDialog.show(mActivity, null, message,
1700 true, true, this);
1701 mValues = mTab.createSnapshotValues();
1702 }
1703
1704 @Override
1705 protected Long doInBackground(Void... params) {
1706 if (!mTab.saveViewState(mValues)) {
1707 return null;
1708 }
1709 if (isCancelled()) {
1710 String path = mValues.getAsString(Snapshots.VIEWSTATE_PATH);
1711 File file = mActivity.getFileStreamPath(path);
1712 if (!file.delete()) {
1713 file.deleteOnExit();
1714 }
1715 return null;
1716 }
1717 final ContentResolver cr = mActivity.getContentResolver();
1718 Uri result = cr.insert(Snapshots.CONTENT_URI, mValues);
1719 if (result == null) {
1720 return null;
1721 }
1722 long id = ContentUris.parseId(result);
1723 return id;
1724 }
1725
1726 @Override
1727 protected void onPostExecute(Long id) {
1728 if (isCancelled()) {
1729 return;
1730 }
1731 mProgressDialog.dismiss();
1732 if (id == null) {
1733 Toast.makeText(mActivity, R.string.snapshot_failed,
1734 Toast.LENGTH_SHORT).show();
1735 return;
1736 }
1737 Bundle b = new Bundle();
1738 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
1739 mUi.showComboView(ComboViews.Snapshots, b);
1740 }
1741
1742 @Override
1743 public void onCancel(DialogInterface dialog) {
1744 cancel(true);
1745 }
1746 }
1747
Michael Kolb80f75082012-04-10 10:50:06 -07001748 @Override
1749 public void toggleUserAgent() {
1750 WebView web = getCurrentWebView();
1751 mSettings.toggleDesktopUseragent(web);
1752 web.loadUrl(web.getOriginalUrl());
1753 }
1754
1755 @Override
1756 public void findOnPage() {
1757 getCurrentTopWebView().showFindDialog(null, true);
1758 }
1759
1760 @Override
1761 public void openPreferences() {
1762 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1763 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1764 getCurrentTopWebView().getUrl());
1765 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1766 }
1767
1768 @Override
1769 public void bookmarkCurrentPage() {
1770 Intent bookmarkIntent = createBookmarkCurrentPageIntent(false);
1771 if (bookmarkIntent != null) {
1772 mActivity.startActivity(bookmarkIntent);
1773 }
1774 }
1775
John Recke1a03a32011-09-14 17:04:16 -07001776 private void goLive() {
1777 Tab t = getCurrentTab();
1778 t.loadUrl(t.getUrl(), null);
1779 }
1780
Michael Kolb315d5022011-10-13 12:47:11 -07001781 @Override
1782 public void showPageInfo() {
1783 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
1784 }
1785
Michael Kolb8233fac2010-10-26 16:08:53 -07001786 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001787 // Let the History and Bookmark fragments handle menus they created.
1788 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1789 return false;
1790 }
1791
Michael Kolb8233fac2010-10-26 16:08:53 -07001792 int id = item.getItemId();
1793 boolean result = true;
1794 switch (id) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001795 // -- Browser context menu
1796 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001797 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001798 case R.id.copy_link_context_menu_id:
1799 final WebView webView = getCurrentTopWebView();
1800 if (null == webView) {
1801 result = false;
1802 break;
1803 }
1804 final HashMap<String, WebView> hrefMap =
1805 new HashMap<String, WebView>();
1806 hrefMap.put("webview", webView);
1807 final Message msg = mHandler.obtainMessage(
1808 FOCUS_NODE_HREF, id, 0, hrefMap);
1809 webView.requestFocusNodeHref(msg);
1810 break;
1811
1812 default:
1813 // For other context menus
1814 result = onOptionsItemSelected(item);
1815 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001816 return result;
1817 }
1818
1819 /**
1820 * support programmatically opening the context menu
1821 */
1822 public void openContextMenu(View view) {
1823 mActivity.openContextMenu(view);
1824 }
1825
1826 /**
1827 * programmatically open the options menu
1828 */
1829 public void openOptionsMenu() {
1830 mActivity.openOptionsMenu();
1831 }
1832
1833 public boolean onMenuOpened(int featureId, Menu menu) {
1834 if (mOptionsMenuOpen) {
1835 if (mConfigChanged) {
1836 // We do not need to make any changes to the state of the
1837 // title bar, since the only thing that happened was a
1838 // change in orientation
1839 mConfigChanged = false;
1840 } else {
1841 if (!mExtendedMenuOpen) {
1842 mExtendedMenuOpen = true;
1843 mUi.onExtendedMenuOpened();
1844 } else {
1845 // Switching the menu back to icon view, so show the
1846 // title bar once again.
1847 mExtendedMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001848 mUi.onExtendedMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001849 }
1850 }
1851 } else {
1852 // The options menu is closed, so open it, and show the title
1853 mOptionsMenuOpen = true;
1854 mConfigChanged = false;
1855 mExtendedMenuOpen = false;
1856 mUi.onOptionsMenuOpened();
1857 }
1858 return true;
1859 }
1860
1861 public void onOptionsMenuClosed(Menu menu) {
1862 mOptionsMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001863 mUi.onOptionsMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001864 }
1865
1866 public void onContextMenuClosed(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001867 mUi.onContextMenuClosed(menu, isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001868 }
1869
1870 // Helper method for getting the top window.
1871 @Override
1872 public WebView getCurrentTopWebView() {
1873 return mTabControl.getCurrentTopWebView();
1874 }
1875
1876 @Override
1877 public WebView getCurrentWebView() {
1878 return mTabControl.getCurrentWebView();
1879 }
1880
1881 /*
1882 * This method is called as a result of the user selecting the options
1883 * menu to see the download window. It shows the download window on top of
1884 * the current window.
1885 */
1886 void viewDownloads() {
1887 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1888 mActivity.startActivity(intent);
1889 }
1890
John Reck30b065e2011-07-19 10:58:05 -07001891 int getActionModeHeight() {
1892 TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
1893 new int[] { android.R.attr.actionBarSize });
1894 int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
1895 actionBarSizeTypedArray.recycle();
1896 return size;
1897 }
1898
Michael Kolb8233fac2010-10-26 16:08:53 -07001899 // action mode
1900
1901 void onActionModeStarted(ActionMode mode) {
1902 mUi.onActionModeStarted(mode);
1903 mActionMode = mode;
1904 }
1905
1906 /*
1907 * True if a custom ActionMode (i.e. find or select) is in use.
1908 */
1909 @Override
1910 public boolean isInCustomActionMode() {
1911 return mActionMode != null;
1912 }
1913
1914 /*
1915 * End the current ActionMode.
1916 */
1917 @Override
1918 public void endActionMode() {
1919 if (mActionMode != null) {
1920 mActionMode.finish();
1921 }
1922 }
1923
1924 /*
1925 * Called by find and select when they are finished. Replace title bars
1926 * as necessary.
1927 */
1928 public void onActionModeFinished(ActionMode mode) {
1929 if (!isInCustomActionMode()) return;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001930 mUi.onActionModeFinished(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001931 mActionMode = null;
1932 }
1933
1934 boolean isInLoad() {
Michael Kolbc5b0b2d2011-11-29 16:13:35 -08001935 final Tab tab = getCurrentTab();
1936 return (tab != null) && tab.inPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07001937 }
1938
1939 // bookmark handling
1940
1941 /**
1942 * add the current page as a bookmark to the given folder id
1943 * @param folderId use -1 for the default folder
John Reckd3e4d5b2011-07-13 15:48:43 -07001944 * @param editExisting If true, check to see whether the site is already
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001945 * bookmarked, and if it is, edit that bookmark. If false, and
1946 * the site is already bookmarked, do not attempt to edit the
1947 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001948 */
1949 @Override
John Reckd3e4d5b2011-07-13 15:48:43 -07001950 public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
John Recka60fffa2011-09-06 16:30:29 -07001951 WebView w = getCurrentTopWebView();
1952 if (w == null) {
1953 return null;
1954 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001955 Intent i = new Intent(mActivity,
1956 AddBookmarkPage.class);
Michael Kolb8233fac2010-10-26 16:08:53 -07001957 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1958 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1959 String touchIconUrl = w.getTouchIconUrl();
1960 if (touchIconUrl != null) {
1961 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1962 WebSettings settings = w.getSettings();
1963 if (settings != null) {
1964 i.putExtra(AddBookmarkPage.USER_AGENT,
1965 settings.getUserAgentString());
1966 }
1967 }
1968 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1969 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1970 getDesiredThumbnailHeight(mActivity)));
1971 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07001972 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001973 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1974 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001975 // Put the dialog at the upper right of the screen, covering the
1976 // star on the title bar.
1977 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07001978 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07001979 }
1980
1981 // file chooser
Ben Murdoch8cad4132012-01-11 10:56:43 +00001982 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001983 mUploadHandler = new UploadHandler(this);
Ben Murdoch8cad4132012-01-11 10:56:43 +00001984 mUploadHandler.openFileChooser(uploadMsg, acceptType, capture);
Michael Kolb8233fac2010-10-26 16:08:53 -07001985 }
1986
1987 // thumbnails
1988
1989 /**
1990 * Return the desired width for thumbnail screenshots, which are stored in
1991 * the database, and used on the bookmarks screen.
1992 * @param context Context for finding out the density of the screen.
1993 * @return desired width for thumbnail screenshot.
1994 */
1995 static int getDesiredThumbnailWidth(Context context) {
1996 return context.getResources().getDimensionPixelOffset(
1997 R.dimen.bookmarkThumbnailWidth);
1998 }
1999
2000 /**
2001 * Return the desired height for thumbnail screenshots, which are stored in
2002 * the database, and used on the bookmarks screen.
2003 * @param context Context for finding out the density of the screen.
2004 * @return desired height for thumbnail screenshot.
2005 */
2006 static int getDesiredThumbnailHeight(Context context) {
2007 return context.getResources().getDimensionPixelOffset(
2008 R.dimen.bookmarkThumbnailHeight);
2009 }
2010
John Reck8cc92352011-07-06 17:41:52 -07002011 static Bitmap createScreenshot(WebView view, int width, int height) {
John Reckd7dd9b22011-08-30 09:18:29 -07002012 if (view == null || view.getContentHeight() == 0
2013 || view.getContentWidth() == 0) {
2014 return null;
2015 }
John Reck5c6ac2f2011-01-05 10:18:03 -08002016 // We render to a bitmap 2x the desired size so that we can then
2017 // re-scale it with filtering since canvas.scale doesn't filter
2018 // This helps reduce aliasing at the cost of being slightly blurry
2019 final int filter_scale = 2;
John Reckd7dd9b22011-08-30 09:18:29 -07002020 int scaledWidth = width * filter_scale;
2021 int scaledHeight = height * filter_scale;
2022 if (sThumbnailBitmap == null || sThumbnailBitmap.getWidth() != scaledWidth
2023 || sThumbnailBitmap.getHeight() != scaledHeight) {
2024 if (sThumbnailBitmap != null) {
2025 sThumbnailBitmap.recycle();
2026 sThumbnailBitmap = null;
2027 }
2028 sThumbnailBitmap =
2029 Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.RGB_565);
Michael Kolb8233fac2010-10-26 16:08:53 -07002030 }
John Reckd7dd9b22011-08-30 09:18:29 -07002031 Canvas canvas = new Canvas(sThumbnailBitmap);
2032 int contentWidth = view.getContentWidth();
2033 float overviewScale = scaledWidth / (view.getScale() * contentWidth);
2034 if (view instanceof BrowserWebView) {
2035 int dy = -((BrowserWebView)view).getTitleHeight();
2036 canvas.translate(0, dy * overviewScale);
2037 }
2038
2039 canvas.scale(overviewScale, overviewScale);
2040
2041 if (view instanceof BrowserWebView) {
2042 ((BrowserWebView)view).drawContent(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07002043 } else {
John Reckd7dd9b22011-08-30 09:18:29 -07002044 view.draw(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07002045 }
John Reckd7dd9b22011-08-30 09:18:29 -07002046 Bitmap ret = Bitmap.createScaledBitmap(sThumbnailBitmap,
2047 width, height, true);
Dianne Hackborn43cfe8a2011-08-02 16:59:35 -07002048 canvas.setBitmap(null);
John Reck5c6ac2f2011-01-05 10:18:03 -08002049 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07002050 }
2051
John Reck34ef2672011-02-10 11:30:55 -08002052 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002053 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07002054 // FIXME: Would like to make sure there is actually something to
2055 // draw, but the API for that (WebViewCore.pictureReady()) is not
2056 // currently accessible here.
2057
John Reck34ef2672011-02-10 11:30:55 -08002058 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08002059 if (view == null) {
2060 // Tab was destroyed
2061 return;
2062 }
John Reck34ef2672011-02-10 11:30:55 -08002063 final String url = tab.getUrl();
2064 final String originalUrl = view.getOriginalUrl();
John Reck34ef2672011-02-10 11:30:55 -08002065 if (TextUtils.isEmpty(url)) {
2066 return;
2067 }
2068
2069 // Only update thumbnails for web urls (http(s)://), not for
2070 // about:, javascript:, data:, etc...
2071 // Unless it is a bookmarked site, then always update
2072 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2073 return;
2074 }
2075
Michael Kolb8233fac2010-10-26 16:08:53 -07002076 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2077 getDesiredThumbnailHeight(mActivity));
2078 if (bm == null) {
2079 return;
2080 }
2081
2082 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002083 new AsyncTask<Void, Void, Void>() {
2084 @Override
2085 protected Void doInBackground(Void... unused) {
2086 Cursor cursor = null;
2087 try {
2088 // TODO: Clean this up
2089 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2090 if (cursor != null && cursor.moveToFirst()) {
2091 final ByteArrayOutputStream os =
2092 new ByteArrayOutputStream();
2093 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002094
John Reck34ef2672011-02-10 11:30:55 -08002095 ContentValues values = new ContentValues();
2096 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002097
John Reck34ef2672011-02-10 11:30:55 -08002098 do {
John Reck617fd832011-02-16 14:35:59 -08002099 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002100 cr.update(Images.CONTENT_URI, values, null, null);
2101 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002102 }
John Reck34ef2672011-02-10 11:30:55 -08002103 } catch (IllegalStateException e) {
2104 // Ignore
2105 } finally {
2106 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002107 }
John Reck34ef2672011-02-10 11:30:55 -08002108 return null;
2109 }
2110 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002111 }
2112
2113 private class Copy implements OnMenuItemClickListener {
2114 private CharSequence mText;
2115
2116 public boolean onMenuItemClick(MenuItem item) {
2117 copy(mText);
2118 return true;
2119 }
2120
2121 public Copy(CharSequence toCopy) {
2122 mText = toCopy;
2123 }
2124 }
2125
Leon Scroggins63c02662010-11-18 15:16:27 -05002126 private static class Download implements OnMenuItemClickListener {
2127 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002128 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002129 private boolean mPrivateBrowsing;
George Mount387d45d2011-10-07 15:57:53 -07002130 private static final String FALLBACK_EXTENSION = "dat";
2131 private static final String IMAGE_BASE_FORMAT = "yyyy-MM-dd-HH-mm-ss-";
Michael Kolb8233fac2010-10-26 16:08:53 -07002132
2133 public boolean onMenuItemClick(MenuItem item) {
George Mount387d45d2011-10-07 15:57:53 -07002134 if (DataUri.isDataUri(mText)) {
2135 saveDataUri();
2136 } else {
2137 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
2138 null, null, mPrivateBrowsing);
2139 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002140 return true;
2141 }
2142
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002143 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002144 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002145 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002146 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002147 }
George Mount387d45d2011-10-07 15:57:53 -07002148
2149 /**
2150 * Treats mText as a data URI and writes its contents to a file
2151 * based on the current time.
2152 */
2153 private void saveDataUri() {
2154 FileOutputStream outputStream = null;
2155 try {
2156 DataUri uri = new DataUri(mText);
2157 File target = getTarget(uri);
2158 outputStream = new FileOutputStream(target);
2159 outputStream.write(uri.getData());
2160 final DownloadManager manager =
2161 (DownloadManager) mActivity.getSystemService(Context.DOWNLOAD_SERVICE);
2162 manager.addCompletedDownload(target.getName(),
2163 mActivity.getTitle().toString(), false,
2164 uri.getMimeType(), target.getAbsolutePath(),
George Mount7501bf42011-11-17 11:17:03 -08002165 (long)uri.getData().length, true);
George Mount387d45d2011-10-07 15:57:53 -07002166 } catch (IOException e) {
2167 Log.e(LOGTAG, "Could not save data URL");
2168 } finally {
2169 if (outputStream != null) {
2170 try {
2171 outputStream.close();
2172 } catch (IOException e) {
2173 // ignore close errors
2174 }
2175 }
2176 }
2177 }
2178
2179 /**
2180 * Creates a File based on the current time stamp and uses
2181 * the mime type of the DataUri to get the extension.
2182 */
2183 private File getTarget(DataUri uri) throws IOException {
2184 File dir = mActivity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
2185 DateFormat format = new SimpleDateFormat(IMAGE_BASE_FORMAT);
2186 String nameBase = format.format(new Date());
2187 String mimeType = uri.getMimeType();
2188 MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
2189 String extension = mimeTypeMap.getExtensionFromMimeType(mimeType);
2190 if (extension == null) {
2191 Log.w(LOGTAG, "Unknown mime type in data URI" + mimeType);
2192 extension = FALLBACK_EXTENSION;
2193 }
2194 extension = "." + extension; // createTempFile needs the '.'
2195 File targetFile = File.createTempFile(nameBase, extension, dir);
2196 return targetFile;
2197 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002198 }
2199
Cary Clark8974d282010-11-22 10:46:05 -05002200 private static class SelectText implements OnMenuItemClickListener {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002201 private WebViewClassic mWebView;
Cary Clark8974d282010-11-22 10:46:05 -05002202
2203 public boolean onMenuItemClick(MenuItem item) {
2204 if (mWebView != null) {
2205 return mWebView.selectText();
2206 }
2207 return false;
2208 }
2209
2210 public SelectText(WebView webView) {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002211 mWebView = WebViewClassic.fromWebView(webView);
Cary Clark8974d282010-11-22 10:46:05 -05002212 }
2213
2214 }
2215
Michael Kolb8233fac2010-10-26 16:08:53 -07002216 /********************** TODO: UI stuff *****************************/
2217
2218 // these methods have been copied, they still need to be cleaned up
2219
2220 /****************** tabs ***************************************************/
2221
2222 // basic tab interactions:
2223
2224 // it is assumed that tabcontrol already knows about the tab
2225 protected void addTab(Tab tab) {
2226 mUi.addTab(tab);
2227 }
2228
2229 protected void removeTab(Tab tab) {
2230 mUi.removeTab(tab);
2231 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002232 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002233 }
2234
Michael Kolbf2055602011-04-09 17:20:03 -07002235 @Override
2236 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002237 // monkey protection against delayed start
2238 if (tab != null) {
2239 mTabControl.setCurrentTab(tab);
2240 // the tab is guaranteed to have a webview after setCurrentTab
2241 mUi.setActiveTab(tab);
2242 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002243 }
2244
John Reck8bcafc12011-08-29 16:43:02 -07002245 protected void closeEmptyTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002246 Tab current = mTabControl.getCurrentTab();
2247 if (current != null
2248 && current.getWebView().copyBackForwardList().getSize() == 0) {
John Reck8bcafc12011-08-29 16:43:02 -07002249 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002250 }
2251 }
2252
John Reck26b18322011-06-21 13:08:58 -07002253 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002254 // Dismiss the subwindow if applicable.
2255 dismissSubWindow(appTab);
2256 // Since we might kill the WebView, remove it from the
2257 // content view first.
2258 mUi.detachTab(appTab);
2259 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002260 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002261 // TODO: analyze why the remove and add are necessary
2262 mUi.attachTab(appTab);
2263 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002264 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002265 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002266 } else {
2267 // If the tab was the current tab, we have to attach
2268 // it to the view system again.
2269 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002270 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002271 }
2272 }
2273
2274 // Remove the sub window if it exists. Also called by TabControl when the
2275 // user clicks the 'X' to dismiss a sub window.
2276 public void dismissSubWindow(Tab tab) {
2277 removeSubWindow(tab);
2278 // dismiss the subwindow. This will destroy the WebView.
2279 tab.dismissSubWindow();
Michael Kolbe8c97572011-11-21 14:03:56 -08002280 WebView wv = getCurrentTopWebView();
2281 if (wv != null) {
2282 wv.requestFocus();
2283 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002284 }
2285
2286 @Override
2287 public void removeSubWindow(Tab t) {
2288 if (t.getSubWebView() != null) {
2289 mUi.removeSubWindow(t.getSubViewContainer());
2290 }
2291 }
2292
2293 @Override
2294 public void attachSubWindow(Tab tab) {
2295 if (tab.getSubWebView() != null) {
2296 mUi.attachSubWindow(tab.getSubViewContainer());
2297 getCurrentTopWebView().requestFocus();
2298 }
2299 }
2300
Mathew Inwood29721c22011-06-29 17:55:24 +01002301 private Tab showPreloadedTab(final UrlData urlData) {
2302 if (!urlData.isPreloaded()) {
2303 return null;
2304 }
2305 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2306 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2307 if (sbQuery != null) {
Mathew Inwood9ad1eac2011-09-15 11:29:50 +01002308 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002309 // Could not submit query. Fallback to regular tab creation
2310 tabControl.destroy();
2311 return null;
2312 }
2313 }
Michael Kolbff6a7482011-07-26 16:37:15 -07002314 // check tab count and make room for new tab
2315 if (!mTabControl.canCreateNewTab()) {
2316 Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
2317 if (leastUsed != null) {
2318 closeTab(leastUsed);
2319 }
2320 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002321 Tab t = tabControl.getTab();
Mathew Inwoode09305e2011-09-02 12:03:26 +01002322 t.refreshIdAfterPreload();
Mathew Inwood29721c22011-06-29 17:55:24 +01002323 mTabControl.addPreloadedTab(t);
2324 addTab(t);
2325 setActiveTab(t);
2326 return t;
2327 }
2328
Michael Kolb7bcafde2011-05-09 13:55:59 -07002329 // open a non inconito tab with the given url data
2330 // and set as active tab
2331 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002332 Tab tab = showPreloadedTab(urlData);
2333 if (tab == null) {
2334 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002335 if ((tab != null) && !urlData.isEmpty()) {
2336 loadUrlDataIn(tab, urlData);
2337 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002338 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002339 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002340 }
2341
Michael Kolb843510f2010-12-09 10:51:49 -08002342 @Override
2343 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002344 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002345 }
2346
Michael Kolb8233fac2010-10-26 16:08:53 -07002347 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002348 public Tab openIncognitoTab() {
2349 return openTab(INCOGNITO_URI, true, true, false);
2350 }
2351
2352 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002353 public Tab openTab(String url, boolean incognito, boolean setActive,
2354 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002355 return openTab(url, incognito, setActive, useCurrent, null);
2356 }
2357
2358 @Override
2359 public Tab openTab(String url, Tab parent, boolean setActive,
2360 boolean useCurrent) {
2361 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2362 setActive, useCurrent, parent);
2363 }
2364
2365 public Tab openTab(String url, boolean incognito, boolean setActive,
2366 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002367 Tab tab = createNewTab(incognito, setActive, useCurrent);
2368 if (tab != null) {
John Reck5949c662011-05-27 09:52:29 -07002369 if (parent != null && parent != tab) {
2370 parent.addChildTab(tab);
2371 }
Michael Kolb519d2282011-05-09 17:03:19 -07002372 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002373 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002374 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002375 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002376 return tab;
2377 }
2378
2379 // this method will attempt to create a new tab
2380 // incognito: private browsing tab
2381 // setActive: ste tab as current tab
2382 // useCurrent: if no new tab can be created, return current tab
2383 private Tab createNewTab(boolean incognito, boolean setActive,
2384 boolean useCurrent) {
2385 Tab tab = null;
2386 if (mTabControl.canCreateNewTab()) {
2387 tab = mTabControl.createNewTab(incognito);
2388 addTab(tab);
2389 if (setActive) {
2390 setActiveTab(tab);
2391 }
2392 } else {
2393 if (useCurrent) {
2394 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002395 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002396 } else {
2397 mUi.showMaxTabsWarning();
2398 }
2399 }
2400 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002401 }
2402
John Reck2bc80422011-06-30 15:11:49 -07002403 @Override
2404 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2405 SnapshotTab tab = null;
2406 if (mTabControl.canCreateNewTab()) {
2407 tab = mTabControl.createSnapshotTab(snapshotId);
2408 addTab(tab);
2409 if (setActive) {
2410 setActiveTab(tab);
2411 }
2412 } else {
2413 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07002414 }
2415 return tab;
2416 }
2417
Michael Kolb8233fac2010-10-26 16:08:53 -07002418 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002419 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002420 * @return boolean True if we successfully switched to a different tab. If
2421 * the indexth tab is null, or if that tab is the same as
2422 * the current one, return false.
2423 */
2424 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002425 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002426 Tab currentTab = mTabControl.getCurrentTab();
2427 if (tab == null || tab == currentTab) {
2428 return false;
2429 }
2430 setActiveTab(tab);
2431 return true;
2432 }
2433
2434 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002435 public void closeCurrentTab() {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002436 closeCurrentTab(false);
2437 }
2438
2439 protected void closeCurrentTab(boolean andQuit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002440 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07002441 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07002442 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08002443 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002444 return;
2445 }
Michael Kolbc831b632011-05-11 09:30:34 -07002446 final Tab current = mTabControl.getCurrentTab();
2447 final int pos = mTabControl.getCurrentPosition();
2448 Tab newTab = current.getParent();
2449 if (newTab == null) {
2450 newTab = mTabControl.getTab(pos + 1);
2451 if (newTab == null) {
2452 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002453 }
2454 }
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002455 if (andQuit) {
2456 mTabControl.setCurrentTab(newTab);
2457 closeTab(current);
2458 } else if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002459 // Close window
2460 closeTab(current);
2461 }
2462 }
2463
2464 /**
2465 * Close the tab, remove its associated title bar, and adjust mTabControl's
2466 * current tab to a valid value.
2467 */
2468 @Override
2469 public void closeTab(Tab tab) {
John Reck28263772011-10-11 17:13:42 -07002470 if (tab == mTabControl.getCurrentTab()) {
2471 closeCurrentTab();
2472 } else {
2473 removeTab(tab);
2474 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002475 }
2476
Michael Kolb8233fac2010-10-26 16:08:53 -07002477 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07002478 protected void loadUrlFromContext(String url) {
2479 Tab tab = getCurrentTab();
2480 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002481 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07002482 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002483 url = UrlUtils.smartUrlFilter(url);
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002484 if (!WebViewClassic.fromWebView(view).getWebViewClient().
2485 shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07002486 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07002487 }
2488 }
2489 }
2490
2491 /**
2492 * Load the URL into the given WebView and update the title bar
2493 * to reflect the new load. Call this instead of WebView.loadUrl
2494 * directly.
2495 * @param view The WebView used to load url.
2496 * @param url The URL to load.
2497 */
John Reck71e51422011-07-01 16:49:28 -07002498 @Override
2499 public void loadUrl(Tab tab, String url) {
John Reck26b18322011-06-21 13:08:58 -07002500 loadUrl(tab, url, null);
2501 }
2502
2503 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
2504 if (tab != null) {
2505 dismissSubWindow(tab);
2506 tab.loadUrl(url, headers);
Michael Kolba53c9892011-10-05 13:31:40 -07002507 mUi.onProgressChanged(tab);
John Reck26b18322011-06-21 13:08:58 -07002508 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002509 }
2510
2511 /**
2512 * Load UrlData into a Tab and update the title bar to reflect the new
2513 * load. Call this instead of UrlData.loadIn directly.
2514 * @param t The Tab used to load.
2515 * @param data The UrlData being loaded.
2516 */
2517 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07002518 if (data != null) {
Michael Kolb5ff5c8b2012-05-03 11:37:58 -07002519 if (data.isPreloaded()) {
Michael Kolb14612442011-06-24 13:06:29 -07002520 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07002521 } else {
2522 loadUrl(t, data.mUrl, data.mHeaders);
2523 }
2524 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002525 }
2526
John Reck30c714c2010-12-16 17:30:34 -08002527 @Override
2528 public void onUserCanceledSsl(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08002529 // TODO: Figure out the "right" behavior
John Reckef654f12011-07-12 16:42:08 -07002530 if (tab.canGoBack()) {
2531 tab.goBack();
John Reck30c714c2010-12-16 17:30:34 -08002532 } else {
John Reckef654f12011-07-12 16:42:08 -07002533 tab.loadUrl(mSettings.getHomePage(), null);
John Reck30c714c2010-12-16 17:30:34 -08002534 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002535 }
2536
2537 void goBackOnePageOrQuit() {
2538 Tab current = mTabControl.getCurrentTab();
2539 if (current == null) {
2540 /*
2541 * Instead of finishing the activity, simply push this to the back
2542 * of the stack and let ActivityManager to choose the foreground
2543 * activity. As BrowserActivity is singleTask, it will be always the
2544 * root of the task. So we can use either true or false for
2545 * moveTaskToBack().
2546 */
2547 mActivity.moveTaskToBack(true);
2548 return;
2549 }
John Reckef654f12011-07-12 16:42:08 -07002550 if (current.canGoBack()) {
2551 current.goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07002552 } else {
2553 // Check to see if we are closing a window that was created by
2554 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002555 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002556 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002557 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002558 // Now we close the other tab
2559 closeTab(current);
2560 } else {
Michael Kolbe28b3472011-08-04 16:54:31 -07002561 if ((current.getAppId() != null) || current.closeOnBack()) {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002562 closeCurrentTab(true);
Michael Kolbe28b3472011-08-04 16:54:31 -07002563 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002564 /*
2565 * Instead of finishing the activity, simply push this to the back
2566 * of the stack and let ActivityManager to choose the foreground
2567 * activity. As BrowserActivity is singleTask, it will be always the
2568 * root of the task. So we can use either true or false for
2569 * moveTaskToBack().
2570 */
2571 mActivity.moveTaskToBack(true);
2572 }
2573 }
2574 }
2575
2576 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002577 * helper method for key handler
2578 * returns the current tab if it can't advance
2579 */
Michael Kolbc831b632011-05-11 09:30:34 -07002580 private Tab getNextTab() {
Michael Kolbf5261da2011-12-15 15:07:35 -08002581 int pos = mTabControl.getCurrentPosition() + 1;
2582 if (pos >= mTabControl.getTabCount()) {
2583 pos = 0;
2584 }
2585 return mTabControl.getTab(pos);
Michael Kolb0035fad2011-03-14 13:25:28 -07002586 }
2587
2588 /**
2589 * helper method for key handler
2590 * returns the current tab if it can't advance
2591 */
Michael Kolbc831b632011-05-11 09:30:34 -07002592 private Tab getPrevTab() {
Michael Kolbf5261da2011-12-15 15:07:35 -08002593 int pos = mTabControl.getCurrentPosition() - 1;
2594 if ( pos < 0) {
2595 pos = mTabControl.getTabCount() - 1;
2596 }
2597 return mTabControl.getTab(pos);
Michael Kolb0035fad2011-03-14 13:25:28 -07002598 }
2599
John Reckbcef87f2012-02-03 14:58:34 -08002600 boolean isMenuOrCtrlKey(int keyCode) {
2601 return (KeyEvent.KEYCODE_MENU == keyCode)
2602 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2603 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode);
2604 }
2605
Michael Kolb0035fad2011-03-14 13:25:28 -07002606 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002607 * handle key events in browser
2608 *
2609 * @param keyCode
2610 * @param event
2611 * @return true if handled, false to pass to super
2612 */
2613 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002614 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002615 // Even if MENU is already held down, we need to call to super to open
2616 // the IME on long press.
John Reckbcef87f2012-02-03 14:58:34 -08002617 if (!noModifiers && isMenuOrCtrlKey(keyCode)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002618 mMenuIsDown = true;
2619 return false;
2620 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002621
Cary Clark8ff8c662010-12-29 15:03:05 -05002622 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07002623 Tab tab = getCurrentTab();
2624 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05002625
Cary Clark160bbb92011-01-10 11:17:07 -05002626 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2627 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002628
Michael Kolb8233fac2010-10-26 16:08:53 -07002629 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002630 case KeyEvent.KEYCODE_TAB:
2631 if (event.isCtrlPressed()) {
2632 if (event.isShiftPressed()) {
2633 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002634 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002635 } else {
2636 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002637 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002638 }
2639 return true;
2640 }
2641 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002642 case KeyEvent.KEYCODE_SPACE:
2643 // WebView/WebTextView handle the keys in the KeyDown. As
2644 // the Activity's shortcut keys are only handled when WebView
2645 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002646 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002647 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002648 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002649 pageDown();
2650 }
2651 return true;
2652 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002653 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002654 event.startTracking();
2655 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07002656 case KeyEvent.KEYCODE_FORWARD:
2657 if (!noModifiers) break;
2658 tab.goForward();
2659 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002660 case KeyEvent.KEYCODE_DPAD_LEFT:
2661 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002662 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05002663 return true;
2664 }
2665 break;
2666 case KeyEvent.KEYCODE_DPAD_RIGHT:
2667 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002668 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05002669 return true;
2670 }
2671 break;
2672 case KeyEvent.KEYCODE_A:
2673 if (ctrl) {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002674 WebViewClassic.fromWebView(webView).selectAll();
Cary Clark8ff8c662010-12-29 15:03:05 -05002675 return true;
2676 }
2677 break;
Michael Kolba4183062011-01-16 10:43:21 -08002678// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002679 case KeyEvent.KEYCODE_C:
2680 if (ctrl) {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002681 WebViewClassic.fromWebView(webView).copySelection();
Cary Clark8ff8c662010-12-29 15:03:05 -05002682 return true;
2683 }
2684 break;
Michael Kolba4183062011-01-16 10:43:21 -08002685// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002686// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002687// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002688// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002689// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002690// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002691// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002692// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002693// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002694// case KeyEvent.KEYCODE_M: // unused
2695// case KeyEvent.KEYCODE_N: // in Chrome: new window
2696// case KeyEvent.KEYCODE_O: // in Chrome: open file
2697// case KeyEvent.KEYCODE_P: // in Chrome: print page
2698// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002699// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002700// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2701 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002702 // we can't use the ctrl/shift flags, they check for
2703 // exclusive use of a modifier
2704 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002705 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002706 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002707 } else {
2708 openTabToHomePage();
2709 }
2710 return true;
2711 }
2712 break;
2713// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2714// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb5ae15bd2011-08-16 17:09:27 -07002715// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002716// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2717// case KeyEvent.KEYCODE_Y: // unused
2718// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002719 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002720 // it is a regular key and webview is not null
2721 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002722 }
2723
John Recke6bf4ab2011-02-24 15:48:05 -08002724 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2725 switch(keyCode) {
2726 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07002727 if (mUi.isWebShowing()) {
Michael Kolb315d5022011-10-13 12:47:11 -07002728 bookmarksOrHistoryPicker(ComboViews.History);
John Recke6bf4ab2011-02-24 15:48:05 -08002729 return true;
2730 }
2731 break;
2732 }
2733 return false;
2734 }
2735
Michael Kolb8233fac2010-10-26 16:08:53 -07002736 boolean onKeyUp(int keyCode, KeyEvent event) {
John Reckbcef87f2012-02-03 14:58:34 -08002737 if (isMenuOrCtrlKey(keyCode)) {
Michael Kolb2814a362011-05-19 15:49:41 -07002738 mMenuIsDown = false;
John Reckbcef87f2012-02-03 14:58:34 -08002739 if (KeyEvent.KEYCODE_MENU == keyCode
2740 && event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002741 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002742 }
2743 }
Cary Clark160bbb92011-01-10 11:17:07 -05002744 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002745 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002746 case KeyEvent.KEYCODE_BACK:
2747 if (event.isTracking() && !event.isCanceled()) {
2748 onBackKey();
2749 return true;
2750 }
2751 break;
2752 }
2753 return false;
2754 }
2755
2756 public boolean isMenuDown() {
2757 return mMenuIsDown;
2758 }
2759
Ben Murdoch8029a772010-11-16 11:58:21 +00002760 public void setupAutoFill(Message message) {
2761 // Open the settings activity at the AutoFill profile fragment so that
2762 // the user can create a new profile. When they return, we will dispatch
2763 // the message so that we can autofill the form using their new profile.
2764 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2765 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2766 AutoFillSettingsFragment.class.getName());
2767 mAutoFillSetupMessage = message;
2768 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2769 }
John Reckb3417f02011-01-14 11:01:05 -08002770
Michael Kolbfbc579a2011-07-07 15:59:33 -07002771 public boolean onSearchRequested() {
Michael Kolb1f9b3562012-04-24 14:38:34 -07002772 mUi.editUrl(false, true);
Michael Kolbfbc579a2011-07-07 15:59:33 -07002773 return true;
2774 }
2775
John Reck1cf4b792011-07-26 10:22:22 -07002776 @Override
2777 public boolean shouldCaptureThumbnails() {
2778 return mUi.shouldCaptureThumbnails();
2779 }
2780
Michael Kolbc3af0672011-08-09 10:24:41 -07002781 @Override
2782 public void setBlockEvents(boolean block) {
2783 mBlockEvents = block;
2784 }
2785
2786 public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002787 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002788 }
2789
2790 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002791 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002792 }
2793
2794 public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002795 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002796 }
2797
2798 public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002799 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002800 }
2801
2802 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002803 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002804 }
2805
Michael Kolb8233fac2010-10-26 16:08:53 -07002806}