blob: 8dc05f8f5bc074a5134e5f3b7dc176326a4ad039 [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;
20import android.app.DownloadManager;
21import android.app.SearchManager;
22import android.content.ClipboardManager;
23import android.content.ContentProvider;
24import android.content.ContentProviderClient;
25import android.content.ContentResolver;
John Reckd8c74522011-06-14 08:45:00 -070026import android.content.ContentUris;
Michael Kolb8233fac2010-10-26 16:08:53 -070027import android.content.ContentValues;
28import android.content.Context;
29import android.content.Intent;
30import android.content.pm.PackageManager;
31import android.content.pm.ResolveInfo;
32import android.content.res.Configuration;
John Reck30b065e2011-07-19 10:58:05 -070033import android.content.res.TypedArray;
Leon Scroggins1961ed22010-12-07 15:22:21 -050034import android.database.ContentObserver;
Michael Kolb8233fac2010-10-26 16:08:53 -070035import android.database.Cursor;
36import android.database.sqlite.SQLiteDatabase;
Michael Kolb8233fac2010-10-26 16:08:53 -070037import android.graphics.Bitmap;
38import android.graphics.Canvas;
Michael Kolb8233fac2010-10-26 16:08:53 -070039import android.net.Uri;
40import android.net.http.SslError;
41import android.os.AsyncTask;
42import android.os.Bundle;
George Mount387d45d2011-10-07 15:57:53 -070043import android.os.Environment;
Michael Kolb8233fac2010-10-26 16:08:53 -070044import android.os.Handler;
45import android.os.Message;
46import android.os.PowerManager;
47import android.os.PowerManager.WakeLock;
Ben Murdoch8029a772010-11-16 11:58:21 +000048import android.preference.PreferenceActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -070049import android.provider.Browser;
50import android.provider.BrowserContract;
Michael Kolb8233fac2010-10-26 16:08:53 -070051import android.provider.BrowserContract.Images;
52import android.provider.ContactsContract;
53import android.provider.ContactsContract.Intents.Insert;
Michael Kolbcfa3af52010-12-14 10:36:11 -080054import android.speech.RecognizerIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070055import android.text.TextUtils;
56import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080057import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070058import android.view.ActionMode;
59import android.view.ContextMenu;
60import android.view.ContextMenu.ContextMenuInfo;
61import android.view.Gravity;
62import android.view.KeyEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070063import android.view.Menu;
64import android.view.MenuInflater;
65import android.view.MenuItem;
66import android.view.MenuItem.OnMenuItemClickListener;
Michael Kolbc3af0672011-08-09 10:24:41 -070067import android.view.MotionEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070068import android.view.View;
69import android.webkit.CookieManager;
70import android.webkit.CookieSyncManager;
71import android.webkit.HttpAuthHandler;
George Mount387d45d2011-10-07 15:57:53 -070072import android.webkit.MimeTypeMap;
Michael Kolb8233fac2010-10-26 16:08:53 -070073import android.webkit.SslErrorHandler;
74import android.webkit.ValueCallback;
75import android.webkit.WebChromeClient;
76import android.webkit.WebIconDatabase;
77import android.webkit.WebSettings;
78import android.webkit.WebView;
Leon Scrogginsac993842011-02-02 12:54:07 -050079import android.widget.Toast;
Michael Kolb8233fac2010-10-26 16:08:53 -070080
Michael Kolb4bd767d2011-05-27 11:33:55 -070081import com.android.browser.IntentHandler.UrlData;
John Reck2bc80422011-06-30 15:11:49 -070082import com.android.browser.UI.ComboViews;
Michael Kolb4bd767d2011-05-27 11:33:55 -070083import com.android.browser.provider.BrowserProvider;
John Reck1cf4b792011-07-26 10:22:22 -070084import com.android.browser.provider.BrowserProvider2.Thumbnails;
John Reck8cc92352011-07-06 17:41:52 -070085import com.android.browser.provider.SnapshotProvider.Snapshots;
Michael Kolb4bd767d2011-05-27 11:33:55 -070086import com.android.browser.search.SearchEngine;
87import com.android.common.Search;
88
Michael Kolb8233fac2010-10-26 16:08:53 -070089import java.io.ByteArrayOutputStream;
George Mount387d45d2011-10-07 15:57:53 -070090import java.io.File;
91import java.io.FileOutputStream;
92import java.io.IOException;
Michael Kolb8233fac2010-10-26 16:08:53 -070093import java.net.URLEncoder;
George Mount387d45d2011-10-07 15:57:53 -070094import java.text.DateFormat;
95import java.text.SimpleDateFormat;
John Reck1cf4b792011-07-26 10:22:22 -070096import java.util.ArrayList;
Michael Kolb8233fac2010-10-26 16:08:53 -070097import java.util.Calendar;
George Mount387d45d2011-10-07 15:57:53 -070098import java.util.Date;
Michael Kolb8233fac2010-10-26 16:08:53 -070099import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -0800100import java.util.List;
John Reck26b18322011-06-21 13:08:58 -0700101import java.util.Map;
Michael Kolb8233fac2010-10-26 16:08:53 -0700102
103/**
104 * Controller for browser
105 */
106public class Controller
107 implements WebViewController, UiController {
108
109 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800110 private static final String SEND_APP_ID_EXTRA =
111 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
Michael Kolba4261fd2011-05-05 11:27:37 -0700112 private static final String INCOGNITO_URI = "browser:incognito";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800113
Michael Kolb8233fac2010-10-26 16:08:53 -0700114
115 // public message ids
116 public final static int LOAD_URL = 1001;
117 public final static int STOP_LOAD = 1002;
118
119 // Message Ids
120 private static final int FOCUS_NODE_HREF = 102;
121 private static final int RELEASE_WAKELOCK = 107;
122
123 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
124
125 private static final int OPEN_BOOKMARKS = 201;
126
127 private static final int EMPTY_MENU = -1;
128
Michael Kolb8233fac2010-10-26 16:08:53 -0700129 // activity requestCode
John Reckd3e4d5b2011-07-13 15:48:43 -0700130 final static int COMBO_VIEW = 1;
Michael Kolb8233fac2010-10-26 16:08:53 -0700131 final static int PREFERENCES_PAGE = 3;
132 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000133 final static int AUTOFILL_SETUP = 5;
134
Michael Kolb8233fac2010-10-26 16:08:53 -0700135 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
136
137 // As the ids are dynamically created, we can't guarantee that they will
138 // be in sequence, so this static array maps ids to a window number.
139 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
140 { R.id.window_one_menu_id, R.id.window_two_menu_id,
141 R.id.window_three_menu_id, R.id.window_four_menu_id,
142 R.id.window_five_menu_id, R.id.window_six_menu_id,
143 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
144
145 // "source" parameter for Google search through search key
146 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
147 // "source" parameter for Google search through simplily type
148 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
149
George Mount387d45d2011-10-07 15:57:53 -0700150 // "no-crash-recovery" parameter in intent to suppress crash recovery
Guang Zhu9e78f512011-05-04 11:45:11 -0700151 final static String NO_CRASH_RECOVERY = "no-crash-recovery";
152
John Reckd7dd9b22011-08-30 09:18:29 -0700153 // A bitmap that is re-used in createScreenshot as scratch space
154 private static Bitmap sThumbnailBitmap;
155
Michael Kolb8233fac2010-10-26 16:08:53 -0700156 private Activity mActivity;
157 private UI mUi;
158 private TabControl mTabControl;
159 private BrowserSettings mSettings;
160 private WebViewFactory mFactory;
161
162 private WakeLock mWakeLock;
163
164 private UrlHandler mUrlHandler;
165 private UploadHandler mUploadHandler;
166 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700167 private PageDialogsHandler mPageDialogsHandler;
168 private NetworkStateHandler mNetworkHandler;
169
Ben Murdoch8029a772010-11-16 11:58:21 +0000170 private Message mAutoFillSetupMessage;
171
Michael Kolb8233fac2010-10-26 16:08:53 -0700172 private boolean mShouldShowErrorConsole;
173
174 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
175
176 // FIXME, temp address onPrepareMenu performance problem.
177 // When we move everything out of view, we should rewrite this.
178 private int mCurrentMenuState = 0;
179 private int mMenuState = R.id.MAIN_MENU;
180 private int mOldMenuState = EMPTY_MENU;
181 private Menu mCachedMenu;
182
Michael Kolb8233fac2010-10-26 16:08:53 -0700183 private boolean mMenuIsDown;
184
185 // For select and find, we keep track of the ActionMode so that
186 // finish() can be called as desired.
187 private ActionMode mActionMode;
188
189 /**
190 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
191 * of whether the configuration has changed. The first onMenuOpened call
192 * after a configuration change is simply a reopening of the same menu
193 * (i.e. mIconView did not change).
194 */
195 private boolean mConfigChanged;
196
197 /**
198 * Keeps track of whether the options menu is open. This is important in
199 * determining whether to show or hide the title bar overlay
200 */
201 private boolean mOptionsMenuOpen;
202
203 /**
204 * Whether or not the options menu is in its bigger, popup menu form. When
205 * true, we want the title bar overlay to be gone. When false, we do not.
206 * Only meaningful if mOptionsMenuOpen is true.
207 */
208 private boolean mExtendedMenuOpen;
209
Michael Kolb8233fac2010-10-26 16:08:53 -0700210 private boolean mActivityPaused = true;
211 private boolean mLoadStopped;
212
213 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500214 // Checks to see when the bookmarks database has changed, and updates the
215 // Tabs' notion of whether they represent bookmarked sites.
216 private ContentObserver mBookmarksObserver;
John Reck847b5322011-04-14 17:02:18 -0700217 private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700218
Michael Kolbc3af0672011-08-09 10:24:41 -0700219 private boolean mBlockEvents;
220
John Reckbc490d22011-07-22 15:04:59 -0700221 public Controller(Activity browser, boolean preloadCrashState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700222 mActivity = browser;
223 mSettings = BrowserSettings.getInstance();
224 mTabControl = new TabControl(this);
225 mSettings.setController(this);
John Reck378a4102011-06-09 16:23:01 -0700226 mCrashRecoveryHandler = CrashRecoveryHandler.initialize(this);
John Reckbc490d22011-07-22 15:04:59 -0700227 if (preloadCrashState) {
228 mCrashRecoveryHandler.preloadCrashState();
229 }
Michael Kolb14612442011-06-24 13:06:29 -0700230 mFactory = new BrowserWebViewFactory(browser);
Michael Kolb8233fac2010-10-26 16:08:53 -0700231
232 mUrlHandler = new UrlHandler(this);
233 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700234 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
235
Michael Kolb8233fac2010-10-26 16:08:53 -0700236 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500237 mBookmarksObserver = new ContentObserver(mHandler) {
238 @Override
239 public void onChange(boolean selfChange) {
240 int size = mTabControl.getTabCount();
241 for (int i = 0; i < size; i++) {
242 mTabControl.getTab(i).updateBookmarkedStatus();
243 }
244 }
245
246 };
247 browser.getContentResolver().registerContentObserver(
248 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700249
250 mNetworkHandler = new NetworkStateHandler(mActivity, this);
251 // Start watching the default geolocation permissions
252 mSystemAllowGeolocationOrigins =
253 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
254 mSystemAllowGeolocationOrigins.start();
255
John Reckaf262e72011-07-25 13:55:44 -0700256 openIconDatabase();
Michael Kolb8233fac2010-10-26 16:08:53 -0700257 }
258
Patrick Scott7d50a932011-02-04 09:27:26 -0500259 void start(final Bundle icicle, final Intent intent) {
Guang Zhu9e78f512011-05-04 11:45:11 -0700260 boolean noCrashRecovery = intent.getBooleanExtra(NO_CRASH_RECOVERY, false);
261 if (icicle != null || noCrashRecovery) {
Michael Kolb938db802011-10-11 10:49:05 -0700262 doStart(icicle, intent, false);
John Reck847b5322011-04-14 17:02:18 -0700263 } else {
264 mCrashRecoveryHandler.startRecovery(intent);
265 }
266 }
267
Michael Kolb938db802011-10-11 10:49:05 -0700268 void doStart(final Bundle icicle, final Intent intent, final boolean fromCrash) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700269 // Unless the last browser usage was within 24 hours, destroy any
270 // remaining incognito tabs.
271
272 Calendar lastActiveDate = icicle != null ?
273 (Calendar) icicle.getSerializable("lastActiveDate") : null;
274 Calendar today = Calendar.getInstance();
275 Calendar yesterday = Calendar.getInstance();
276 yesterday.add(Calendar.DATE, -1);
277
Patrick Scott7d50a932011-02-04 09:27:26 -0500278 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700279 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800280 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700281
Patrick Scott7d50a932011-02-04 09:27:26 -0500282 // Find out if we will restore any state and remember the tab.
Michael Kolbc831b632011-05-11 09:30:34 -0700283 final long currentTabId =
Patrick Scott7d50a932011-02-04 09:27:26 -0500284 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000285
Michael Kolbc831b632011-05-11 09:30:34 -0700286 if (currentTabId == -1) {
Patrick Scott7d50a932011-02-04 09:27:26 -0500287 // Not able to restore so we go ahead and clear session cookies. We
288 // must do this before trying to login the user as we don't want to
289 // clear any session cookies set during login.
290 CookieManager.getInstance().removeSessionCookie();
291 }
292
Patrick Scottd43e75a2011-03-14 14:47:23 -0400293 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500294 new Runnable() {
295 @Override public void run() {
Michael Kolb938db802011-10-11 10:49:05 -0700296 onPreloginFinished(icicle, intent, currentTabId, restoreIncognitoTabs,
297 fromCrash);
Patrick Scott7d50a932011-02-04 09:27:26 -0500298 }
299 });
300 }
301
Michael Kolbc831b632011-05-11 09:30:34 -0700302 private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId,
Michael Kolb938db802011-10-11 10:49:05 -0700303 boolean restoreIncognitoTabs, boolean fromCrash) {
Michael Kolbc831b632011-05-11 09:30:34 -0700304 if (currentTabId == -1) {
John Reck1cf4b792011-07-26 10:22:22 -0700305 BackgroundHandler.execute(new PruneThumbnails(mActivity, null));
Michael Kolb8233fac2010-10-26 16:08:53 -0700306 final Bundle extra = intent.getExtras();
307 // Create an initial tab.
308 // If the intent is ACTION_VIEW and data is not null, the Browser is
309 // invoked to view the content by another application. In this case,
310 // the tab will be close when exit.
Michael Kolb14612442011-06-24 13:06:29 -0700311 UrlData urlData = IntentHandler.getUrlDataFromIntent(intent);
Michael Kolb7bcafde2011-05-09 13:55:59 -0700312 Tab t = null;
313 if (urlData.isEmpty()) {
314 t = openTabToHomePage();
315 } else {
316 t = openTab(urlData);
317 }
318 if (t != null) {
319 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
320 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700321 WebView webView = t.getWebView();
322 if (extra != null) {
323 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
324 if (scale > 0 && scale <= 1000) {
325 webView.setInitialScale(scale);
326 }
327 }
John Reckd8c74522011-06-14 08:45:00 -0700328 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700329 } else {
Michael Kolbc831b632011-05-11 09:30:34 -0700330 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
Patrick Scott7d50a932011-02-04 09:27:26 -0500331 mUi.needsRestoreAllTabs());
John Reck1cf4b792011-07-26 10:22:22 -0700332 List<Tab> tabs = mTabControl.getTabs();
333 ArrayList<Long> restoredTabs = new ArrayList<Long>(tabs.size());
334 for (Tab t : tabs) {
335 restoredTabs.add(t.getId());
336 }
337 BackgroundHandler.execute(new PruneThumbnails(mActivity, restoredTabs));
John Reck52be4782011-08-26 15:37:29 -0700338 if (tabs.size() == 0) {
339 openTabToHomePage();
340 }
John Reck1cf4b792011-07-26 10:22:22 -0700341 mUi.updateTabs(tabs);
Michael Kolb8233fac2010-10-26 16:08:53 -0700342 // TabControl.restoreState() will create a new tab even if
343 // restoring the state fails.
344 setActiveTab(mTabControl.getCurrentTab());
John Reck9dd4a412011-10-05 14:55:30 -0700345 // Handle the intent if needed. If icicle != null, we are restoring
346 // and the intent will be stale - ignore it.
Michael Kolb938db802011-10-11 10:49:05 -0700347 if (icicle == null || fromCrash) {
John Reck9dd4a412011-10-05 14:55:30 -0700348 mIntentHandler.onNewIntent(intent);
349 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700350 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700351 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700352 String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb8233fac2010-10-26 16:08:53 -0700353 if (jsFlags.trim().length() != 0) {
354 getCurrentWebView().setJsFlags(jsFlags);
355 }
John Reck439c9a52010-12-14 10:04:39 -0800356 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
Michael Kolb315d5022011-10-13 12:47:11 -0700357 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
John Reck439c9a52010-12-14 10:04:39 -0800358 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700359 }
360
John Reck1cf4b792011-07-26 10:22:22 -0700361 private static class PruneThumbnails implements Runnable {
362 private Context mContext;
363 private List<Long> mIds;
364
365 PruneThumbnails(Context context, List<Long> preserveIds) {
366 mContext = context.getApplicationContext();
367 mIds = preserveIds;
368 }
369
370 @Override
371 public void run() {
372 ContentResolver cr = mContext.getContentResolver();
373 if (mIds == null || mIds.size() == 0) {
374 cr.delete(Thumbnails.CONTENT_URI, null, null);
375 } else {
376 int length = mIds.size();
377 StringBuilder where = new StringBuilder();
378 where.append(Thumbnails._ID);
379 where.append(" not in (");
380 for (int i = 0; i < length; i++) {
381 where.append(mIds.get(i));
382 if (i < (length - 1)) {
383 where.append(",");
384 }
385 }
386 where.append(")");
387 cr.delete(Thumbnails.CONTENT_URI, where.toString(), null);
388 }
389 }
390
391 }
392
Michael Kolb1514bb72010-11-22 09:11:48 -0800393 @Override
394 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700395 return mFactory;
396 }
397
398 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800399 public void onSetWebView(Tab tab, WebView view) {
400 mUi.onSetWebView(tab, view);
401 }
402
403 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800404 public void createSubWindow(Tab tab) {
405 endActionMode();
406 WebView mainView = tab.getWebView();
407 WebView subView = mFactory.createWebView((mainView == null)
408 ? false
409 : mainView.isPrivateBrowsingEnabled());
410 mUi.createSubWindow(tab, subView);
411 }
412
413 @Override
Michael Kolb14612442011-06-24 13:06:29 -0700414 public Context getContext() {
415 return mActivity;
416 }
417
418 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700419 public Activity getActivity() {
420 return mActivity;
421 }
422
423 void setUi(UI ui) {
424 mUi = ui;
425 }
426
427 BrowserSettings getSettings() {
428 return mSettings;
429 }
430
431 IntentHandler getIntentHandler() {
432 return mIntentHandler;
433 }
434
435 @Override
436 public UI getUi() {
437 return mUi;
438 }
439
440 int getMaxTabs() {
441 return mActivity.getResources().getInteger(R.integer.max_tabs);
442 }
443
444 @Override
445 public TabControl getTabControl() {
446 return mTabControl;
447 }
448
Michael Kolb1bf23132010-11-19 12:55:12 -0800449 @Override
450 public List<Tab> getTabs() {
451 return mTabControl.getTabs();
452 }
453
John Reckaf262e72011-07-25 13:55:44 -0700454 // Open the icon database.
455 private void openIconDatabase() {
456 // We have to call getInstance on the UI thread
457 final WebIconDatabase instance = WebIconDatabase.getInstance();
458 BackgroundHandler.execute(new Runnable() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000459
John Reckaf262e72011-07-25 13:55:44 -0700460 @Override
461 public void run() {
462 instance.open(mActivity.getDir("icons", 0).getPath());
Michael Kolb8233fac2010-10-26 16:08:53 -0700463 }
John Reckaf262e72011-07-25 13:55:44 -0700464 });
Michael Kolb8233fac2010-10-26 16:08:53 -0700465 }
466
467 private void startHandler() {
468 mHandler = new Handler() {
469
470 @Override
471 public void handleMessage(Message msg) {
472 switch (msg.what) {
473 case OPEN_BOOKMARKS:
Michael Kolb315d5022011-10-13 12:47:11 -0700474 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
Michael Kolb8233fac2010-10-26 16:08:53 -0700475 break;
476 case FOCUS_NODE_HREF:
477 {
478 String url = (String) msg.getData().get("url");
479 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500480 String src = (String) msg.getData().get("src");
481 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700482 if (TextUtils.isEmpty(url)) {
483 break;
484 }
485 HashMap focusNodeMap = (HashMap) msg.obj;
486 WebView view = (WebView) focusNodeMap.get("webview");
487 // Only apply the action if the top window did not change.
488 if (getCurrentTopWebView() != view) {
489 break;
490 }
491 switch (msg.arg1) {
492 case R.id.open_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700493 loadUrlFromContext(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700494 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500495 case R.id.view_image_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700496 loadUrlFromContext(src);
Cary Clark043c2d62010-12-15 11:19:39 -0500497 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500498 case R.id.open_newtab_context_menu_id:
499 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -0700500 openTab(url, parent,
501 !mSettings.openInBackground(), true);
Leon Scroggins026f2542010-11-22 13:26:12 -0500502 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700503 case R.id.copy_link_context_menu_id:
504 copy(url);
505 break;
506 case R.id.save_link_context_menu_id:
507 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500508 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000509 mActivity, url, null, null, null,
510 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700511 break;
512 }
513 break;
514 }
515
516 case LOAD_URL:
John Reck26b18322011-06-21 13:08:58 -0700517 loadUrlFromContext((String) msg.obj);
Michael Kolb8233fac2010-10-26 16:08:53 -0700518 break;
519
520 case STOP_LOAD:
521 stopLoading();
522 break;
523
524 case RELEASE_WAKELOCK:
John Reckf57c0292011-07-21 18:15:39 -0700525 if (mWakeLock != null && mWakeLock.isHeld()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700526 mWakeLock.release();
527 // if we reach here, Browser should be still in the
528 // background loading after WAKELOCK_TIMEOUT (5-min).
529 // To avoid burning the battery, stop loading.
530 mTabControl.stopAllLoading();
531 }
532 break;
533
534 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800535 Tab tab = (Tab) msg.obj;
536 if (tab != null) {
537 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700538 }
539 break;
540 }
541 }
542 };
543
544 }
545
John Reckef654f12011-07-12 16:42:08 -0700546 @Override
Martijn Coenenb2f93552011-06-14 10:48:35 +0200547 public Tab getCurrentTab() {
548 return mTabControl.getCurrentTab();
549 }
550
Michael Kolbba99c5d2010-11-29 14:57:41 -0800551 @Override
552 public void shareCurrentPage() {
553 shareCurrentPage(mTabControl.getCurrentTab());
554 }
555
556 private void shareCurrentPage(Tab tab) {
557 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800558 sharePage(mActivity, tab.getTitle(),
559 tab.getUrl(), tab.getFavicon(),
560 createScreenshot(tab.getWebView(),
561 getDesiredThumbnailWidth(mActivity),
562 getDesiredThumbnailHeight(mActivity)));
563 }
564 }
565
Michael Kolb8233fac2010-10-26 16:08:53 -0700566 /**
567 * Share a page, providing the title, url, favicon, and a screenshot. Uses
568 * an {@link Intent} to launch the Activity chooser.
569 * @param c Context used to launch a new Activity.
570 * @param title Title of the page. Stored in the Intent with
571 * {@link Intent#EXTRA_SUBJECT}
572 * @param url URL of the page. Stored in the Intent with
573 * {@link Intent#EXTRA_TEXT}
574 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
575 * with {@link Browser#EXTRA_SHARE_FAVICON}
576 * @param screenshot Bitmap of a screenshot of the page. Stored in the
577 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
578 */
579 static final void sharePage(Context c, String title, String url,
580 Bitmap favicon, Bitmap screenshot) {
581 Intent send = new Intent(Intent.ACTION_SEND);
582 send.setType("text/plain");
583 send.putExtra(Intent.EXTRA_TEXT, url);
584 send.putExtra(Intent.EXTRA_SUBJECT, title);
585 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
586 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
587 try {
588 c.startActivity(Intent.createChooser(send, c.getString(
589 R.string.choosertitle_sharevia)));
590 } catch(android.content.ActivityNotFoundException ex) {
591 // if no app handles it, do nothing
592 }
593 }
594
595 private void copy(CharSequence text) {
596 ClipboardManager cm = (ClipboardManager) mActivity
597 .getSystemService(Context.CLIPBOARD_SERVICE);
598 cm.setText(text);
599 }
600
601 // lifecycle
602
603 protected void onConfgurationChanged(Configuration config) {
604 mConfigChanged = true;
605 if (mPageDialogsHandler != null) {
606 mPageDialogsHandler.onConfigurationChanged(config);
607 }
608 mUi.onConfigurationChanged(config);
609 }
610
611 @Override
612 public void handleNewIntent(Intent intent) {
Michael Kolb59e232c2011-08-18 17:19:53 -0700613 if (!mUi.isWebShowing()) {
614 mUi.showWeb(false);
615 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700616 mIntentHandler.onNewIntent(intent);
617 }
618
619 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800620 if (mUi.isCustomViewShowing()) {
621 hideCustomView();
622 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700623 if (mActivityPaused) {
624 Log.e(LOGTAG, "BrowserActivity is already paused.");
625 return;
626 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700627 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800628 Tab tab = mTabControl.getCurrentTab();
629 if (tab != null) {
630 tab.pause();
631 if (!pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700632 if (mWakeLock == null) {
633 PowerManager pm = (PowerManager) mActivity
634 .getSystemService(Context.POWER_SERVICE);
635 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
636 }
Michael Kolb70976932010-11-30 11:34:01 -0800637 mWakeLock.acquire();
638 mHandler.sendMessageDelayed(mHandler
639 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
640 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700641 }
642 mUi.onPause();
643 mNetworkHandler.onPause();
644
645 WebView.disablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100646 NfcHandler.unregister(mActivity);
John Reckd7dd9b22011-08-30 09:18:29 -0700647 if (sThumbnailBitmap != null) {
648 sThumbnailBitmap.recycle();
649 sThumbnailBitmap = null;
650 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700651 }
652
John Reck1cf4b792011-07-26 10:22:22 -0700653 void onSaveInstanceState(Bundle outState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700654 // the default implementation requires each view to have an id. As the
655 // browser handles the state itself and it doesn't use id for the views,
656 // don't call the default implementation. Otherwise it will trigger the
657 // warning like this, "couldn't save which view has focus because the
658 // focused view XXX has no id".
659
660 // Save all the tabs
John Reck1cf4b792011-07-26 10:22:22 -0700661 mTabControl.saveState(outState);
John Reck24f18262011-06-17 14:47:20 -0700662 if (!outState.isEmpty()) {
663 // Save time so that we know how old incognito tabs (if any) are.
664 outState.putSerializable("lastActiveDate", Calendar.getInstance());
665 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700666 }
667
668 void onResume() {
669 if (!mActivityPaused) {
670 Log.e(LOGTAG, "BrowserActivity is already resumed.");
671 return;
672 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700673 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800674 Tab current = mTabControl.getCurrentTab();
675 if (current != null) {
676 current.resume();
677 resumeWebViewTimers(current);
678 }
John Reckf57c0292011-07-21 18:15:39 -0700679 releaseWakeLock();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200680
Michael Kolb8233fac2010-10-26 16:08:53 -0700681 mUi.onResume();
682 mNetworkHandler.onResume();
683 WebView.enablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100684 NfcHandler.register(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700685 }
686
John Reckf57c0292011-07-21 18:15:39 -0700687 private void releaseWakeLock() {
688 if (mWakeLock != null && mWakeLock.isHeld()) {
689 mHandler.removeMessages(RELEASE_WAKELOCK);
690 mWakeLock.release();
691 }
692 }
693
Michael Kolb70976932010-11-30 11:34:01 -0800694 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800695 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800696 * @param tab guaranteed non-null
697 */
698 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700699 boolean inLoad = tab.inPageLoad();
700 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
701 CookieSyncManager.getInstance().startSync();
702 WebView w = tab.getWebView();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100703 WebViewTimersControl.getInstance().onBrowserActivityResume(w);
Michael Kolb8233fac2010-10-26 16:08:53 -0700704 }
705 }
706
Michael Kolb70976932010-11-30 11:34:01 -0800707 /**
708 * Pause all WebView timers using the WebView of the given tab
709 * @param tab
710 * @return true if the timers are paused or tab is null
711 */
712 private boolean pauseWebViewTimers(Tab tab) {
713 if (tab == null) {
714 return true;
715 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700716 CookieSyncManager.getInstance().stopSync();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100717 WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView());
Michael Kolb8233fac2010-10-26 16:08:53 -0700718 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700719 }
Michael Kolb70976932010-11-30 11:34:01 -0800720 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700721 }
722
723 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800724 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700725 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
726 mUploadHandler = null;
727 }
728 if (mTabControl == null) return;
729 mUi.onDestroy();
730 // Remove the current tab and sub window
731 Tab t = mTabControl.getCurrentTab();
732 if (t != null) {
733 dismissSubWindow(t);
734 removeTab(t);
735 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500736 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700737 // Destroy all the tabs
738 mTabControl.destroy();
739 WebIconDatabase.getInstance().close();
740 // Stop watching the default geolocation permissions
741 mSystemAllowGeolocationOrigins.stop();
742 mSystemAllowGeolocationOrigins = null;
743 }
744
745 protected boolean isActivityPaused() {
746 return mActivityPaused;
747 }
748
749 protected void onLowMemory() {
750 mTabControl.freeMemory();
751 }
752
753 @Override
754 public boolean shouldShowErrorConsole() {
755 return mShouldShowErrorConsole;
756 }
757
758 protected void setShouldShowErrorConsole(boolean show) {
759 if (show == mShouldShowErrorConsole) {
760 // Nothing to do.
761 return;
762 }
763 mShouldShowErrorConsole = show;
764 Tab t = mTabControl.getCurrentTab();
765 if (t == null) {
766 // There is no current tab so we cannot toggle the error console
767 return;
768 }
769 mUi.setShouldShowErrorConsole(t, show);
770 }
771
772 @Override
773 public void stopLoading() {
774 mLoadStopped = true;
775 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700776 WebView w = getCurrentTopWebView();
777 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700778 mUi.onPageStopped(tab);
779 }
780
781 boolean didUserStopLoading() {
782 return mLoadStopped;
783 }
784
785 // WebViewController
786
787 @Override
John Reck324d4402011-01-11 16:56:42 -0800788 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700789
790 // We've started to load a new page. If there was a pending message
791 // to save a screenshot then we will now take the new page and save
792 // an incorrect screenshot. Therefore, remove any pending thumbnail
793 // messages from the queue.
794 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800795 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700796
797 // reset sync timer to avoid sync starts during loading a page
798 CookieSyncManager.getInstance().resetSync();
799
800 if (!mNetworkHandler.isNetworkUp()) {
801 view.setNetworkAvailable(false);
802 }
803
804 // when BrowserActivity just starts, onPageStarted may be called before
805 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
806 // to start the timer. As we won't switch tabs while an activity is in
807 // pause state, we can ensure calling resume and pause in pair.
808 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800809 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700810 }
811 mLoadStopped = false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700812 endActionMode();
813
John Reck30c714c2010-12-16 17:30:34 -0800814 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700815
John Reck324d4402011-01-11 16:56:42 -0800816 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700817 // update the bookmark database for favicon
818 maybeUpdateFavicon(tab, null, url, favicon);
819
820 Performance.tracePageStart(url);
821
822 // Performance probe
823 if (false) {
824 Performance.onPageStarted();
825 }
826
827 }
828
829 @Override
John Reck324d4402011-01-11 16:56:42 -0800830 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800831 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800832 if (!tab.isPrivateBrowsingEnabled()
John Reckd8c74522011-06-14 08:45:00 -0700833 && !TextUtils.isEmpty(tab.getUrl())
834 && !tab.isSnapshot()) {
John Recka1696282011-07-08 14:10:37 -0700835 // Only update the bookmark screenshot if the user did not
836 // cancel the load early and there is not already
837 // a pending update for the tab.
Michael Kolb8233fac2010-10-26 16:08:53 -0700838 if (tab.inForeground() && !didUserStopLoading()
839 || !tab.inForeground()) {
John Recka1696282011-07-08 14:10:37 -0700840 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
841 mHandler.sendMessageDelayed(mHandler.obtainMessage(
842 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
843 500);
844 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700845 }
846 }
847 // pause the WebView timer and release the wake lock if it is finished
848 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800849 if (mActivityPaused && pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700850 releaseWakeLock();
Michael Kolb8233fac2010-10-26 16:08:53 -0700851 }
Martijn Coenenb2f93552011-06-14 10:48:35 +0200852
Michael Kolb8233fac2010-10-26 16:08:53 -0700853 // Performance probe
854 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800855 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700856 }
857
858 Performance.tracePageFinished();
859 }
860
861 @Override
John Reck30c714c2010-12-16 17:30:34 -0800862 public void onProgressChanged(Tab tab) {
John Reck6c2e2f32011-08-22 13:41:23 -0700863 mCrashRecoveryHandler.backupState();
John Reck30c714c2010-12-16 17:30:34 -0800864 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700865
866 if (newProgress == 100) {
867 CookieSyncManager.getInstance().sync();
868 // onProgressChanged() may continue to be called after the main
869 // frame has finished loading, as any remaining sub frames continue
870 // to load. We'll only get called once though with newProgress as
871 // 100 when everything is loaded. (onPageFinished is called once
872 // when the main frame completes loading regardless of the state of
873 // any sub frames so calls to onProgressChanges may continue after
874 // onPageFinished has executed)
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800875 if (tab.inPageLoad()) {
876 updateInLoadMenuItems(mCachedMenu, tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700877 }
878 } else {
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800879 if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700880 // onPageFinished may have already been called but a subframe is
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800881 // still loading
882 // updating the progress and
Michael Kolb8233fac2010-10-26 16:08:53 -0700883 // update the menu items.
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800884 updateInLoadMenuItems(mCachedMenu, tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700885 }
886 }
John Reck30c714c2010-12-16 17:30:34 -0800887 mUi.onProgressChanged(tab);
888 }
889
890 @Override
Steve Block2466eff2011-10-03 15:33:09 +0100891 public void onUpdatedSecurityState(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800892 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700893 }
894
895 @Override
896 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800897 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800898 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800899 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700900 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
901 return;
902 }
903 // Update the title in the history database if not in private browsing mode
904 if (!tab.isPrivateBrowsingEnabled()) {
John Reckf57c0292011-07-21 18:15:39 -0700905 DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700906 }
907 }
908
909 @Override
910 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800911 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700912 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
913 }
914
915 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800916 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
917 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700918 }
919
920 @Override
921 public boolean shouldOverrideKeyEvent(KeyEvent event) {
922 if (mMenuIsDown) {
923 // only check shortcut key when MENU is held
924 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
925 event);
926 } else {
927 return false;
928 }
929 }
930
931 @Override
932 public void onUnhandledKeyEvent(KeyEvent event) {
933 if (!isActivityPaused()) {
934 if (event.getAction() == KeyEvent.ACTION_DOWN) {
935 mActivity.onKeyDown(event.getKeyCode(), event);
936 } else {
937 mActivity.onKeyUp(event.getKeyCode(), event);
938 }
939 }
940 }
941
942 @Override
John Reck324d4402011-01-11 16:56:42 -0800943 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700944 // Don't save anything in private browsing mode
945 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800946 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700947
John Reck324d4402011-01-11 16:56:42 -0800948 if (TextUtils.isEmpty(url)
949 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700950 return;
951 }
John Reckf57c0292011-07-21 18:15:39 -0700952 DataController.getInstance(mActivity).updateVisitedHistory(url);
John Reck6c2e2f32011-08-22 13:41:23 -0700953 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -0700954 }
955
956 @Override
957 public void getVisitedHistory(final ValueCallback<String[]> callback) {
958 AsyncTask<Void, Void, String[]> task =
959 new AsyncTask<Void, Void, String[]>() {
960 @Override
961 public String[] doInBackground(Void... unused) {
962 return Browser.getVisitedHistory(mActivity.getContentResolver());
963 }
964 @Override
965 public void onPostExecute(String[] result) {
966 callback.onReceiveValue(result);
967 }
968 };
969 task.execute();
970 }
971
972 @Override
973 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
974 final HttpAuthHandler handler, final String host,
975 final String realm) {
976 String username = null;
977 String password = null;
978
979 boolean reuseHttpAuthUsernamePassword
980 = handler.useHttpAuthUsernamePassword();
981
982 if (reuseHttpAuthUsernamePassword && view != null) {
983 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
984 if (credentials != null && credentials.length == 2) {
985 username = credentials[0];
986 password = credentials[1];
987 }
988 }
989
990 if (username != null && password != null) {
991 handler.proceed(username, password);
992 } else {
Ben Murdochfdd37112011-08-05 15:48:14 +0100993 if (tab.inForeground() && !handler.suppressDialog()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700994 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
995 } else {
996 handler.cancel();
997 }
998 }
999 }
1000
1001 @Override
1002 public void onDownloadStart(Tab tab, String url, String userAgent,
1003 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001004 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -05001005 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001006 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
1007 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001008 // This Tab was opened for the sole purpose of downloading a
1009 // file. Remove it.
1010 if (tab == mTabControl.getCurrentTab()) {
1011 // In this case, the Tab is still on top.
1012 goBackOnePageOrQuit();
1013 } else {
1014 // In this case, it is not.
1015 closeTab(tab);
1016 }
1017 }
1018 }
1019
1020 @Override
1021 public Bitmap getDefaultVideoPoster() {
1022 return mUi.getDefaultVideoPoster();
1023 }
1024
1025 @Override
1026 public View getVideoLoadingProgressView() {
1027 return mUi.getVideoLoadingProgressView();
1028 }
1029
1030 @Override
1031 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1032 SslError error) {
1033 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1034 }
1035
Patrick Scott92066772011-03-10 08:46:27 -05001036 @Override
1037 public void showAutoLogin(Tab tab) {
1038 assert tab.inForeground();
1039 // Update the title bar to show the auto-login request.
1040 mUi.showAutoLogin(tab);
1041 }
1042
1043 @Override
1044 public void hideAutoLogin(Tab tab) {
1045 assert tab.inForeground();
1046 mUi.hideAutoLogin(tab);
1047 }
1048
Michael Kolb8233fac2010-10-26 16:08:53 -07001049 // helper method
1050
1051 /*
1052 * Update the favorites icon if the private browsing isn't enabled and the
1053 * icon is valid.
1054 */
1055 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1056 final String url, Bitmap favicon) {
1057 if (favicon == null) {
1058 return;
1059 }
1060 if (!tab.isPrivateBrowsingEnabled()) {
1061 Bookmarks.updateFavicon(mActivity
1062 .getContentResolver(), originalUrl, url, favicon);
1063 }
1064 }
1065
Leon Scroggins4cd97792010-12-03 15:31:56 -05001066 @Override
1067 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001068 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001069 mUi.bookmarkedStatusHasChanged(tab);
1070 }
1071
Michael Kolb8233fac2010-10-26 16:08:53 -07001072 // end WebViewController
1073
1074 protected void pageUp() {
1075 getCurrentTopWebView().pageUp(false);
1076 }
1077
1078 protected void pageDown() {
1079 getCurrentTopWebView().pageDown(false);
1080 }
1081
1082 // callback from phone title bar
1083 public void editUrl() {
1084 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001085 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001086 }
1087
Michael Kolbcfa3af52010-12-14 10:36:11 -08001088 public void startVoiceSearch() {
1089 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1090 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1091 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1092 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1093 mActivity.getComponentName().flattenToString());
1094 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001095 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001096 mActivity.startActivity(intent);
1097 }
1098
Michael Kolb11d19782011-03-20 10:17:40 -07001099 @Override
1100 public void activateVoiceSearchMode(String title, List<String> results) {
1101 mUi.showVoiceTitleBar(title, results);
Michael Kolb8233fac2010-10-26 16:08:53 -07001102 }
1103
1104 public void revertVoiceSearchMode(Tab tab) {
1105 mUi.revertVoiceTitleBar(tab);
1106 }
1107
Michael Kolb736990c2011-03-20 10:01:20 -07001108 public boolean supportsVoiceSearch() {
John Reck35e9dd62011-04-25 09:01:54 -07001109 SearchEngine searchEngine = getSettings().getSearchEngine();
Michael Kolb736990c2011-03-20 10:01:20 -07001110 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1111 }
1112
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001113 public void showCustomView(Tab tab, View view, int requestedOrientation,
Michael Kolb8233fac2010-10-26 16:08:53 -07001114 WebChromeClient.CustomViewCallback callback) {
1115 if (tab.inForeground()) {
1116 if (mUi.isCustomViewShowing()) {
1117 callback.onCustomViewHidden();
1118 return;
1119 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001120 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001121 // Save the menu state and set it to empty while the custom
1122 // view is showing.
1123 mOldMenuState = mMenuState;
1124 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001125 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001126 }
1127 }
1128
1129 @Override
1130 public void hideCustomView() {
1131 if (mUi.isCustomViewShowing()) {
1132 mUi.onHideCustomView();
1133 // Reset the old menu state.
1134 mMenuState = mOldMenuState;
1135 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001136 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001137 }
1138 }
1139
1140 protected void onActivityResult(int requestCode, int resultCode,
1141 Intent intent) {
1142 if (getCurrentTopWebView() == null) return;
1143 switch (requestCode) {
1144 case PREFERENCES_PAGE:
1145 if (resultCode == Activity.RESULT_OK && intent != null) {
1146 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001147 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001148 mTabControl.removeParentChildRelationShips();
1149 }
1150 }
1151 break;
1152 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001153 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001154 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001155 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001156 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001157 case AUTOFILL_SETUP:
1158 // Determine whether a profile was actually set up or not
1159 // and if so, send the message back to the WebTextView to
1160 // fill the form with the new profile.
1161 if (getSettings().getAutoFillProfile() != null) {
1162 mAutoFillSetupMessage.sendToTarget();
1163 mAutoFillSetupMessage = null;
1164 }
1165 break;
John Reckd3e4d5b2011-07-13 15:48:43 -07001166 case COMBO_VIEW:
1167 if (intent == null || resultCode != Activity.RESULT_OK) {
1168 break;
1169 }
John Reck3ba45532011-08-11 16:26:53 -07001170 mUi.showWeb(false);
John Reckd3e4d5b2011-07-13 15:48:43 -07001171 if (Intent.ACTION_VIEW.equals(intent.getAction())) {
1172 Tab t = getCurrentTab();
1173 Uri uri = intent.getData();
1174 loadUrl(t, uri.toString());
1175 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
1176 String[] urls = intent.getStringArrayExtra(
1177 ComboViewActivity.EXTRA_OPEN_ALL);
1178 Tab parent = getCurrentTab();
1179 for (String url : urls) {
1180 parent = openTab(url, parent,
1181 !mSettings.openInBackground(), true);
1182 }
1183 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
1184 long id = intent.getLongExtra(
1185 ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
1186 if (id >= 0) {
1187 createNewSnapshotTab(id, true);
1188 }
1189 }
1190 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001191 default:
1192 break;
1193 }
1194 getCurrentTopWebView().requestFocus();
1195 }
1196
1197 /**
1198 * Open the Go page.
1199 * @param startWithHistory If true, open starting on the history tab.
1200 * Otherwise, start with the bookmarks tab.
1201 */
1202 @Override
Michael Kolb315d5022011-10-13 12:47:11 -07001203 public void bookmarksOrHistoryPicker(ComboViews startView) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001204 if (mTabControl.getCurrentWebView() == null) {
1205 return;
1206 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001207 // clear action mode
1208 if (isInCustomActionMode()) {
1209 endActionMode();
1210 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001211 Bundle extras = new Bundle();
1212 // Disable opening in a new window if we have maxed out the windows
1213 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1214 !mTabControl.canCreateNewTab());
Michael Kolb315d5022011-10-13 12:47:11 -07001215 mUi.showComboView(startView, extras);
Michael Kolb8233fac2010-10-26 16:08:53 -07001216 }
1217
1218 // combo view callbacks
1219
Michael Kolb8233fac2010-10-26 16:08:53 -07001220 // key handling
1221 protected void onBackKey() {
1222 if (!mUi.onBackKey()) {
1223 WebView subwindow = mTabControl.getCurrentSubWindow();
1224 if (subwindow != null) {
1225 if (subwindow.canGoBack()) {
1226 subwindow.goBack();
1227 } else {
1228 dismissSubWindow(mTabControl.getCurrentTab());
1229 }
1230 } else {
1231 goBackOnePageOrQuit();
1232 }
1233 }
1234 }
1235
Michael Kolb4bd767d2011-05-27 11:33:55 -07001236 protected boolean onMenuKey() {
1237 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001238 }
1239
Michael Kolb8233fac2010-10-26 16:08:53 -07001240 // menu handling and state
1241 // TODO: maybe put into separate handler
1242
1243 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckd73c5a22010-12-22 10:22:50 -08001244 if (mMenuState == EMPTY_MENU) {
1245 return false;
1246 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001247 MenuInflater inflater = mActivity.getMenuInflater();
1248 inflater.inflate(R.menu.browser, menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001249 return true;
1250 }
1251
1252 protected void onCreateContextMenu(ContextMenu menu, View v,
1253 ContextMenuInfo menuInfo) {
John Reck0f602f32011-07-07 15:38:43 -07001254 if (v instanceof TitleBar) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001255 return;
1256 }
1257 if (!(v instanceof WebView)) {
1258 return;
1259 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001260 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001261 WebView.HitTestResult result = webview.getHitTestResult();
1262 if (result == null) {
1263 return;
1264 }
1265
1266 int type = result.getType();
1267 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1268 Log.w(LOGTAG,
1269 "We should not show context menu when nothing is touched");
1270 return;
1271 }
1272 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1273 // let TextView handles context menu
1274 return;
1275 }
1276
1277 // Note, http://b/issue?id=1106666 is requesting that
1278 // an inflated menu can be used again. This is not available
1279 // yet, so inflate each time (yuk!)
1280 MenuInflater inflater = mActivity.getMenuInflater();
1281 inflater.inflate(R.menu.browsercontext, menu);
1282
1283 // Show the correct menu group
1284 final String extra = result.getExtra();
1285 menu.setGroupVisible(R.id.PHONE_MENU,
1286 type == WebView.HitTestResult.PHONE_TYPE);
1287 menu.setGroupVisible(R.id.EMAIL_MENU,
1288 type == WebView.HitTestResult.EMAIL_TYPE);
1289 menu.setGroupVisible(R.id.GEO_MENU,
1290 type == WebView.HitTestResult.GEO_TYPE);
1291 menu.setGroupVisible(R.id.IMAGE_MENU,
1292 type == WebView.HitTestResult.IMAGE_TYPE
1293 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1294 menu.setGroupVisible(R.id.ANCHOR_MENU,
1295 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1296 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001297 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1298 || type == WebView.HitTestResult.PHONE_TYPE
1299 || type == WebView.HitTestResult.EMAIL_TYPE
1300 || type == WebView.HitTestResult.GEO_TYPE;
1301 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1302 if (hitText) {
1303 menu.findItem(R.id.select_text_menu_id)
1304 .setOnMenuItemClickListener(new SelectText(webview));
1305 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001306 // Setup custom handling depending on the type
1307 switch (type) {
1308 case WebView.HitTestResult.PHONE_TYPE:
1309 menu.setHeaderTitle(Uri.decode(extra));
1310 menu.findItem(R.id.dial_context_menu_id).setIntent(
1311 new Intent(Intent.ACTION_VIEW, Uri
1312 .parse(WebView.SCHEME_TEL + extra)));
1313 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1314 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1315 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1316 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1317 addIntent);
1318 menu.findItem(R.id.copy_phone_context_menu_id)
1319 .setOnMenuItemClickListener(
1320 new Copy(extra));
1321 break;
1322
1323 case WebView.HitTestResult.EMAIL_TYPE:
1324 menu.setHeaderTitle(extra);
1325 menu.findItem(R.id.email_context_menu_id).setIntent(
1326 new Intent(Intent.ACTION_VIEW, Uri
1327 .parse(WebView.SCHEME_MAILTO + extra)));
1328 menu.findItem(R.id.copy_mail_context_menu_id)
1329 .setOnMenuItemClickListener(
1330 new Copy(extra));
1331 break;
1332
1333 case WebView.HitTestResult.GEO_TYPE:
1334 menu.setHeaderTitle(extra);
1335 menu.findItem(R.id.map_context_menu_id).setIntent(
1336 new Intent(Intent.ACTION_VIEW, Uri
1337 .parse(WebView.SCHEME_GEO
1338 + URLEncoder.encode(extra))));
1339 menu.findItem(R.id.copy_geo_context_menu_id)
1340 .setOnMenuItemClickListener(
1341 new Copy(extra));
1342 break;
1343
1344 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1345 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001346 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001347 // decide whether to show the open link in new tab option
1348 boolean showNewTab = mTabControl.canCreateNewTab();
1349 MenuItem newTabItem
1350 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001351 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001352 ? R.string.contextmenu_openlink_newwindow_background
1353 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001354 newTabItem.setVisible(showNewTab);
1355 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001356 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1357 newTabItem.setOnMenuItemClickListener(
1358 new MenuItem.OnMenuItemClickListener() {
1359 @Override
1360 public boolean onMenuItemClick(MenuItem item) {
1361 final HashMap<String, WebView> hrefMap =
1362 new HashMap<String, WebView>();
1363 hrefMap.put("webview", webview);
1364 final Message msg = mHandler.obtainMessage(
1365 FOCUS_NODE_HREF,
1366 R.id.open_newtab_context_menu_id,
1367 0, hrefMap);
1368 webview.requestFocusNodeHref(msg);
1369 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001370 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001371 });
1372 } else {
1373 newTabItem.setOnMenuItemClickListener(
1374 new MenuItem.OnMenuItemClickListener() {
1375 @Override
1376 public boolean onMenuItemClick(MenuItem item) {
1377 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001378 openTab(extra, parent,
1379 !mSettings.openInBackground(),
1380 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001381 return true;
1382 }
1383 });
1384 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001385 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001386 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1387 break;
1388 }
1389 // otherwise fall through to handle image part
1390 case WebView.HitTestResult.IMAGE_TYPE:
1391 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1392 menu.setHeaderTitle(extra);
1393 }
Michael Kolb3639c4c2011-09-28 15:36:40 -07001394 menu.findItem(R.id.view_image_context_menu_id)
1395 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1396 @Override
1397 public boolean onMenuItemClick(MenuItem item) {
1398 openTab(extra, mTabControl.getCurrentTab(), true, true);
1399 return false;
1400 }
1401 });
Michael Kolb8233fac2010-10-26 16:08:53 -07001402 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001403 setOnMenuItemClickListener(
1404 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001405 menu.findItem(R.id.set_wallpaper_context_menu_id).
1406 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1407 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001408 break;
1409
1410 default:
1411 Log.w(LOGTAG, "We should not get here.");
1412 break;
1413 }
1414 //update the ui
1415 mUi.onContextMenuCreated(menu);
1416 }
1417
1418 /**
1419 * As the menu can be open when loading state changes
1420 * we must manually update the state of the stop/reload menu
1421 * item
1422 */
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001423 private void updateInLoadMenuItems(Menu menu, Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001424 if (menu == null) {
1425 return;
1426 }
1427 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolbb8337132011-11-28 15:07:39 -08001428 MenuItem src = ((tab != null) && tab.inPageLoad()) ?
Michael Kolb8233fac2010-10-26 16:08:53 -07001429 menu.findItem(R.id.stop_menu_id):
1430 menu.findItem(R.id.reload_menu_id);
1431 if (src != null) {
1432 dest.setIcon(src.getIcon());
1433 dest.setTitle(src.getTitle());
1434 }
1435 }
1436
John Reckb3417f02011-01-14 11:01:05 -08001437 boolean onPrepareOptionsMenu(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001438 updateInLoadMenuItems(menu, getCurrentTab());
John Recke1a03a32011-09-14 17:04:16 -07001439 // hold on to the menu reference here; it is used by the page callbacks
1440 // to update the menu based on loading state
1441 mCachedMenu = menu;
Michael Kolb8233fac2010-10-26 16:08:53 -07001442 // Note: setVisible will decide whether an item is visible; while
1443 // setEnabled() will decide whether an item is enabled, which also means
1444 // whether the matching shortcut key will function.
1445 switch (mMenuState) {
1446 case EMPTY_MENU:
1447 if (mCurrentMenuState != mMenuState) {
1448 menu.setGroupVisible(R.id.MAIN_MENU, false);
1449 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1450 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1451 }
1452 break;
1453 default:
1454 if (mCurrentMenuState != mMenuState) {
1455 menu.setGroupVisible(R.id.MAIN_MENU, true);
1456 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1457 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1458 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001459 updateMenuState(getCurrentTab(), menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001460 break;
1461 }
1462 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001463 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001464 }
1465
Michael Kolb4bf79712011-07-14 14:18:12 -07001466 @Override
1467 public void updateMenuState(Tab tab, Menu menu) {
1468 boolean canGoBack = false;
1469 boolean canGoForward = false;
1470 boolean isHome = false;
John Reck42229bc2011-08-19 13:26:43 -07001471 boolean isDesktopUa = false;
John Recke1a03a32011-09-14 17:04:16 -07001472 boolean isLive = false;
Michael Kolb4bf79712011-07-14 14:18:12 -07001473 if (tab != null) {
1474 canGoBack = tab.canGoBack();
1475 canGoForward = tab.canGoForward();
1476 isHome = mSettings.getHomePage().equals(tab.getUrl());
John Reck42229bc2011-08-19 13:26:43 -07001477 isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
John Recke1a03a32011-09-14 17:04:16 -07001478 isLive = !tab.isSnapshot();
Michael Kolb4bf79712011-07-14 14:18:12 -07001479 }
1480 final MenuItem back = menu.findItem(R.id.back_menu_id);
1481 back.setEnabled(canGoBack);
1482
1483 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1484 home.setEnabled(!isHome);
1485
1486 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1487 forward.setEnabled(canGoForward);
1488
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001489 final MenuItem source = menu.findItem(isInLoad() ? R.id.stop_menu_id
1490 : R.id.reload_menu_id);
Michael Kolb4bf79712011-07-14 14:18:12 -07001491 final MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolb7ab75ee2011-07-14 16:36:38 -07001492 if (source != null && dest != null) {
1493 dest.setTitle(source.getTitle());
1494 dest.setIcon(source.getIcon());
1495 }
John Recke1a03a32011-09-14 17:04:16 -07001496 menu.setGroupVisible(R.id.NAV_MENU, isLive);
Michael Kolb4bf79712011-07-14 14:18:12 -07001497
1498 // decide whether to show the share link option
1499 PackageManager pm = mActivity.getPackageManager();
1500 Intent send = new Intent(Intent.ACTION_SEND);
1501 send.setType("text/plain");
1502 ResolveInfo ri = pm.resolveActivity(send,
1503 PackageManager.MATCH_DEFAULT_ONLY);
1504 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1505
1506 boolean isNavDump = mSettings.enableNavDump();
1507 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1508 nav.setVisible(isNavDump);
1509 nav.setEnabled(isNavDump);
1510
1511 boolean showDebugSettings = mSettings.isDebugEnabled();
1512 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1513 counter.setVisible(showDebugSettings);
1514 counter.setEnabled(showDebugSettings);
John Reck42229bc2011-08-19 13:26:43 -07001515 final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
1516 uaSwitcher.setChecked(isDesktopUa);
John Recke1a03a32011-09-14 17:04:16 -07001517 menu.setGroupVisible(R.id.LIVE_MENU, isLive);
1518 menu.setGroupVisible(R.id.SNAPSHOT_MENU, !isLive);
Michael Kolb315d5022011-10-13 12:47:11 -07001519 menu.setGroupVisible(R.id.COMBO_MENU, false);
Michael Kolb4bf79712011-07-14 14:18:12 -07001520
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001521 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001522 }
1523
Michael Kolb8233fac2010-10-26 16:08:53 -07001524 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001525 if (null == getCurrentTopWebView()) {
1526 return false;
1527 }
1528 if (mMenuIsDown) {
1529 // The shortcut action consumes the MENU. Even if it is still down,
1530 // it won't trigger the next shortcut action. In the case of the
1531 // shortcut action triggering a new activity, like Bookmarks, we
1532 // won't get onKeyUp for MENU. So it is important to reset it here.
1533 mMenuIsDown = false;
1534 }
Michael Kolb3ca12752011-07-20 13:52:25 -07001535 if (mUi.onOptionsItemSelected(item)) {
1536 // ui callback handled it
1537 return true;
1538 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001539 switch (item.getItemId()) {
1540 // -- Main menu
1541 case R.id.new_tab_menu_id:
1542 openTabToHomePage();
1543 break;
1544
1545 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001546 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001547 break;
1548
1549 case R.id.goto_menu_id:
1550 editUrl();
1551 break;
1552
1553 case R.id.bookmarks_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001554 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
1555 break;
1556
1557 case R.id.history_menu_id:
1558 bookmarksOrHistoryPicker(ComboViews.History);
1559 break;
1560
1561 case R.id.snapshots_menu_id:
1562 bookmarksOrHistoryPicker(ComboViews.Snapshots);
Michael Kolb8233fac2010-10-26 16:08:53 -07001563 break;
1564
Michael Kolb8233fac2010-10-26 16:08:53 -07001565 case R.id.add_bookmark_menu_id:
John Recka60fffa2011-09-06 16:30:29 -07001566 Intent bookmarkIntent = createBookmarkCurrentPageIntent(false);
1567 if (bookmarkIntent != null) {
1568 mActivity.startActivity(bookmarkIntent);
1569 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001570 break;
1571
1572 case R.id.stop_reload_menu_id:
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001573 if (isInLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001574 stopLoading();
1575 } else {
1576 getCurrentTopWebView().reload();
1577 }
1578 break;
1579
1580 case R.id.back_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001581 getCurrentTab().goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07001582 break;
1583
1584 case R.id.forward_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001585 getCurrentTab().goForward();
Michael Kolb8233fac2010-10-26 16:08:53 -07001586 break;
1587
1588 case R.id.close_menu_id:
1589 // Close the subwindow if it exists.
1590 if (mTabControl.getCurrentSubWindow() != null) {
1591 dismissSubWindow(mTabControl.getCurrentTab());
1592 break;
1593 }
1594 closeCurrentTab();
1595 break;
1596
1597 case R.id.homepage_menu_id:
1598 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07001599 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07001600 break;
1601
1602 case R.id.preferences_menu_id:
1603 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1604 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1605 getCurrentTopWebView().getUrl());
1606 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1607 break;
1608
1609 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001610 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001611 break;
1612
John Reck2bc80422011-06-30 15:11:49 -07001613 case R.id.save_snapshot_menu_id:
1614 final Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07001615 if (source == null) break;
John Reckd8c74522011-06-14 08:45:00 -07001616 final ContentResolver cr = mActivity.getContentResolver();
1617 final ContentValues values = source.createSnapshotValues();
John Reck2bc80422011-06-30 15:11:49 -07001618 if (values != null) {
1619 new AsyncTask<Tab, Void, Long>() {
John Reckd8c74522011-06-14 08:45:00 -07001620
John Reck2bc80422011-06-30 15:11:49 -07001621 @Override
1622 protected Long doInBackground(Tab... params) {
1623 Uri result = cr.insert(Snapshots.CONTENT_URI, values);
John Reck93384ff2011-11-10 11:29:18 -08001624 if (result == null) {
1625 return null;
1626 }
John Reck2bc80422011-06-30 15:11:49 -07001627 long id = ContentUris.parseId(result);
1628 return id;
John Reckd8c74522011-06-14 08:45:00 -07001629 }
John Reckf33b1632011-06-04 20:00:23 -07001630
John Reck2bc80422011-06-30 15:11:49 -07001631 @Override
1632 protected void onPostExecute(Long id) {
John Reck93384ff2011-11-10 11:29:18 -08001633 if (id == null) {
1634 Toast.makeText(mActivity, R.string.snapshot_failed,
1635 Toast.LENGTH_SHORT).show();
1636 return;
1637 }
John Reck2bc80422011-06-30 15:11:49 -07001638 Bundle b = new Bundle();
1639 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
1640 mUi.showComboView(ComboViews.Snapshots, b);
1641 };
1642 }.execute(source);
1643 } else {
1644 Toast.makeText(mActivity, R.string.snapshot_failed,
Leon Scrogginsac993842011-02-02 12:54:07 -05001645 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001646 }
Leon Scrogginsac993842011-02-02 12:54:07 -05001647 break;
1648
Michael Kolb8233fac2010-10-26 16:08:53 -07001649 case R.id.page_info_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001650 showPageInfo();
Michael Kolb8233fac2010-10-26 16:08:53 -07001651 break;
1652
John Recke1a03a32011-09-14 17:04:16 -07001653 case R.id.snapshot_go_live:
1654 goLive();
1655 return true;
1656
Michael Kolb8233fac2010-10-26 16:08:53 -07001657 case R.id.share_page_menu_id:
1658 Tab currentTab = mTabControl.getCurrentTab();
1659 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001660 return false;
1661 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001662 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001663 break;
1664
1665 case R.id.dump_nav_menu_id:
1666 getCurrentTopWebView().debugDump();
1667 break;
1668
1669 case R.id.dump_counters_menu_id:
1670 getCurrentTopWebView().dumpV8Counters();
1671 break;
1672
1673 case R.id.zoom_in_menu_id:
1674 getCurrentTopWebView().zoomIn();
1675 break;
1676
1677 case R.id.zoom_out_menu_id:
1678 getCurrentTopWebView().zoomOut();
1679 break;
1680
1681 case R.id.view_downloads_menu_id:
1682 viewDownloads();
1683 break;
1684
John Reck42229bc2011-08-19 13:26:43 -07001685 case R.id.ua_desktop_menu_id:
1686 WebView web = getCurrentWebView();
1687 mSettings.toggleDesktopUseragent(web);
1688 web.loadUrl(web.getOriginalUrl());
1689 break;
1690
Michael Kolb8233fac2010-10-26 16:08:53 -07001691 case R.id.window_one_menu_id:
1692 case R.id.window_two_menu_id:
1693 case R.id.window_three_menu_id:
1694 case R.id.window_four_menu_id:
1695 case R.id.window_five_menu_id:
1696 case R.id.window_six_menu_id:
1697 case R.id.window_seven_menu_id:
1698 case R.id.window_eight_menu_id:
1699 {
1700 int menuid = item.getItemId();
1701 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1702 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1703 Tab desiredTab = mTabControl.getTab(id);
1704 if (desiredTab != null &&
1705 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001706 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001707 }
1708 break;
1709 }
1710 }
1711 }
1712 break;
1713
1714 default:
1715 return false;
1716 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001717 return true;
1718 }
1719
John Recke1a03a32011-09-14 17:04:16 -07001720 private void goLive() {
1721 Tab t = getCurrentTab();
1722 t.loadUrl(t.getUrl(), null);
1723 }
1724
Michael Kolb315d5022011-10-13 12:47:11 -07001725 @Override
1726 public void showPageInfo() {
1727 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
1728 }
1729
Michael Kolb8233fac2010-10-26 16:08:53 -07001730 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001731 // Let the History and Bookmark fragments handle menus they created.
1732 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1733 return false;
1734 }
1735
Michael Kolb8233fac2010-10-26 16:08:53 -07001736 int id = item.getItemId();
1737 boolean result = true;
1738 switch (id) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001739 // -- Browser context menu
1740 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001741 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001742 case R.id.copy_link_context_menu_id:
1743 final WebView webView = getCurrentTopWebView();
1744 if (null == webView) {
1745 result = false;
1746 break;
1747 }
1748 final HashMap<String, WebView> hrefMap =
1749 new HashMap<String, WebView>();
1750 hrefMap.put("webview", webView);
1751 final Message msg = mHandler.obtainMessage(
1752 FOCUS_NODE_HREF, id, 0, hrefMap);
1753 webView.requestFocusNodeHref(msg);
1754 break;
1755
1756 default:
1757 // For other context menus
1758 result = onOptionsItemSelected(item);
1759 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001760 return result;
1761 }
1762
1763 /**
1764 * support programmatically opening the context menu
1765 */
1766 public void openContextMenu(View view) {
1767 mActivity.openContextMenu(view);
1768 }
1769
1770 /**
1771 * programmatically open the options menu
1772 */
1773 public void openOptionsMenu() {
1774 mActivity.openOptionsMenu();
1775 }
1776
1777 public boolean onMenuOpened(int featureId, Menu menu) {
1778 if (mOptionsMenuOpen) {
1779 if (mConfigChanged) {
1780 // We do not need to make any changes to the state of the
1781 // title bar, since the only thing that happened was a
1782 // change in orientation
1783 mConfigChanged = false;
1784 } else {
1785 if (!mExtendedMenuOpen) {
1786 mExtendedMenuOpen = true;
1787 mUi.onExtendedMenuOpened();
1788 } else {
1789 // Switching the menu back to icon view, so show the
1790 // title bar once again.
1791 mExtendedMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001792 mUi.onExtendedMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001793 }
1794 }
1795 } else {
1796 // The options menu is closed, so open it, and show the title
1797 mOptionsMenuOpen = true;
1798 mConfigChanged = false;
1799 mExtendedMenuOpen = false;
1800 mUi.onOptionsMenuOpened();
1801 }
1802 return true;
1803 }
1804
1805 public void onOptionsMenuClosed(Menu menu) {
1806 mOptionsMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001807 mUi.onOptionsMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001808 }
1809
1810 public void onContextMenuClosed(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001811 mUi.onContextMenuClosed(menu, isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001812 }
1813
1814 // Helper method for getting the top window.
1815 @Override
1816 public WebView getCurrentTopWebView() {
1817 return mTabControl.getCurrentTopWebView();
1818 }
1819
1820 @Override
1821 public WebView getCurrentWebView() {
1822 return mTabControl.getCurrentWebView();
1823 }
1824
1825 /*
1826 * This method is called as a result of the user selecting the options
1827 * menu to see the download window. It shows the download window on top of
1828 * the current window.
1829 */
1830 void viewDownloads() {
1831 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1832 mActivity.startActivity(intent);
1833 }
1834
John Reck30b065e2011-07-19 10:58:05 -07001835 int getActionModeHeight() {
1836 TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
1837 new int[] { android.R.attr.actionBarSize });
1838 int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
1839 actionBarSizeTypedArray.recycle();
1840 return size;
1841 }
1842
Michael Kolb8233fac2010-10-26 16:08:53 -07001843 // action mode
1844
1845 void onActionModeStarted(ActionMode mode) {
1846 mUi.onActionModeStarted(mode);
1847 mActionMode = mode;
1848 }
1849
1850 /*
1851 * True if a custom ActionMode (i.e. find or select) is in use.
1852 */
1853 @Override
1854 public boolean isInCustomActionMode() {
1855 return mActionMode != null;
1856 }
1857
1858 /*
1859 * End the current ActionMode.
1860 */
1861 @Override
1862 public void endActionMode() {
1863 if (mActionMode != null) {
1864 mActionMode.finish();
1865 }
1866 }
1867
1868 /*
1869 * Called by find and select when they are finished. Replace title bars
1870 * as necessary.
1871 */
1872 public void onActionModeFinished(ActionMode mode) {
1873 if (!isInCustomActionMode()) return;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001874 mUi.onActionModeFinished(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001875 mActionMode = null;
1876 }
1877
1878 boolean isInLoad() {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001879 return getCurrentTab().inPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07001880 }
1881
1882 // bookmark handling
1883
1884 /**
1885 * add the current page as a bookmark to the given folder id
1886 * @param folderId use -1 for the default folder
John Reckd3e4d5b2011-07-13 15:48:43 -07001887 * @param editExisting If true, check to see whether the site is already
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001888 * bookmarked, and if it is, edit that bookmark. If false, and
1889 * the site is already bookmarked, do not attempt to edit the
1890 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001891 */
1892 @Override
John Reckd3e4d5b2011-07-13 15:48:43 -07001893 public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
John Recka60fffa2011-09-06 16:30:29 -07001894 WebView w = getCurrentTopWebView();
1895 if (w == null) {
1896 return null;
1897 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001898 Intent i = new Intent(mActivity,
1899 AddBookmarkPage.class);
Michael Kolb8233fac2010-10-26 16:08:53 -07001900 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1901 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1902 String touchIconUrl = w.getTouchIconUrl();
1903 if (touchIconUrl != null) {
1904 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1905 WebSettings settings = w.getSettings();
1906 if (settings != null) {
1907 i.putExtra(AddBookmarkPage.USER_AGENT,
1908 settings.getUserAgentString());
1909 }
1910 }
1911 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1912 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1913 getDesiredThumbnailHeight(mActivity)));
1914 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07001915 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001916 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1917 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001918 // Put the dialog at the upper right of the screen, covering the
1919 // star on the title bar.
1920 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07001921 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07001922 }
1923
1924 // file chooser
1925 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1926 mUploadHandler = new UploadHandler(this);
1927 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1928 }
1929
1930 // thumbnails
1931
1932 /**
1933 * Return the desired width for thumbnail screenshots, which are stored in
1934 * the database, and used on the bookmarks screen.
1935 * @param context Context for finding out the density of the screen.
1936 * @return desired width for thumbnail screenshot.
1937 */
1938 static int getDesiredThumbnailWidth(Context context) {
1939 return context.getResources().getDimensionPixelOffset(
1940 R.dimen.bookmarkThumbnailWidth);
1941 }
1942
1943 /**
1944 * Return the desired height for thumbnail screenshots, which are stored in
1945 * the database, and used on the bookmarks screen.
1946 * @param context Context for finding out the density of the screen.
1947 * @return desired height for thumbnail screenshot.
1948 */
1949 static int getDesiredThumbnailHeight(Context context) {
1950 return context.getResources().getDimensionPixelOffset(
1951 R.dimen.bookmarkThumbnailHeight);
1952 }
1953
John Reck8cc92352011-07-06 17:41:52 -07001954 static Bitmap createScreenshot(WebView view, int width, int height) {
John Reckd7dd9b22011-08-30 09:18:29 -07001955 if (view == null || view.getContentHeight() == 0
1956 || view.getContentWidth() == 0) {
1957 return null;
1958 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001959 // We render to a bitmap 2x the desired size so that we can then
1960 // re-scale it with filtering since canvas.scale doesn't filter
1961 // This helps reduce aliasing at the cost of being slightly blurry
1962 final int filter_scale = 2;
John Reckd7dd9b22011-08-30 09:18:29 -07001963 int scaledWidth = width * filter_scale;
1964 int scaledHeight = height * filter_scale;
1965 if (sThumbnailBitmap == null || sThumbnailBitmap.getWidth() != scaledWidth
1966 || sThumbnailBitmap.getHeight() != scaledHeight) {
1967 if (sThumbnailBitmap != null) {
1968 sThumbnailBitmap.recycle();
1969 sThumbnailBitmap = null;
1970 }
1971 sThumbnailBitmap =
1972 Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.RGB_565);
Michael Kolb8233fac2010-10-26 16:08:53 -07001973 }
John Reckd7dd9b22011-08-30 09:18:29 -07001974 Canvas canvas = new Canvas(sThumbnailBitmap);
1975 int contentWidth = view.getContentWidth();
1976 float overviewScale = scaledWidth / (view.getScale() * contentWidth);
1977 if (view instanceof BrowserWebView) {
1978 int dy = -((BrowserWebView)view).getTitleHeight();
1979 canvas.translate(0, dy * overviewScale);
1980 }
1981
1982 canvas.scale(overviewScale, overviewScale);
1983
1984 if (view instanceof BrowserWebView) {
1985 ((BrowserWebView)view).drawContent(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07001986 } else {
John Reckd7dd9b22011-08-30 09:18:29 -07001987 view.draw(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07001988 }
John Reckd7dd9b22011-08-30 09:18:29 -07001989 Bitmap ret = Bitmap.createScaledBitmap(sThumbnailBitmap,
1990 width, height, true);
Dianne Hackborn43cfe8a2011-08-02 16:59:35 -07001991 canvas.setBitmap(null);
John Reck5c6ac2f2011-01-05 10:18:03 -08001992 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001993 }
1994
John Reck34ef2672011-02-10 11:30:55 -08001995 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001996 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07001997 // FIXME: Would like to make sure there is actually something to
1998 // draw, but the API for that (WebViewCore.pictureReady()) is not
1999 // currently accessible here.
2000
John Reck34ef2672011-02-10 11:30:55 -08002001 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08002002 if (view == null) {
2003 // Tab was destroyed
2004 return;
2005 }
John Reck34ef2672011-02-10 11:30:55 -08002006 final String url = tab.getUrl();
2007 final String originalUrl = view.getOriginalUrl();
2008
2009 if (TextUtils.isEmpty(url)) {
2010 return;
2011 }
2012
2013 // Only update thumbnails for web urls (http(s)://), not for
2014 // about:, javascript:, data:, etc...
2015 // Unless it is a bookmarked site, then always update
2016 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2017 return;
2018 }
2019
Michael Kolb8233fac2010-10-26 16:08:53 -07002020 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2021 getDesiredThumbnailHeight(mActivity));
2022 if (bm == null) {
2023 return;
2024 }
2025
2026 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002027 new AsyncTask<Void, Void, Void>() {
2028 @Override
2029 protected Void doInBackground(Void... unused) {
2030 Cursor cursor = null;
2031 try {
2032 // TODO: Clean this up
2033 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2034 if (cursor != null && cursor.moveToFirst()) {
2035 final ByteArrayOutputStream os =
2036 new ByteArrayOutputStream();
2037 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002038
John Reck34ef2672011-02-10 11:30:55 -08002039 ContentValues values = new ContentValues();
2040 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002041
John Reck34ef2672011-02-10 11:30:55 -08002042 do {
John Reck617fd832011-02-16 14:35:59 -08002043 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002044 cr.update(Images.CONTENT_URI, values, null, null);
2045 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002046 }
John Reck34ef2672011-02-10 11:30:55 -08002047 } catch (IllegalStateException e) {
2048 // Ignore
2049 } finally {
2050 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002051 }
John Reck34ef2672011-02-10 11:30:55 -08002052 return null;
2053 }
2054 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002055 }
2056
2057 private class Copy implements OnMenuItemClickListener {
2058 private CharSequence mText;
2059
2060 public boolean onMenuItemClick(MenuItem item) {
2061 copy(mText);
2062 return true;
2063 }
2064
2065 public Copy(CharSequence toCopy) {
2066 mText = toCopy;
2067 }
2068 }
2069
Leon Scroggins63c02662010-11-18 15:16:27 -05002070 private static class Download implements OnMenuItemClickListener {
2071 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002072 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002073 private boolean mPrivateBrowsing;
George Mount387d45d2011-10-07 15:57:53 -07002074 private static final String FALLBACK_EXTENSION = "dat";
2075 private static final String IMAGE_BASE_FORMAT = "yyyy-MM-dd-HH-mm-ss-";
Michael Kolb8233fac2010-10-26 16:08:53 -07002076
2077 public boolean onMenuItemClick(MenuItem item) {
George Mount387d45d2011-10-07 15:57:53 -07002078 if (DataUri.isDataUri(mText)) {
2079 saveDataUri();
2080 } else {
2081 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
2082 null, null, mPrivateBrowsing);
2083 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002084 return true;
2085 }
2086
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002087 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002088 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002089 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002090 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002091 }
George Mount387d45d2011-10-07 15:57:53 -07002092
2093 /**
2094 * Treats mText as a data URI and writes its contents to a file
2095 * based on the current time.
2096 */
2097 private void saveDataUri() {
2098 FileOutputStream outputStream = null;
2099 try {
2100 DataUri uri = new DataUri(mText);
2101 File target = getTarget(uri);
2102 outputStream = new FileOutputStream(target);
2103 outputStream.write(uri.getData());
2104 final DownloadManager manager =
2105 (DownloadManager) mActivity.getSystemService(Context.DOWNLOAD_SERVICE);
2106 manager.addCompletedDownload(target.getName(),
2107 mActivity.getTitle().toString(), false,
2108 uri.getMimeType(), target.getAbsolutePath(),
2109 (long)uri.getData().length, false);
2110 } catch (IOException e) {
2111 Log.e(LOGTAG, "Could not save data URL");
2112 } finally {
2113 if (outputStream != null) {
2114 try {
2115 outputStream.close();
2116 } catch (IOException e) {
2117 // ignore close errors
2118 }
2119 }
2120 }
2121 }
2122
2123 /**
2124 * Creates a File based on the current time stamp and uses
2125 * the mime type of the DataUri to get the extension.
2126 */
2127 private File getTarget(DataUri uri) throws IOException {
2128 File dir = mActivity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
2129 DateFormat format = new SimpleDateFormat(IMAGE_BASE_FORMAT);
2130 String nameBase = format.format(new Date());
2131 String mimeType = uri.getMimeType();
2132 MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
2133 String extension = mimeTypeMap.getExtensionFromMimeType(mimeType);
2134 if (extension == null) {
2135 Log.w(LOGTAG, "Unknown mime type in data URI" + mimeType);
2136 extension = FALLBACK_EXTENSION;
2137 }
2138 extension = "." + extension; // createTempFile needs the '.'
2139 File targetFile = File.createTempFile(nameBase, extension, dir);
2140 return targetFile;
2141 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002142 }
2143
Cary Clark8974d282010-11-22 10:46:05 -05002144 private static class SelectText implements OnMenuItemClickListener {
2145 private WebView mWebView;
2146
2147 public boolean onMenuItemClick(MenuItem item) {
2148 if (mWebView != null) {
2149 return mWebView.selectText();
2150 }
2151 return false;
2152 }
2153
2154 public SelectText(WebView webView) {
2155 mWebView = webView;
2156 }
2157
2158 }
2159
Michael Kolb8233fac2010-10-26 16:08:53 -07002160 /********************** TODO: UI stuff *****************************/
2161
2162 // these methods have been copied, they still need to be cleaned up
2163
2164 /****************** tabs ***************************************************/
2165
2166 // basic tab interactions:
2167
2168 // it is assumed that tabcontrol already knows about the tab
2169 protected void addTab(Tab tab) {
2170 mUi.addTab(tab);
2171 }
2172
2173 protected void removeTab(Tab tab) {
2174 mUi.removeTab(tab);
2175 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002176 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002177 }
2178
Michael Kolbf2055602011-04-09 17:20:03 -07002179 @Override
2180 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002181 // monkey protection against delayed start
2182 if (tab != null) {
2183 mTabControl.setCurrentTab(tab);
2184 // the tab is guaranteed to have a webview after setCurrentTab
2185 mUi.setActiveTab(tab);
2186 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002187 }
2188
John Reck8bcafc12011-08-29 16:43:02 -07002189 protected void closeEmptyTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002190 Tab current = mTabControl.getCurrentTab();
2191 if (current != null
2192 && current.getWebView().copyBackForwardList().getSize() == 0) {
John Reck8bcafc12011-08-29 16:43:02 -07002193 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002194 }
2195 }
2196
John Reck26b18322011-06-21 13:08:58 -07002197 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002198 // Dismiss the subwindow if applicable.
2199 dismissSubWindow(appTab);
2200 // Since we might kill the WebView, remove it from the
2201 // content view first.
2202 mUi.detachTab(appTab);
2203 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002204 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002205 // TODO: analyze why the remove and add are necessary
2206 mUi.attachTab(appTab);
2207 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002208 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002209 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002210 } else {
2211 // If the tab was the current tab, we have to attach
2212 // it to the view system again.
2213 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002214 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002215 }
2216 }
2217
2218 // Remove the sub window if it exists. Also called by TabControl when the
2219 // user clicks the 'X' to dismiss a sub window.
2220 public void dismissSubWindow(Tab tab) {
2221 removeSubWindow(tab);
2222 // dismiss the subwindow. This will destroy the WebView.
2223 tab.dismissSubWindow();
Michael Kolbe8c97572011-11-21 14:03:56 -08002224 WebView wv = getCurrentTopWebView();
2225 if (wv != null) {
2226 wv.requestFocus();
2227 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002228 }
2229
2230 @Override
2231 public void removeSubWindow(Tab t) {
2232 if (t.getSubWebView() != null) {
2233 mUi.removeSubWindow(t.getSubViewContainer());
2234 }
2235 }
2236
2237 @Override
2238 public void attachSubWindow(Tab tab) {
2239 if (tab.getSubWebView() != null) {
2240 mUi.attachSubWindow(tab.getSubViewContainer());
2241 getCurrentTopWebView().requestFocus();
2242 }
2243 }
2244
Mathew Inwood29721c22011-06-29 17:55:24 +01002245 private Tab showPreloadedTab(final UrlData urlData) {
2246 if (!urlData.isPreloaded()) {
2247 return null;
2248 }
2249 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2250 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2251 if (sbQuery != null) {
Mathew Inwood9ad1eac2011-09-15 11:29:50 +01002252 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002253 // Could not submit query. Fallback to regular tab creation
2254 tabControl.destroy();
2255 return null;
2256 }
2257 }
Michael Kolbff6a7482011-07-26 16:37:15 -07002258 // check tab count and make room for new tab
2259 if (!mTabControl.canCreateNewTab()) {
2260 Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
2261 if (leastUsed != null) {
2262 closeTab(leastUsed);
2263 }
2264 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002265 Tab t = tabControl.getTab();
Mathew Inwoode09305e2011-09-02 12:03:26 +01002266 t.refreshIdAfterPreload();
Mathew Inwood29721c22011-06-29 17:55:24 +01002267 mTabControl.addPreloadedTab(t);
2268 addTab(t);
2269 setActiveTab(t);
2270 return t;
2271 }
2272
Michael Kolb7bcafde2011-05-09 13:55:59 -07002273 // open a non inconito tab with the given url data
2274 // and set as active tab
2275 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002276 Tab tab = showPreloadedTab(urlData);
2277 if (tab == null) {
2278 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002279 if ((tab != null) && !urlData.isEmpty()) {
2280 loadUrlDataIn(tab, urlData);
2281 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002282 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002283 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002284 }
2285
Michael Kolb843510f2010-12-09 10:51:49 -08002286 @Override
2287 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002288 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002289 }
2290
Michael Kolb8233fac2010-10-26 16:08:53 -07002291 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002292 public Tab openIncognitoTab() {
2293 return openTab(INCOGNITO_URI, true, true, false);
2294 }
2295
2296 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002297 public Tab openTab(String url, boolean incognito, boolean setActive,
2298 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002299 return openTab(url, incognito, setActive, useCurrent, null);
2300 }
2301
2302 @Override
2303 public Tab openTab(String url, Tab parent, boolean setActive,
2304 boolean useCurrent) {
2305 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2306 setActive, useCurrent, parent);
2307 }
2308
2309 public Tab openTab(String url, boolean incognito, boolean setActive,
2310 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002311 Tab tab = createNewTab(incognito, setActive, useCurrent);
2312 if (tab != null) {
John Reck5949c662011-05-27 09:52:29 -07002313 if (parent != null && parent != tab) {
2314 parent.addChildTab(tab);
2315 }
Michael Kolb519d2282011-05-09 17:03:19 -07002316 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002317 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002318 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002319 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002320 return tab;
2321 }
2322
2323 // this method will attempt to create a new tab
2324 // incognito: private browsing tab
2325 // setActive: ste tab as current tab
2326 // useCurrent: if no new tab can be created, return current tab
2327 private Tab createNewTab(boolean incognito, boolean setActive,
2328 boolean useCurrent) {
2329 Tab tab = null;
2330 if (mTabControl.canCreateNewTab()) {
2331 tab = mTabControl.createNewTab(incognito);
2332 addTab(tab);
2333 if (setActive) {
2334 setActiveTab(tab);
2335 }
2336 } else {
2337 if (useCurrent) {
2338 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002339 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002340 } else {
2341 mUi.showMaxTabsWarning();
2342 }
2343 }
2344 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002345 }
2346
John Reck2bc80422011-06-30 15:11:49 -07002347 @Override
2348 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2349 SnapshotTab tab = null;
2350 if (mTabControl.canCreateNewTab()) {
2351 tab = mTabControl.createSnapshotTab(snapshotId);
2352 addTab(tab);
2353 if (setActive) {
2354 setActiveTab(tab);
2355 }
2356 } else {
2357 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07002358 }
2359 return tab;
2360 }
2361
Michael Kolb8233fac2010-10-26 16:08:53 -07002362 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002363 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002364 * @return boolean True if we successfully switched to a different tab. If
2365 * the indexth tab is null, or if that tab is the same as
2366 * the current one, return false.
2367 */
2368 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002369 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002370 Tab currentTab = mTabControl.getCurrentTab();
2371 if (tab == null || tab == currentTab) {
2372 return false;
2373 }
2374 setActiveTab(tab);
2375 return true;
2376 }
2377
2378 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002379 public void closeCurrentTab() {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002380 closeCurrentTab(false);
2381 }
2382
2383 protected void closeCurrentTab(boolean andQuit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002384 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07002385 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07002386 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08002387 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002388 return;
2389 }
Michael Kolbc831b632011-05-11 09:30:34 -07002390 final Tab current = mTabControl.getCurrentTab();
2391 final int pos = mTabControl.getCurrentPosition();
2392 Tab newTab = current.getParent();
2393 if (newTab == null) {
2394 newTab = mTabControl.getTab(pos + 1);
2395 if (newTab == null) {
2396 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002397 }
2398 }
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002399 if (andQuit) {
2400 mTabControl.setCurrentTab(newTab);
2401 closeTab(current);
2402 } else if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002403 // Close window
2404 closeTab(current);
2405 }
2406 }
2407
2408 /**
2409 * Close the tab, remove its associated title bar, and adjust mTabControl's
2410 * current tab to a valid value.
2411 */
2412 @Override
2413 public void closeTab(Tab tab) {
John Reck28263772011-10-11 17:13:42 -07002414 if (tab == mTabControl.getCurrentTab()) {
2415 closeCurrentTab();
2416 } else {
2417 removeTab(tab);
2418 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002419 }
2420
Michael Kolb8233fac2010-10-26 16:08:53 -07002421 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07002422 protected void loadUrlFromContext(String url) {
2423 Tab tab = getCurrentTab();
2424 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002425 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07002426 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002427 url = UrlUtils.smartUrlFilter(url);
2428 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07002429 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07002430 }
2431 }
2432 }
2433
2434 /**
2435 * Load the URL into the given WebView and update the title bar
2436 * to reflect the new load. Call this instead of WebView.loadUrl
2437 * directly.
2438 * @param view The WebView used to load url.
2439 * @param url The URL to load.
2440 */
John Reck71e51422011-07-01 16:49:28 -07002441 @Override
2442 public void loadUrl(Tab tab, String url) {
John Reck26b18322011-06-21 13:08:58 -07002443 loadUrl(tab, url, null);
2444 }
2445
2446 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
2447 if (tab != null) {
2448 dismissSubWindow(tab);
2449 tab.loadUrl(url, headers);
Michael Kolba53c9892011-10-05 13:31:40 -07002450 mUi.onProgressChanged(tab);
John Reck26b18322011-06-21 13:08:58 -07002451 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002452 }
2453
2454 /**
2455 * Load UrlData into a Tab and update the title bar to reflect the new
2456 * load. Call this instead of UrlData.loadIn directly.
2457 * @param t The Tab used to load.
2458 * @param data The UrlData being loaded.
2459 */
2460 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07002461 if (data != null) {
2462 if (data.mVoiceIntent != null) {
2463 t.activateVoiceSearchMode(data.mVoiceIntent);
Michael Kolb14612442011-06-24 13:06:29 -07002464 } else if (data.isPreloaded()) {
2465 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07002466 } else {
2467 loadUrl(t, data.mUrl, data.mHeaders);
2468 }
2469 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002470 }
2471
John Reck30c714c2010-12-16 17:30:34 -08002472 @Override
2473 public void onUserCanceledSsl(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08002474 // TODO: Figure out the "right" behavior
John Reckef654f12011-07-12 16:42:08 -07002475 if (tab.canGoBack()) {
2476 tab.goBack();
John Reck30c714c2010-12-16 17:30:34 -08002477 } else {
John Reckef654f12011-07-12 16:42:08 -07002478 tab.loadUrl(mSettings.getHomePage(), null);
John Reck30c714c2010-12-16 17:30:34 -08002479 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002480 }
2481
2482 void goBackOnePageOrQuit() {
2483 Tab current = mTabControl.getCurrentTab();
2484 if (current == null) {
2485 /*
2486 * Instead of finishing the activity, simply push this to the back
2487 * of the stack and let ActivityManager to choose the foreground
2488 * activity. As BrowserActivity is singleTask, it will be always the
2489 * root of the task. So we can use either true or false for
2490 * moveTaskToBack().
2491 */
2492 mActivity.moveTaskToBack(true);
2493 return;
2494 }
John Reckef654f12011-07-12 16:42:08 -07002495 if (current.canGoBack()) {
2496 current.goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07002497 } else {
2498 // Check to see if we are closing a window that was created by
2499 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002500 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002501 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002502 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002503 // Now we close the other tab
2504 closeTab(current);
2505 } else {
Michael Kolbe28b3472011-08-04 16:54:31 -07002506 if ((current.getAppId() != null) || current.closeOnBack()) {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002507 closeCurrentTab(true);
Michael Kolbe28b3472011-08-04 16:54:31 -07002508 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002509 /*
2510 * Instead of finishing the activity, simply push this to the back
2511 * of the stack and let ActivityManager to choose the foreground
2512 * activity. As BrowserActivity is singleTask, it will be always the
2513 * root of the task. So we can use either true or false for
2514 * moveTaskToBack().
2515 */
2516 mActivity.moveTaskToBack(true);
2517 }
2518 }
2519 }
2520
2521 /**
2522 * Feed the previously stored results strings to the BrowserProvider so that
2523 * the SearchDialog will show them instead of the standard searches.
2524 * @param result String to show on the editable line of the SearchDialog.
2525 */
2526 @Override
2527 public void showVoiceSearchResults(String result) {
2528 ContentProviderClient client = mActivity.getContentResolver()
2529 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2530 ContentProvider prov = client.getLocalContentProvider();
2531 BrowserProvider bp = (BrowserProvider) prov;
2532 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2533 client.release();
2534
2535 Bundle bundle = createGoogleSearchSourceBundle(
2536 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2537 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2538 startSearch(result, false, bundle, false);
2539 }
2540
2541 private void startSearch(String initialQuery, boolean selectInitialQuery,
2542 Bundle appSearchData, boolean globalSearch) {
2543 if (appSearchData == null) {
2544 appSearchData = createGoogleSearchSourceBundle(
2545 GOOGLE_SEARCH_SOURCE_TYPE);
2546 }
2547
2548 SearchEngine searchEngine = mSettings.getSearchEngine();
2549 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2550 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2551 }
2552 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2553 globalSearch);
2554 }
2555
2556 private Bundle createGoogleSearchSourceBundle(String source) {
2557 Bundle bundle = new Bundle();
2558 bundle.putString(Search.SOURCE, source);
2559 return bundle;
2560 }
2561
2562 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002563 * helper method for key handler
2564 * returns the current tab if it can't advance
2565 */
Michael Kolbc831b632011-05-11 09:30:34 -07002566 private Tab getNextTab() {
2567 return mTabControl.getTab(Math.min(mTabControl.getTabCount() - 1,
2568 mTabControl.getCurrentPosition() + 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002569 }
2570
2571 /**
2572 * helper method for key handler
2573 * returns the current tab if it can't advance
2574 */
Michael Kolbc831b632011-05-11 09:30:34 -07002575 private Tab getPrevTab() {
2576 return mTabControl.getTab(Math.max(0,
2577 mTabControl.getCurrentPosition() - 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002578 }
2579
2580 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002581 * handle key events in browser
2582 *
2583 * @param keyCode
2584 * @param event
2585 * @return true if handled, false to pass to super
2586 */
2587 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002588 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002589 // Even if MENU is already held down, we need to call to super to open
2590 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002591 if (!noModifiers
2592 && ((KeyEvent.KEYCODE_MENU == keyCode)
2593 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2594 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002595 mMenuIsDown = true;
2596 return false;
2597 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002598
Cary Clark8ff8c662010-12-29 15:03:05 -05002599 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07002600 Tab tab = getCurrentTab();
2601 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05002602
Cary Clark160bbb92011-01-10 11:17:07 -05002603 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2604 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002605
Michael Kolb8233fac2010-10-26 16:08:53 -07002606 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002607 case KeyEvent.KEYCODE_TAB:
2608 if (event.isCtrlPressed()) {
2609 if (event.isShiftPressed()) {
2610 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002611 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002612 } else {
2613 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002614 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002615 }
2616 return true;
2617 }
2618 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002619 case KeyEvent.KEYCODE_SPACE:
2620 // WebView/WebTextView handle the keys in the KeyDown. As
2621 // the Activity's shortcut keys are only handled when WebView
2622 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002623 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002624 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002625 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002626 pageDown();
2627 }
2628 return true;
2629 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002630 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002631 event.startTracking();
2632 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07002633 case KeyEvent.KEYCODE_FORWARD:
2634 if (!noModifiers) break;
2635 tab.goForward();
2636 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002637 case KeyEvent.KEYCODE_DPAD_LEFT:
2638 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002639 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05002640 return true;
2641 }
2642 break;
2643 case KeyEvent.KEYCODE_DPAD_RIGHT:
2644 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002645 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05002646 return true;
2647 }
2648 break;
2649 case KeyEvent.KEYCODE_A:
2650 if (ctrl) {
2651 webView.selectAll();
2652 return true;
2653 }
2654 break;
Michael Kolba4183062011-01-16 10:43:21 -08002655// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002656 case KeyEvent.KEYCODE_C:
2657 if (ctrl) {
2658 webView.copySelection();
2659 return true;
2660 }
2661 break;
Michael Kolba4183062011-01-16 10:43:21 -08002662// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002663// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002664// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002665// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002666// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002667// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002668// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002669// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002670// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002671// case KeyEvent.KEYCODE_M: // unused
2672// case KeyEvent.KEYCODE_N: // in Chrome: new window
2673// case KeyEvent.KEYCODE_O: // in Chrome: open file
2674// case KeyEvent.KEYCODE_P: // in Chrome: print page
2675// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002676// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002677// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2678 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002679 // we can't use the ctrl/shift flags, they check for
2680 // exclusive use of a modifier
2681 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002682 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002683 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002684 } else {
2685 openTabToHomePage();
2686 }
2687 return true;
2688 }
2689 break;
2690// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2691// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb5ae15bd2011-08-16 17:09:27 -07002692// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002693// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2694// case KeyEvent.KEYCODE_Y: // unused
2695// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002696 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002697 // it is a regular key and webview is not null
2698 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002699 }
2700
John Recke6bf4ab2011-02-24 15:48:05 -08002701 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2702 switch(keyCode) {
2703 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07002704 if (mUi.isWebShowing()) {
Michael Kolb315d5022011-10-13 12:47:11 -07002705 bookmarksOrHistoryPicker(ComboViews.History);
John Recke6bf4ab2011-02-24 15:48:05 -08002706 return true;
2707 }
2708 break;
2709 }
2710 return false;
2711 }
2712
Michael Kolb8233fac2010-10-26 16:08:53 -07002713 boolean onKeyUp(int keyCode, KeyEvent event) {
Michael Kolb2814a362011-05-19 15:49:41 -07002714 if (KeyEvent.KEYCODE_MENU == keyCode) {
2715 mMenuIsDown = false;
2716 if (event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002717 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002718 }
2719 }
Cary Clark160bbb92011-01-10 11:17:07 -05002720 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002721 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002722 case KeyEvent.KEYCODE_BACK:
2723 if (event.isTracking() && !event.isCanceled()) {
2724 onBackKey();
2725 return true;
2726 }
2727 break;
2728 }
2729 return false;
2730 }
2731
2732 public boolean isMenuDown() {
2733 return mMenuIsDown;
2734 }
2735
Ben Murdoch8029a772010-11-16 11:58:21 +00002736 public void setupAutoFill(Message message) {
2737 // Open the settings activity at the AutoFill profile fragment so that
2738 // the user can create a new profile. When they return, we will dispatch
2739 // the message so that we can autofill the form using their new profile.
2740 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2741 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2742 AutoFillSettingsFragment.class.getName());
2743 mAutoFillSetupMessage = message;
2744 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2745 }
John Reckb3417f02011-01-14 11:01:05 -08002746
Michael Kolbfbc579a2011-07-07 15:59:33 -07002747 public boolean onSearchRequested() {
2748 mUi.editUrl(false);
2749 return true;
2750 }
2751
John Reck1cf4b792011-07-26 10:22:22 -07002752 @Override
2753 public boolean shouldCaptureThumbnails() {
2754 return mUi.shouldCaptureThumbnails();
2755 }
2756
Michael Kolbc3af0672011-08-09 10:24:41 -07002757 @Override
2758 public void setBlockEvents(boolean block) {
2759 mBlockEvents = block;
2760 }
2761
2762 public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002763 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002764 }
2765
2766 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002767 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002768 }
2769
2770 public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002771 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002772 }
2773
2774 public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002775 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002776 }
2777
2778 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002779 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002780 }
2781
Michael Kolb8233fac2010-10-26 16:08:53 -07002782}