blob: e7013168560095bf4834e8513bc61559771451e6 [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
210 private boolean mInLoad;
211
212 private boolean mActivityPaused = true;
213 private boolean mLoadStopped;
214
215 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500216 // Checks to see when the bookmarks database has changed, and updates the
217 // Tabs' notion of whether they represent bookmarked sites.
218 private ContentObserver mBookmarksObserver;
John Reck847b5322011-04-14 17:02:18 -0700219 private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700220
Michael Kolbc3af0672011-08-09 10:24:41 -0700221 private boolean mBlockEvents;
222
John Reckbc490d22011-07-22 15:04:59 -0700223 public Controller(Activity browser, boolean preloadCrashState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700224 mActivity = browser;
225 mSettings = BrowserSettings.getInstance();
226 mTabControl = new TabControl(this);
227 mSettings.setController(this);
John Reck378a4102011-06-09 16:23:01 -0700228 mCrashRecoveryHandler = CrashRecoveryHandler.initialize(this);
John Reckbc490d22011-07-22 15:04:59 -0700229 if (preloadCrashState) {
230 mCrashRecoveryHandler.preloadCrashState();
231 }
Michael Kolb14612442011-06-24 13:06:29 -0700232 mFactory = new BrowserWebViewFactory(browser);
Michael Kolb8233fac2010-10-26 16:08:53 -0700233
234 mUrlHandler = new UrlHandler(this);
235 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700236 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
237
Michael Kolb8233fac2010-10-26 16:08:53 -0700238 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500239 mBookmarksObserver = new ContentObserver(mHandler) {
240 @Override
241 public void onChange(boolean selfChange) {
242 int size = mTabControl.getTabCount();
243 for (int i = 0; i < size; i++) {
244 mTabControl.getTab(i).updateBookmarkedStatus();
245 }
246 }
247
248 };
249 browser.getContentResolver().registerContentObserver(
250 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700251
252 mNetworkHandler = new NetworkStateHandler(mActivity, this);
253 // Start watching the default geolocation permissions
254 mSystemAllowGeolocationOrigins =
255 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
256 mSystemAllowGeolocationOrigins.start();
257
John Reckaf262e72011-07-25 13:55:44 -0700258 openIconDatabase();
Michael Kolb8233fac2010-10-26 16:08:53 -0700259 }
260
Patrick Scott7d50a932011-02-04 09:27:26 -0500261 void start(final Bundle icicle, final Intent intent) {
Guang Zhu9e78f512011-05-04 11:45:11 -0700262 boolean noCrashRecovery = intent.getBooleanExtra(NO_CRASH_RECOVERY, false);
263 if (icicle != null || noCrashRecovery) {
Michael Kolb938db802011-10-11 10:49:05 -0700264 doStart(icicle, intent, false);
John Reck847b5322011-04-14 17:02:18 -0700265 } else {
266 mCrashRecoveryHandler.startRecovery(intent);
267 }
268 }
269
Michael Kolb938db802011-10-11 10:49:05 -0700270 void doStart(final Bundle icicle, final Intent intent, final boolean fromCrash) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700271 // Unless the last browser usage was within 24 hours, destroy any
272 // remaining incognito tabs.
273
274 Calendar lastActiveDate = icicle != null ?
275 (Calendar) icicle.getSerializable("lastActiveDate") : null;
276 Calendar today = Calendar.getInstance();
277 Calendar yesterday = Calendar.getInstance();
278 yesterday.add(Calendar.DATE, -1);
279
Patrick Scott7d50a932011-02-04 09:27:26 -0500280 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700281 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800282 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700283
Patrick Scott7d50a932011-02-04 09:27:26 -0500284 // Find out if we will restore any state and remember the tab.
Michael Kolbc831b632011-05-11 09:30:34 -0700285 final long currentTabId =
Patrick Scott7d50a932011-02-04 09:27:26 -0500286 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000287
Michael Kolbc831b632011-05-11 09:30:34 -0700288 if (currentTabId == -1) {
Patrick Scott7d50a932011-02-04 09:27:26 -0500289 // Not able to restore so we go ahead and clear session cookies. We
290 // must do this before trying to login the user as we don't want to
291 // clear any session cookies set during login.
292 CookieManager.getInstance().removeSessionCookie();
293 }
294
Patrick Scottd43e75a2011-03-14 14:47:23 -0400295 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500296 new Runnable() {
297 @Override public void run() {
Michael Kolb938db802011-10-11 10:49:05 -0700298 onPreloginFinished(icicle, intent, currentTabId, restoreIncognitoTabs,
299 fromCrash);
Patrick Scott7d50a932011-02-04 09:27:26 -0500300 }
301 });
302 }
303
Michael Kolbc831b632011-05-11 09:30:34 -0700304 private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId,
Michael Kolb938db802011-10-11 10:49:05 -0700305 boolean restoreIncognitoTabs, boolean fromCrash) {
Michael Kolbc831b632011-05-11 09:30:34 -0700306 if (currentTabId == -1) {
John Reck1cf4b792011-07-26 10:22:22 -0700307 BackgroundHandler.execute(new PruneThumbnails(mActivity, null));
Michael Kolb8233fac2010-10-26 16:08:53 -0700308 final Bundle extra = intent.getExtras();
309 // Create an initial tab.
310 // If the intent is ACTION_VIEW and data is not null, the Browser is
311 // invoked to view the content by another application. In this case,
312 // the tab will be close when exit.
Michael Kolb14612442011-06-24 13:06:29 -0700313 UrlData urlData = IntentHandler.getUrlDataFromIntent(intent);
Michael Kolb7bcafde2011-05-09 13:55:59 -0700314 Tab t = null;
315 if (urlData.isEmpty()) {
316 t = openTabToHomePage();
317 } else {
318 t = openTab(urlData);
319 }
320 if (t != null) {
321 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
322 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700323 WebView webView = t.getWebView();
324 if (extra != null) {
325 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
326 if (scale > 0 && scale <= 1000) {
327 webView.setInitialScale(scale);
328 }
329 }
John Reckd8c74522011-06-14 08:45:00 -0700330 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700331 } else {
Michael Kolbc831b632011-05-11 09:30:34 -0700332 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
Patrick Scott7d50a932011-02-04 09:27:26 -0500333 mUi.needsRestoreAllTabs());
John Reck1cf4b792011-07-26 10:22:22 -0700334 List<Tab> tabs = mTabControl.getTabs();
335 ArrayList<Long> restoredTabs = new ArrayList<Long>(tabs.size());
336 for (Tab t : tabs) {
337 restoredTabs.add(t.getId());
338 }
339 BackgroundHandler.execute(new PruneThumbnails(mActivity, restoredTabs));
John Reck52be4782011-08-26 15:37:29 -0700340 if (tabs.size() == 0) {
341 openTabToHomePage();
342 }
John Reck1cf4b792011-07-26 10:22:22 -0700343 mUi.updateTabs(tabs);
Michael Kolb8233fac2010-10-26 16:08:53 -0700344 // TabControl.restoreState() will create a new tab even if
345 // restoring the state fails.
346 setActiveTab(mTabControl.getCurrentTab());
John Reck9dd4a412011-10-05 14:55:30 -0700347 // Handle the intent if needed. If icicle != null, we are restoring
348 // and the intent will be stale - ignore it.
Michael Kolb938db802011-10-11 10:49:05 -0700349 if (icicle == null || fromCrash) {
John Reck9dd4a412011-10-05 14:55:30 -0700350 mIntentHandler.onNewIntent(intent);
351 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700352 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700353 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700354 String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb8233fac2010-10-26 16:08:53 -0700355 if (jsFlags.trim().length() != 0) {
356 getCurrentWebView().setJsFlags(jsFlags);
357 }
John Reck439c9a52010-12-14 10:04:39 -0800358 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
Michael Kolb315d5022011-10-13 12:47:11 -0700359 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
John Reck439c9a52010-12-14 10:04:39 -0800360 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700361 }
362
John Reck1cf4b792011-07-26 10:22:22 -0700363 private static class PruneThumbnails implements Runnable {
364 private Context mContext;
365 private List<Long> mIds;
366
367 PruneThumbnails(Context context, List<Long> preserveIds) {
368 mContext = context.getApplicationContext();
369 mIds = preserveIds;
370 }
371
372 @Override
373 public void run() {
374 ContentResolver cr = mContext.getContentResolver();
375 if (mIds == null || mIds.size() == 0) {
376 cr.delete(Thumbnails.CONTENT_URI, null, null);
377 } else {
378 int length = mIds.size();
379 StringBuilder where = new StringBuilder();
380 where.append(Thumbnails._ID);
381 where.append(" not in (");
382 for (int i = 0; i < length; i++) {
383 where.append(mIds.get(i));
384 if (i < (length - 1)) {
385 where.append(",");
386 }
387 }
388 where.append(")");
389 cr.delete(Thumbnails.CONTENT_URI, where.toString(), null);
390 }
391 }
392
393 }
394
Michael Kolb1514bb72010-11-22 09:11:48 -0800395 @Override
396 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700397 return mFactory;
398 }
399
400 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800401 public void onSetWebView(Tab tab, WebView view) {
402 mUi.onSetWebView(tab, view);
403 }
404
405 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800406 public void createSubWindow(Tab tab) {
407 endActionMode();
408 WebView mainView = tab.getWebView();
409 WebView subView = mFactory.createWebView((mainView == null)
410 ? false
411 : mainView.isPrivateBrowsingEnabled());
412 mUi.createSubWindow(tab, subView);
413 }
414
415 @Override
Michael Kolb14612442011-06-24 13:06:29 -0700416 public Context getContext() {
417 return mActivity;
418 }
419
420 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700421 public Activity getActivity() {
422 return mActivity;
423 }
424
425 void setUi(UI ui) {
426 mUi = ui;
427 }
428
429 BrowserSettings getSettings() {
430 return mSettings;
431 }
432
433 IntentHandler getIntentHandler() {
434 return mIntentHandler;
435 }
436
437 @Override
438 public UI getUi() {
439 return mUi;
440 }
441
442 int getMaxTabs() {
443 return mActivity.getResources().getInteger(R.integer.max_tabs);
444 }
445
446 @Override
447 public TabControl getTabControl() {
448 return mTabControl;
449 }
450
Michael Kolb1bf23132010-11-19 12:55:12 -0800451 @Override
452 public List<Tab> getTabs() {
453 return mTabControl.getTabs();
454 }
455
John Reckaf262e72011-07-25 13:55:44 -0700456 // Open the icon database.
457 private void openIconDatabase() {
458 // We have to call getInstance on the UI thread
459 final WebIconDatabase instance = WebIconDatabase.getInstance();
460 BackgroundHandler.execute(new Runnable() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000461
John Reckaf262e72011-07-25 13:55:44 -0700462 @Override
463 public void run() {
464 instance.open(mActivity.getDir("icons", 0).getPath());
Michael Kolb8233fac2010-10-26 16:08:53 -0700465 }
John Reckaf262e72011-07-25 13:55:44 -0700466 });
Michael Kolb8233fac2010-10-26 16:08:53 -0700467 }
468
469 private void startHandler() {
470 mHandler = new Handler() {
471
472 @Override
473 public void handleMessage(Message msg) {
474 switch (msg.what) {
475 case OPEN_BOOKMARKS:
Michael Kolb315d5022011-10-13 12:47:11 -0700476 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
Michael Kolb8233fac2010-10-26 16:08:53 -0700477 break;
478 case FOCUS_NODE_HREF:
479 {
480 String url = (String) msg.getData().get("url");
481 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500482 String src = (String) msg.getData().get("src");
483 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700484 if (TextUtils.isEmpty(url)) {
485 break;
486 }
487 HashMap focusNodeMap = (HashMap) msg.obj;
488 WebView view = (WebView) focusNodeMap.get("webview");
489 // Only apply the action if the top window did not change.
490 if (getCurrentTopWebView() != view) {
491 break;
492 }
493 switch (msg.arg1) {
494 case R.id.open_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700495 loadUrlFromContext(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700496 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500497 case R.id.view_image_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700498 loadUrlFromContext(src);
Cary Clark043c2d62010-12-15 11:19:39 -0500499 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500500 case R.id.open_newtab_context_menu_id:
501 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -0700502 openTab(url, parent,
503 !mSettings.openInBackground(), true);
Leon Scroggins026f2542010-11-22 13:26:12 -0500504 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700505 case R.id.copy_link_context_menu_id:
506 copy(url);
507 break;
508 case R.id.save_link_context_menu_id:
509 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500510 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000511 mActivity, url, null, null, null,
512 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700513 break;
514 }
515 break;
516 }
517
518 case LOAD_URL:
John Reck26b18322011-06-21 13:08:58 -0700519 loadUrlFromContext((String) msg.obj);
Michael Kolb8233fac2010-10-26 16:08:53 -0700520 break;
521
522 case STOP_LOAD:
523 stopLoading();
524 break;
525
526 case RELEASE_WAKELOCK:
John Reckf57c0292011-07-21 18:15:39 -0700527 if (mWakeLock != null && mWakeLock.isHeld()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700528 mWakeLock.release();
529 // if we reach here, Browser should be still in the
530 // background loading after WAKELOCK_TIMEOUT (5-min).
531 // To avoid burning the battery, stop loading.
532 mTabControl.stopAllLoading();
533 }
534 break;
535
536 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800537 Tab tab = (Tab) msg.obj;
538 if (tab != null) {
539 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700540 }
541 break;
542 }
543 }
544 };
545
546 }
547
John Reckef654f12011-07-12 16:42:08 -0700548 @Override
Martijn Coenenb2f93552011-06-14 10:48:35 +0200549 public Tab getCurrentTab() {
550 return mTabControl.getCurrentTab();
551 }
552
Michael Kolbba99c5d2010-11-29 14:57:41 -0800553 @Override
554 public void shareCurrentPage() {
555 shareCurrentPage(mTabControl.getCurrentTab());
556 }
557
558 private void shareCurrentPage(Tab tab) {
559 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800560 sharePage(mActivity, tab.getTitle(),
561 tab.getUrl(), tab.getFavicon(),
562 createScreenshot(tab.getWebView(),
563 getDesiredThumbnailWidth(mActivity),
564 getDesiredThumbnailHeight(mActivity)));
565 }
566 }
567
Michael Kolb8233fac2010-10-26 16:08:53 -0700568 /**
569 * Share a page, providing the title, url, favicon, and a screenshot. Uses
570 * an {@link Intent} to launch the Activity chooser.
571 * @param c Context used to launch a new Activity.
572 * @param title Title of the page. Stored in the Intent with
573 * {@link Intent#EXTRA_SUBJECT}
574 * @param url URL of the page. Stored in the Intent with
575 * {@link Intent#EXTRA_TEXT}
576 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
577 * with {@link Browser#EXTRA_SHARE_FAVICON}
578 * @param screenshot Bitmap of a screenshot of the page. Stored in the
579 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
580 */
581 static final void sharePage(Context c, String title, String url,
582 Bitmap favicon, Bitmap screenshot) {
583 Intent send = new Intent(Intent.ACTION_SEND);
584 send.setType("text/plain");
585 send.putExtra(Intent.EXTRA_TEXT, url);
586 send.putExtra(Intent.EXTRA_SUBJECT, title);
587 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
588 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
589 try {
590 c.startActivity(Intent.createChooser(send, c.getString(
591 R.string.choosertitle_sharevia)));
592 } catch(android.content.ActivityNotFoundException ex) {
593 // if no app handles it, do nothing
594 }
595 }
596
597 private void copy(CharSequence text) {
598 ClipboardManager cm = (ClipboardManager) mActivity
599 .getSystemService(Context.CLIPBOARD_SERVICE);
600 cm.setText(text);
601 }
602
603 // lifecycle
604
605 protected void onConfgurationChanged(Configuration config) {
606 mConfigChanged = true;
607 if (mPageDialogsHandler != null) {
608 mPageDialogsHandler.onConfigurationChanged(config);
609 }
610 mUi.onConfigurationChanged(config);
611 }
612
613 @Override
614 public void handleNewIntent(Intent intent) {
Michael Kolb59e232c2011-08-18 17:19:53 -0700615 if (!mUi.isWebShowing()) {
616 mUi.showWeb(false);
617 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700618 mIntentHandler.onNewIntent(intent);
619 }
620
621 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800622 if (mUi.isCustomViewShowing()) {
623 hideCustomView();
624 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700625 if (mActivityPaused) {
626 Log.e(LOGTAG, "BrowserActivity is already paused.");
627 return;
628 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700629 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800630 Tab tab = mTabControl.getCurrentTab();
631 if (tab != null) {
632 tab.pause();
633 if (!pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700634 if (mWakeLock == null) {
635 PowerManager pm = (PowerManager) mActivity
636 .getSystemService(Context.POWER_SERVICE);
637 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
638 }
Michael Kolb70976932010-11-30 11:34:01 -0800639 mWakeLock.acquire();
640 mHandler.sendMessageDelayed(mHandler
641 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
642 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700643 }
644 mUi.onPause();
645 mNetworkHandler.onPause();
646
647 WebView.disablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100648 NfcHandler.unregister(mActivity);
John Reckd7dd9b22011-08-30 09:18:29 -0700649 if (sThumbnailBitmap != null) {
650 sThumbnailBitmap.recycle();
651 sThumbnailBitmap = null;
652 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700653 }
654
John Reck1cf4b792011-07-26 10:22:22 -0700655 void onSaveInstanceState(Bundle outState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700656 // the default implementation requires each view to have an id. As the
657 // browser handles the state itself and it doesn't use id for the views,
658 // don't call the default implementation. Otherwise it will trigger the
659 // warning like this, "couldn't save which view has focus because the
660 // focused view XXX has no id".
661
662 // Save all the tabs
John Reck1cf4b792011-07-26 10:22:22 -0700663 mTabControl.saveState(outState);
John Reck24f18262011-06-17 14:47:20 -0700664 if (!outState.isEmpty()) {
665 // Save time so that we know how old incognito tabs (if any) are.
666 outState.putSerializable("lastActiveDate", Calendar.getInstance());
667 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700668 }
669
670 void onResume() {
671 if (!mActivityPaused) {
672 Log.e(LOGTAG, "BrowserActivity is already resumed.");
673 return;
674 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700675 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800676 Tab current = mTabControl.getCurrentTab();
677 if (current != null) {
678 current.resume();
679 resumeWebViewTimers(current);
680 }
John Reckf57c0292011-07-21 18:15:39 -0700681 releaseWakeLock();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200682
Michael Kolb8233fac2010-10-26 16:08:53 -0700683 mUi.onResume();
684 mNetworkHandler.onResume();
685 WebView.enablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100686 NfcHandler.register(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700687 }
688
John Reckf57c0292011-07-21 18:15:39 -0700689 private void releaseWakeLock() {
690 if (mWakeLock != null && mWakeLock.isHeld()) {
691 mHandler.removeMessages(RELEASE_WAKELOCK);
692 mWakeLock.release();
693 }
694 }
695
Michael Kolb70976932010-11-30 11:34:01 -0800696 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800697 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800698 * @param tab guaranteed non-null
699 */
700 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700701 boolean inLoad = tab.inPageLoad();
702 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
703 CookieSyncManager.getInstance().startSync();
704 WebView w = tab.getWebView();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100705 WebViewTimersControl.getInstance().onBrowserActivityResume(w);
Michael Kolb8233fac2010-10-26 16:08:53 -0700706 }
707 }
708
Michael Kolb70976932010-11-30 11:34:01 -0800709 /**
710 * Pause all WebView timers using the WebView of the given tab
711 * @param tab
712 * @return true if the timers are paused or tab is null
713 */
714 private boolean pauseWebViewTimers(Tab tab) {
715 if (tab == null) {
716 return true;
717 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700718 CookieSyncManager.getInstance().stopSync();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100719 WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView());
Michael Kolb8233fac2010-10-26 16:08:53 -0700720 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700721 }
Michael Kolb70976932010-11-30 11:34:01 -0800722 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700723 }
724
725 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800726 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700727 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
728 mUploadHandler = null;
729 }
730 if (mTabControl == null) return;
731 mUi.onDestroy();
732 // Remove the current tab and sub window
733 Tab t = mTabControl.getCurrentTab();
734 if (t != null) {
735 dismissSubWindow(t);
736 removeTab(t);
737 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500738 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700739 // Destroy all the tabs
740 mTabControl.destroy();
741 WebIconDatabase.getInstance().close();
742 // Stop watching the default geolocation permissions
743 mSystemAllowGeolocationOrigins.stop();
744 mSystemAllowGeolocationOrigins = null;
745 }
746
747 protected boolean isActivityPaused() {
748 return mActivityPaused;
749 }
750
751 protected void onLowMemory() {
752 mTabControl.freeMemory();
753 }
754
755 @Override
756 public boolean shouldShowErrorConsole() {
757 return mShouldShowErrorConsole;
758 }
759
760 protected void setShouldShowErrorConsole(boolean show) {
761 if (show == mShouldShowErrorConsole) {
762 // Nothing to do.
763 return;
764 }
765 mShouldShowErrorConsole = show;
766 Tab t = mTabControl.getCurrentTab();
767 if (t == null) {
768 // There is no current tab so we cannot toggle the error console
769 return;
770 }
771 mUi.setShouldShowErrorConsole(t, show);
772 }
773
774 @Override
775 public void stopLoading() {
776 mLoadStopped = true;
777 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700778 WebView w = getCurrentTopWebView();
779 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700780 mUi.onPageStopped(tab);
781 }
782
783 boolean didUserStopLoading() {
784 return mLoadStopped;
785 }
786
787 // WebViewController
788
789 @Override
John Reck324d4402011-01-11 16:56:42 -0800790 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700791
792 // We've started to load a new page. If there was a pending message
793 // to save a screenshot then we will now take the new page and save
794 // an incorrect screenshot. Therefore, remove any pending thumbnail
795 // messages from the queue.
796 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800797 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700798
799 // reset sync timer to avoid sync starts during loading a page
800 CookieSyncManager.getInstance().resetSync();
801
802 if (!mNetworkHandler.isNetworkUp()) {
803 view.setNetworkAvailable(false);
804 }
805
806 // when BrowserActivity just starts, onPageStarted may be called before
807 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
808 // to start the timer. As we won't switch tabs while an activity is in
809 // pause state, we can ensure calling resume and pause in pair.
810 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800811 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700812 }
813 mLoadStopped = false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700814 endActionMode();
815
John Reck30c714c2010-12-16 17:30:34 -0800816 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700817
John Reck324d4402011-01-11 16:56:42 -0800818 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700819 // update the bookmark database for favicon
820 maybeUpdateFavicon(tab, null, url, favicon);
821
822 Performance.tracePageStart(url);
823
824 // Performance probe
825 if (false) {
826 Performance.onPageStarted();
827 }
828
829 }
830
831 @Override
John Reck324d4402011-01-11 16:56:42 -0800832 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800833 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800834 if (!tab.isPrivateBrowsingEnabled()
John Reckd8c74522011-06-14 08:45:00 -0700835 && !TextUtils.isEmpty(tab.getUrl())
836 && !tab.isSnapshot()) {
John Recka1696282011-07-08 14:10:37 -0700837 // Only update the bookmark screenshot if the user did not
838 // cancel the load early and there is not already
839 // a pending update for the tab.
Michael Kolb8233fac2010-10-26 16:08:53 -0700840 if (tab.inForeground() && !didUserStopLoading()
841 || !tab.inForeground()) {
John Recka1696282011-07-08 14:10:37 -0700842 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
843 mHandler.sendMessageDelayed(mHandler.obtainMessage(
844 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
845 500);
846 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700847 }
848 }
849 // pause the WebView timer and release the wake lock if it is finished
850 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800851 if (mActivityPaused && pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700852 releaseWakeLock();
Michael Kolb8233fac2010-10-26 16:08:53 -0700853 }
Martijn Coenenb2f93552011-06-14 10:48:35 +0200854
Michael Kolb8233fac2010-10-26 16:08:53 -0700855 // Performance probe
856 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800857 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700858 }
859
860 Performance.tracePageFinished();
861 }
862
863 @Override
John Reck30c714c2010-12-16 17:30:34 -0800864 public void onProgressChanged(Tab tab) {
John Reck6c2e2f32011-08-22 13:41:23 -0700865 mCrashRecoveryHandler.backupState();
John Reck30c714c2010-12-16 17:30:34 -0800866 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700867
868 if (newProgress == 100) {
869 CookieSyncManager.getInstance().sync();
870 // onProgressChanged() may continue to be called after the main
871 // frame has finished loading, as any remaining sub frames continue
872 // to load. We'll only get called once though with newProgress as
873 // 100 when everything is loaded. (onPageFinished is called once
874 // when the main frame completes loading regardless of the state of
875 // any sub frames so calls to onProgressChanges may continue after
876 // onPageFinished has executed)
877 if (mInLoad) {
878 mInLoad = false;
879 updateInLoadMenuItems(mCachedMenu);
880 }
881 } else {
882 if (!mInLoad) {
883 // onPageFinished may have already been called but a subframe is
884 // still loading and updating the progress. Reset mInLoad and
885 // update the menu items.
886 mInLoad = true;
887 updateInLoadMenuItems(mCachedMenu);
888 }
889 }
John Reck30c714c2010-12-16 17:30:34 -0800890 mUi.onProgressChanged(tab);
891 }
892
893 @Override
Steve Block2466eff2011-10-03 15:33:09 +0100894 public void onUpdatedSecurityState(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800895 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700896 }
897
898 @Override
899 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800900 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800901 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800902 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700903 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
904 return;
905 }
906 // Update the title in the history database if not in private browsing mode
907 if (!tab.isPrivateBrowsingEnabled()) {
John Reckf57c0292011-07-21 18:15:39 -0700908 DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700909 }
910 }
911
912 @Override
913 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800914 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700915 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
916 }
917
918 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800919 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
920 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700921 }
922
923 @Override
924 public boolean shouldOverrideKeyEvent(KeyEvent event) {
925 if (mMenuIsDown) {
926 // only check shortcut key when MENU is held
927 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
928 event);
929 } else {
930 return false;
931 }
932 }
933
934 @Override
935 public void onUnhandledKeyEvent(KeyEvent event) {
936 if (!isActivityPaused()) {
937 if (event.getAction() == KeyEvent.ACTION_DOWN) {
938 mActivity.onKeyDown(event.getKeyCode(), event);
939 } else {
940 mActivity.onKeyUp(event.getKeyCode(), event);
941 }
942 }
943 }
944
945 @Override
John Reck324d4402011-01-11 16:56:42 -0800946 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700947 // Don't save anything in private browsing mode
948 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800949 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700950
John Reck324d4402011-01-11 16:56:42 -0800951 if (TextUtils.isEmpty(url)
952 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700953 return;
954 }
John Reckf57c0292011-07-21 18:15:39 -0700955 DataController.getInstance(mActivity).updateVisitedHistory(url);
John Reck6c2e2f32011-08-22 13:41:23 -0700956 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -0700957 }
958
959 @Override
960 public void getVisitedHistory(final ValueCallback<String[]> callback) {
961 AsyncTask<Void, Void, String[]> task =
962 new AsyncTask<Void, Void, String[]>() {
963 @Override
964 public String[] doInBackground(Void... unused) {
965 return Browser.getVisitedHistory(mActivity.getContentResolver());
966 }
967 @Override
968 public void onPostExecute(String[] result) {
969 callback.onReceiveValue(result);
970 }
971 };
972 task.execute();
973 }
974
975 @Override
976 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
977 final HttpAuthHandler handler, final String host,
978 final String realm) {
979 String username = null;
980 String password = null;
981
982 boolean reuseHttpAuthUsernamePassword
983 = handler.useHttpAuthUsernamePassword();
984
985 if (reuseHttpAuthUsernamePassword && view != null) {
986 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
987 if (credentials != null && credentials.length == 2) {
988 username = credentials[0];
989 password = credentials[1];
990 }
991 }
992
993 if (username != null && password != null) {
994 handler.proceed(username, password);
995 } else {
Ben Murdochfdd37112011-08-05 15:48:14 +0100996 if (tab.inForeground() && !handler.suppressDialog()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700997 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
998 } else {
999 handler.cancel();
1000 }
1001 }
1002 }
1003
1004 @Override
1005 public void onDownloadStart(Tab tab, String url, String userAgent,
1006 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001007 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -05001008 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001009 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
1010 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001011 // This Tab was opened for the sole purpose of downloading a
1012 // file. Remove it.
1013 if (tab == mTabControl.getCurrentTab()) {
1014 // In this case, the Tab is still on top.
1015 goBackOnePageOrQuit();
1016 } else {
1017 // In this case, it is not.
1018 closeTab(tab);
1019 }
1020 }
1021 }
1022
1023 @Override
1024 public Bitmap getDefaultVideoPoster() {
1025 return mUi.getDefaultVideoPoster();
1026 }
1027
1028 @Override
1029 public View getVideoLoadingProgressView() {
1030 return mUi.getVideoLoadingProgressView();
1031 }
1032
1033 @Override
1034 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1035 SslError error) {
1036 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1037 }
1038
Patrick Scott92066772011-03-10 08:46:27 -05001039 @Override
1040 public void showAutoLogin(Tab tab) {
1041 assert tab.inForeground();
1042 // Update the title bar to show the auto-login request.
1043 mUi.showAutoLogin(tab);
1044 }
1045
1046 @Override
1047 public void hideAutoLogin(Tab tab) {
1048 assert tab.inForeground();
1049 mUi.hideAutoLogin(tab);
1050 }
1051
Michael Kolb8233fac2010-10-26 16:08:53 -07001052 // helper method
1053
1054 /*
1055 * Update the favorites icon if the private browsing isn't enabled and the
1056 * icon is valid.
1057 */
1058 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1059 final String url, Bitmap favicon) {
1060 if (favicon == null) {
1061 return;
1062 }
1063 if (!tab.isPrivateBrowsingEnabled()) {
1064 Bookmarks.updateFavicon(mActivity
1065 .getContentResolver(), originalUrl, url, favicon);
1066 }
1067 }
1068
Leon Scroggins4cd97792010-12-03 15:31:56 -05001069 @Override
1070 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001071 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001072 mUi.bookmarkedStatusHasChanged(tab);
1073 }
1074
Michael Kolb8233fac2010-10-26 16:08:53 -07001075 // end WebViewController
1076
1077 protected void pageUp() {
1078 getCurrentTopWebView().pageUp(false);
1079 }
1080
1081 protected void pageDown() {
1082 getCurrentTopWebView().pageDown(false);
1083 }
1084
1085 // callback from phone title bar
1086 public void editUrl() {
1087 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001088 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001089 }
1090
Michael Kolbcfa3af52010-12-14 10:36:11 -08001091 public void startVoiceSearch() {
1092 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1093 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1094 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1095 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1096 mActivity.getComponentName().flattenToString());
1097 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001098 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001099 mActivity.startActivity(intent);
1100 }
1101
Michael Kolb11d19782011-03-20 10:17:40 -07001102 @Override
1103 public void activateVoiceSearchMode(String title, List<String> results) {
1104 mUi.showVoiceTitleBar(title, results);
Michael Kolb8233fac2010-10-26 16:08:53 -07001105 }
1106
1107 public void revertVoiceSearchMode(Tab tab) {
1108 mUi.revertVoiceTitleBar(tab);
1109 }
1110
Michael Kolb736990c2011-03-20 10:01:20 -07001111 public boolean supportsVoiceSearch() {
John Reck35e9dd62011-04-25 09:01:54 -07001112 SearchEngine searchEngine = getSettings().getSearchEngine();
Michael Kolb736990c2011-03-20 10:01:20 -07001113 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1114 }
1115
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001116 public void showCustomView(Tab tab, View view, int requestedOrientation,
Michael Kolb8233fac2010-10-26 16:08:53 -07001117 WebChromeClient.CustomViewCallback callback) {
1118 if (tab.inForeground()) {
1119 if (mUi.isCustomViewShowing()) {
1120 callback.onCustomViewHidden();
1121 return;
1122 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001123 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001124 // Save the menu state and set it to empty while the custom
1125 // view is showing.
1126 mOldMenuState = mMenuState;
1127 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001128 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001129 }
1130 }
1131
1132 @Override
1133 public void hideCustomView() {
1134 if (mUi.isCustomViewShowing()) {
1135 mUi.onHideCustomView();
1136 // Reset the old menu state.
1137 mMenuState = mOldMenuState;
1138 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001139 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001140 }
1141 }
1142
1143 protected void onActivityResult(int requestCode, int resultCode,
1144 Intent intent) {
1145 if (getCurrentTopWebView() == null) return;
1146 switch (requestCode) {
1147 case PREFERENCES_PAGE:
1148 if (resultCode == Activity.RESULT_OK && intent != null) {
1149 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001150 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001151 mTabControl.removeParentChildRelationShips();
1152 }
1153 }
1154 break;
1155 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001156 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001157 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001158 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001159 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001160 case AUTOFILL_SETUP:
1161 // Determine whether a profile was actually set up or not
1162 // and if so, send the message back to the WebTextView to
1163 // fill the form with the new profile.
1164 if (getSettings().getAutoFillProfile() != null) {
1165 mAutoFillSetupMessage.sendToTarget();
1166 mAutoFillSetupMessage = null;
1167 }
1168 break;
John Reckd3e4d5b2011-07-13 15:48:43 -07001169 case COMBO_VIEW:
1170 if (intent == null || resultCode != Activity.RESULT_OK) {
1171 break;
1172 }
John Reck3ba45532011-08-11 16:26:53 -07001173 mUi.showWeb(false);
John Reckd3e4d5b2011-07-13 15:48:43 -07001174 if (Intent.ACTION_VIEW.equals(intent.getAction())) {
1175 Tab t = getCurrentTab();
1176 Uri uri = intent.getData();
1177 loadUrl(t, uri.toString());
1178 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
1179 String[] urls = intent.getStringArrayExtra(
1180 ComboViewActivity.EXTRA_OPEN_ALL);
1181 Tab parent = getCurrentTab();
1182 for (String url : urls) {
1183 parent = openTab(url, parent,
1184 !mSettings.openInBackground(), true);
1185 }
1186 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
1187 long id = intent.getLongExtra(
1188 ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
1189 if (id >= 0) {
1190 createNewSnapshotTab(id, true);
1191 }
1192 }
1193 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001194 default:
1195 break;
1196 }
1197 getCurrentTopWebView().requestFocus();
1198 }
1199
1200 /**
1201 * Open the Go page.
1202 * @param startWithHistory If true, open starting on the history tab.
1203 * Otherwise, start with the bookmarks tab.
1204 */
1205 @Override
Michael Kolb315d5022011-10-13 12:47:11 -07001206 public void bookmarksOrHistoryPicker(ComboViews startView) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001207 if (mTabControl.getCurrentWebView() == null) {
1208 return;
1209 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001210 // clear action mode
1211 if (isInCustomActionMode()) {
1212 endActionMode();
1213 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001214 Bundle extras = new Bundle();
1215 // Disable opening in a new window if we have maxed out the windows
1216 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1217 !mTabControl.canCreateNewTab());
Michael Kolb315d5022011-10-13 12:47:11 -07001218 mUi.showComboView(startView, extras);
Michael Kolb8233fac2010-10-26 16:08:53 -07001219 }
1220
1221 // combo view callbacks
1222
Michael Kolb8233fac2010-10-26 16:08:53 -07001223 // key handling
1224 protected void onBackKey() {
1225 if (!mUi.onBackKey()) {
1226 WebView subwindow = mTabControl.getCurrentSubWindow();
1227 if (subwindow != null) {
1228 if (subwindow.canGoBack()) {
1229 subwindow.goBack();
1230 } else {
1231 dismissSubWindow(mTabControl.getCurrentTab());
1232 }
1233 } else {
1234 goBackOnePageOrQuit();
1235 }
1236 }
1237 }
1238
Michael Kolb4bd767d2011-05-27 11:33:55 -07001239 protected boolean onMenuKey() {
1240 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001241 }
1242
Michael Kolb8233fac2010-10-26 16:08:53 -07001243 // menu handling and state
1244 // TODO: maybe put into separate handler
1245
1246 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckd73c5a22010-12-22 10:22:50 -08001247 if (mMenuState == EMPTY_MENU) {
1248 return false;
1249 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001250 MenuInflater inflater = mActivity.getMenuInflater();
1251 inflater.inflate(R.menu.browser, menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001252 return true;
1253 }
1254
1255 protected void onCreateContextMenu(ContextMenu menu, View v,
1256 ContextMenuInfo menuInfo) {
John Reck0f602f32011-07-07 15:38:43 -07001257 if (v instanceof TitleBar) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001258 return;
1259 }
1260 if (!(v instanceof WebView)) {
1261 return;
1262 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001263 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001264 WebView.HitTestResult result = webview.getHitTestResult();
1265 if (result == null) {
1266 return;
1267 }
1268
1269 int type = result.getType();
1270 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1271 Log.w(LOGTAG,
1272 "We should not show context menu when nothing is touched");
1273 return;
1274 }
1275 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1276 // let TextView handles context menu
1277 return;
1278 }
1279
1280 // Note, http://b/issue?id=1106666 is requesting that
1281 // an inflated menu can be used again. This is not available
1282 // yet, so inflate each time (yuk!)
1283 MenuInflater inflater = mActivity.getMenuInflater();
1284 inflater.inflate(R.menu.browsercontext, menu);
1285
1286 // Show the correct menu group
1287 final String extra = result.getExtra();
1288 menu.setGroupVisible(R.id.PHONE_MENU,
1289 type == WebView.HitTestResult.PHONE_TYPE);
1290 menu.setGroupVisible(R.id.EMAIL_MENU,
1291 type == WebView.HitTestResult.EMAIL_TYPE);
1292 menu.setGroupVisible(R.id.GEO_MENU,
1293 type == WebView.HitTestResult.GEO_TYPE);
1294 menu.setGroupVisible(R.id.IMAGE_MENU,
1295 type == WebView.HitTestResult.IMAGE_TYPE
1296 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1297 menu.setGroupVisible(R.id.ANCHOR_MENU,
1298 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1299 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001300 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1301 || type == WebView.HitTestResult.PHONE_TYPE
1302 || type == WebView.HitTestResult.EMAIL_TYPE
1303 || type == WebView.HitTestResult.GEO_TYPE;
1304 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1305 if (hitText) {
1306 menu.findItem(R.id.select_text_menu_id)
1307 .setOnMenuItemClickListener(new SelectText(webview));
1308 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001309 // Setup custom handling depending on the type
1310 switch (type) {
1311 case WebView.HitTestResult.PHONE_TYPE:
1312 menu.setHeaderTitle(Uri.decode(extra));
1313 menu.findItem(R.id.dial_context_menu_id).setIntent(
1314 new Intent(Intent.ACTION_VIEW, Uri
1315 .parse(WebView.SCHEME_TEL + extra)));
1316 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1317 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1318 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1319 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1320 addIntent);
1321 menu.findItem(R.id.copy_phone_context_menu_id)
1322 .setOnMenuItemClickListener(
1323 new Copy(extra));
1324 break;
1325
1326 case WebView.HitTestResult.EMAIL_TYPE:
1327 menu.setHeaderTitle(extra);
1328 menu.findItem(R.id.email_context_menu_id).setIntent(
1329 new Intent(Intent.ACTION_VIEW, Uri
1330 .parse(WebView.SCHEME_MAILTO + extra)));
1331 menu.findItem(R.id.copy_mail_context_menu_id)
1332 .setOnMenuItemClickListener(
1333 new Copy(extra));
1334 break;
1335
1336 case WebView.HitTestResult.GEO_TYPE:
1337 menu.setHeaderTitle(extra);
1338 menu.findItem(R.id.map_context_menu_id).setIntent(
1339 new Intent(Intent.ACTION_VIEW, Uri
1340 .parse(WebView.SCHEME_GEO
1341 + URLEncoder.encode(extra))));
1342 menu.findItem(R.id.copy_geo_context_menu_id)
1343 .setOnMenuItemClickListener(
1344 new Copy(extra));
1345 break;
1346
1347 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1348 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001349 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001350 // decide whether to show the open link in new tab option
1351 boolean showNewTab = mTabControl.canCreateNewTab();
1352 MenuItem newTabItem
1353 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001354 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001355 ? R.string.contextmenu_openlink_newwindow_background
1356 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001357 newTabItem.setVisible(showNewTab);
1358 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001359 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1360 newTabItem.setOnMenuItemClickListener(
1361 new MenuItem.OnMenuItemClickListener() {
1362 @Override
1363 public boolean onMenuItemClick(MenuItem item) {
1364 final HashMap<String, WebView> hrefMap =
1365 new HashMap<String, WebView>();
1366 hrefMap.put("webview", webview);
1367 final Message msg = mHandler.obtainMessage(
1368 FOCUS_NODE_HREF,
1369 R.id.open_newtab_context_menu_id,
1370 0, hrefMap);
1371 webview.requestFocusNodeHref(msg);
1372 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001373 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001374 });
1375 } else {
1376 newTabItem.setOnMenuItemClickListener(
1377 new MenuItem.OnMenuItemClickListener() {
1378 @Override
1379 public boolean onMenuItemClick(MenuItem item) {
1380 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001381 openTab(extra, parent,
1382 !mSettings.openInBackground(),
1383 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001384 return true;
1385 }
1386 });
1387 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001388 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001389 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1390 break;
1391 }
1392 // otherwise fall through to handle image part
1393 case WebView.HitTestResult.IMAGE_TYPE:
1394 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1395 menu.setHeaderTitle(extra);
1396 }
Michael Kolb3639c4c2011-09-28 15:36:40 -07001397 menu.findItem(R.id.view_image_context_menu_id)
1398 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1399 @Override
1400 public boolean onMenuItemClick(MenuItem item) {
1401 openTab(extra, mTabControl.getCurrentTab(), true, true);
1402 return false;
1403 }
1404 });
Michael Kolb8233fac2010-10-26 16:08:53 -07001405 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001406 setOnMenuItemClickListener(
1407 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001408 menu.findItem(R.id.set_wallpaper_context_menu_id).
1409 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1410 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001411 break;
1412
1413 default:
1414 Log.w(LOGTAG, "We should not get here.");
1415 break;
1416 }
1417 //update the ui
1418 mUi.onContextMenuCreated(menu);
1419 }
1420
1421 /**
1422 * As the menu can be open when loading state changes
1423 * we must manually update the state of the stop/reload menu
1424 * item
1425 */
1426 private void updateInLoadMenuItems(Menu menu) {
1427 if (menu == null) {
1428 return;
1429 }
1430 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1431 MenuItem src = mInLoad ?
1432 menu.findItem(R.id.stop_menu_id):
1433 menu.findItem(R.id.reload_menu_id);
1434 if (src != null) {
1435 dest.setIcon(src.getIcon());
1436 dest.setTitle(src.getTitle());
1437 }
1438 }
1439
John Reckb3417f02011-01-14 11:01:05 -08001440 boolean onPrepareOptionsMenu(Menu menu) {
John Recke1a03a32011-09-14 17:04:16 -07001441 updateInLoadMenuItems(menu);
1442 // hold on to the menu reference here; it is used by the page callbacks
1443 // to update the menu based on loading state
1444 mCachedMenu = menu;
Michael Kolb8233fac2010-10-26 16:08:53 -07001445 // Note: setVisible will decide whether an item is visible; while
1446 // setEnabled() will decide whether an item is enabled, which also means
1447 // whether the matching shortcut key will function.
1448 switch (mMenuState) {
1449 case EMPTY_MENU:
1450 if (mCurrentMenuState != mMenuState) {
1451 menu.setGroupVisible(R.id.MAIN_MENU, false);
1452 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1453 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1454 }
1455 break;
1456 default:
1457 if (mCurrentMenuState != mMenuState) {
1458 menu.setGroupVisible(R.id.MAIN_MENU, true);
1459 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1460 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1461 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001462 updateMenuState(getCurrentTab(), menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001463 break;
1464 }
1465 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001466 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001467 }
1468
Michael Kolb4bf79712011-07-14 14:18:12 -07001469 @Override
1470 public void updateMenuState(Tab tab, Menu menu) {
1471 boolean canGoBack = false;
1472 boolean canGoForward = false;
1473 boolean isHome = false;
John Reck42229bc2011-08-19 13:26:43 -07001474 boolean isDesktopUa = false;
John Recke1a03a32011-09-14 17:04:16 -07001475 boolean isLive = false;
Michael Kolb4bf79712011-07-14 14:18:12 -07001476 if (tab != null) {
1477 canGoBack = tab.canGoBack();
1478 canGoForward = tab.canGoForward();
1479 isHome = mSettings.getHomePage().equals(tab.getUrl());
John Reck42229bc2011-08-19 13:26:43 -07001480 isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
John Recke1a03a32011-09-14 17:04:16 -07001481 isLive = !tab.isSnapshot();
Michael Kolb4bf79712011-07-14 14:18:12 -07001482 }
1483 final MenuItem back = menu.findItem(R.id.back_menu_id);
1484 back.setEnabled(canGoBack);
1485
1486 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1487 home.setEnabled(!isHome);
1488
1489 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1490 forward.setEnabled(canGoForward);
1491
1492 final MenuItem source = menu.findItem(mInLoad ? R.id.stop_menu_id : R.id.reload_menu_id);
1493 final MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolb7ab75ee2011-07-14 16:36:38 -07001494 if (source != null && dest != null) {
1495 dest.setTitle(source.getTitle());
1496 dest.setIcon(source.getIcon());
1497 }
John Recke1a03a32011-09-14 17:04:16 -07001498 menu.setGroupVisible(R.id.NAV_MENU, isLive);
Michael Kolb4bf79712011-07-14 14:18:12 -07001499
1500 // decide whether to show the share link option
1501 PackageManager pm = mActivity.getPackageManager();
1502 Intent send = new Intent(Intent.ACTION_SEND);
1503 send.setType("text/plain");
1504 ResolveInfo ri = pm.resolveActivity(send,
1505 PackageManager.MATCH_DEFAULT_ONLY);
1506 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1507
1508 boolean isNavDump = mSettings.enableNavDump();
1509 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1510 nav.setVisible(isNavDump);
1511 nav.setEnabled(isNavDump);
1512
1513 boolean showDebugSettings = mSettings.isDebugEnabled();
1514 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1515 counter.setVisible(showDebugSettings);
1516 counter.setEnabled(showDebugSettings);
John Reck42229bc2011-08-19 13:26:43 -07001517 final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
1518 uaSwitcher.setChecked(isDesktopUa);
John Recke1a03a32011-09-14 17:04:16 -07001519 menu.setGroupVisible(R.id.LIVE_MENU, isLive);
1520 menu.setGroupVisible(R.id.SNAPSHOT_MENU, !isLive);
Michael Kolb315d5022011-10-13 12:47:11 -07001521 menu.setGroupVisible(R.id.COMBO_MENU, false);
Michael Kolb4bf79712011-07-14 14:18:12 -07001522
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001523 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001524 }
1525
Michael Kolb8233fac2010-10-26 16:08:53 -07001526 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001527 if (null == getCurrentTopWebView()) {
1528 return false;
1529 }
1530 if (mMenuIsDown) {
1531 // The shortcut action consumes the MENU. Even if it is still down,
1532 // it won't trigger the next shortcut action. In the case of the
1533 // shortcut action triggering a new activity, like Bookmarks, we
1534 // won't get onKeyUp for MENU. So it is important to reset it here.
1535 mMenuIsDown = false;
1536 }
Michael Kolb3ca12752011-07-20 13:52:25 -07001537 if (mUi.onOptionsItemSelected(item)) {
1538 // ui callback handled it
1539 return true;
1540 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001541 switch (item.getItemId()) {
1542 // -- Main menu
1543 case R.id.new_tab_menu_id:
1544 openTabToHomePage();
1545 break;
1546
1547 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001548 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001549 break;
1550
1551 case R.id.goto_menu_id:
1552 editUrl();
1553 break;
1554
1555 case R.id.bookmarks_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001556 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
1557 break;
1558
1559 case R.id.history_menu_id:
1560 bookmarksOrHistoryPicker(ComboViews.History);
1561 break;
1562
1563 case R.id.snapshots_menu_id:
1564 bookmarksOrHistoryPicker(ComboViews.Snapshots);
Michael Kolb8233fac2010-10-26 16:08:53 -07001565 break;
1566
Michael Kolb8233fac2010-10-26 16:08:53 -07001567 case R.id.add_bookmark_menu_id:
John Recka60fffa2011-09-06 16:30:29 -07001568 Intent bookmarkIntent = createBookmarkCurrentPageIntent(false);
1569 if (bookmarkIntent != null) {
1570 mActivity.startActivity(bookmarkIntent);
1571 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001572 break;
1573
1574 case R.id.stop_reload_menu_id:
1575 if (mInLoad) {
1576 stopLoading();
1577 } else {
1578 getCurrentTopWebView().reload();
1579 }
1580 break;
1581
1582 case R.id.back_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001583 getCurrentTab().goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07001584 break;
1585
1586 case R.id.forward_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001587 getCurrentTab().goForward();
Michael Kolb8233fac2010-10-26 16:08:53 -07001588 break;
1589
1590 case R.id.close_menu_id:
1591 // Close the subwindow if it exists.
1592 if (mTabControl.getCurrentSubWindow() != null) {
1593 dismissSubWindow(mTabControl.getCurrentTab());
1594 break;
1595 }
1596 closeCurrentTab();
1597 break;
1598
1599 case R.id.homepage_menu_id:
1600 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07001601 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07001602 break;
1603
1604 case R.id.preferences_menu_id:
1605 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1606 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1607 getCurrentTopWebView().getUrl());
1608 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1609 break;
1610
1611 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001612 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001613 break;
1614
John Reck2bc80422011-06-30 15:11:49 -07001615 case R.id.save_snapshot_menu_id:
1616 final Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07001617 if (source == null) break;
John Reckd8c74522011-06-14 08:45:00 -07001618 final ContentResolver cr = mActivity.getContentResolver();
1619 final ContentValues values = source.createSnapshotValues();
John Reck2bc80422011-06-30 15:11:49 -07001620 if (values != null) {
1621 new AsyncTask<Tab, Void, Long>() {
John Reckd8c74522011-06-14 08:45:00 -07001622
John Reck2bc80422011-06-30 15:11:49 -07001623 @Override
1624 protected Long doInBackground(Tab... params) {
1625 Uri result = cr.insert(Snapshots.CONTENT_URI, values);
John Reck93384ff2011-11-10 11:29:18 -08001626 if (result == null) {
1627 return null;
1628 }
John Reck2bc80422011-06-30 15:11:49 -07001629 long id = ContentUris.parseId(result);
1630 return id;
John Reckd8c74522011-06-14 08:45:00 -07001631 }
John Reckf33b1632011-06-04 20:00:23 -07001632
John Reck2bc80422011-06-30 15:11:49 -07001633 @Override
1634 protected void onPostExecute(Long id) {
John Reck93384ff2011-11-10 11:29:18 -08001635 if (id == null) {
1636 Toast.makeText(mActivity, R.string.snapshot_failed,
1637 Toast.LENGTH_SHORT).show();
1638 return;
1639 }
John Reck2bc80422011-06-30 15:11:49 -07001640 Bundle b = new Bundle();
1641 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
1642 mUi.showComboView(ComboViews.Snapshots, b);
1643 };
1644 }.execute(source);
1645 } else {
1646 Toast.makeText(mActivity, R.string.snapshot_failed,
Leon Scrogginsac993842011-02-02 12:54:07 -05001647 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001648 }
Leon Scrogginsac993842011-02-02 12:54:07 -05001649 break;
1650
Michael Kolb8233fac2010-10-26 16:08:53 -07001651 case R.id.page_info_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001652 showPageInfo();
Michael Kolb8233fac2010-10-26 16:08:53 -07001653 break;
1654
John Recke1a03a32011-09-14 17:04:16 -07001655 case R.id.snapshot_go_live:
1656 goLive();
1657 return true;
1658
Michael Kolb8233fac2010-10-26 16:08:53 -07001659 case R.id.share_page_menu_id:
1660 Tab currentTab = mTabControl.getCurrentTab();
1661 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001662 return false;
1663 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001664 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001665 break;
1666
1667 case R.id.dump_nav_menu_id:
1668 getCurrentTopWebView().debugDump();
1669 break;
1670
1671 case R.id.dump_counters_menu_id:
1672 getCurrentTopWebView().dumpV8Counters();
1673 break;
1674
1675 case R.id.zoom_in_menu_id:
1676 getCurrentTopWebView().zoomIn();
1677 break;
1678
1679 case R.id.zoom_out_menu_id:
1680 getCurrentTopWebView().zoomOut();
1681 break;
1682
1683 case R.id.view_downloads_menu_id:
1684 viewDownloads();
1685 break;
1686
John Reck42229bc2011-08-19 13:26:43 -07001687 case R.id.ua_desktop_menu_id:
1688 WebView web = getCurrentWebView();
1689 mSettings.toggleDesktopUseragent(web);
1690 web.loadUrl(web.getOriginalUrl());
1691 break;
1692
Michael Kolb8233fac2010-10-26 16:08:53 -07001693 case R.id.window_one_menu_id:
1694 case R.id.window_two_menu_id:
1695 case R.id.window_three_menu_id:
1696 case R.id.window_four_menu_id:
1697 case R.id.window_five_menu_id:
1698 case R.id.window_six_menu_id:
1699 case R.id.window_seven_menu_id:
1700 case R.id.window_eight_menu_id:
1701 {
1702 int menuid = item.getItemId();
1703 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1704 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1705 Tab desiredTab = mTabControl.getTab(id);
1706 if (desiredTab != null &&
1707 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001708 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001709 }
1710 break;
1711 }
1712 }
1713 }
1714 break;
1715
1716 default:
1717 return false;
1718 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001719 return true;
1720 }
1721
John Recke1a03a32011-09-14 17:04:16 -07001722 private void goLive() {
1723 Tab t = getCurrentTab();
1724 t.loadUrl(t.getUrl(), null);
1725 }
1726
Michael Kolb315d5022011-10-13 12:47:11 -07001727 @Override
1728 public void showPageInfo() {
1729 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
1730 }
1731
Michael Kolb8233fac2010-10-26 16:08:53 -07001732 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001733 // Let the History and Bookmark fragments handle menus they created.
1734 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1735 return false;
1736 }
1737
Michael Kolb8233fac2010-10-26 16:08:53 -07001738 int id = item.getItemId();
1739 boolean result = true;
1740 switch (id) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001741 // -- Browser context menu
1742 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001743 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001744 case R.id.copy_link_context_menu_id:
1745 final WebView webView = getCurrentTopWebView();
1746 if (null == webView) {
1747 result = false;
1748 break;
1749 }
1750 final HashMap<String, WebView> hrefMap =
1751 new HashMap<String, WebView>();
1752 hrefMap.put("webview", webView);
1753 final Message msg = mHandler.obtainMessage(
1754 FOCUS_NODE_HREF, id, 0, hrefMap);
1755 webView.requestFocusNodeHref(msg);
1756 break;
1757
1758 default:
1759 // For other context menus
1760 result = onOptionsItemSelected(item);
1761 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001762 return result;
1763 }
1764
1765 /**
1766 * support programmatically opening the context menu
1767 */
1768 public void openContextMenu(View view) {
1769 mActivity.openContextMenu(view);
1770 }
1771
1772 /**
1773 * programmatically open the options menu
1774 */
1775 public void openOptionsMenu() {
1776 mActivity.openOptionsMenu();
1777 }
1778
1779 public boolean onMenuOpened(int featureId, Menu menu) {
1780 if (mOptionsMenuOpen) {
1781 if (mConfigChanged) {
1782 // We do not need to make any changes to the state of the
1783 // title bar, since the only thing that happened was a
1784 // change in orientation
1785 mConfigChanged = false;
1786 } else {
1787 if (!mExtendedMenuOpen) {
1788 mExtendedMenuOpen = true;
1789 mUi.onExtendedMenuOpened();
1790 } else {
1791 // Switching the menu back to icon view, so show the
1792 // title bar once again.
1793 mExtendedMenuOpen = false;
1794 mUi.onExtendedMenuClosed(mInLoad);
Michael Kolb8233fac2010-10-26 16:08:53 -07001795 }
1796 }
1797 } else {
1798 // The options menu is closed, so open it, and show the title
1799 mOptionsMenuOpen = true;
1800 mConfigChanged = false;
1801 mExtendedMenuOpen = false;
1802 mUi.onOptionsMenuOpened();
1803 }
1804 return true;
1805 }
1806
1807 public void onOptionsMenuClosed(Menu menu) {
1808 mOptionsMenuOpen = false;
1809 mUi.onOptionsMenuClosed(mInLoad);
1810 }
1811
1812 public void onContextMenuClosed(Menu menu) {
1813 mUi.onContextMenuClosed(menu, mInLoad);
1814 }
1815
1816 // Helper method for getting the top window.
1817 @Override
1818 public WebView getCurrentTopWebView() {
1819 return mTabControl.getCurrentTopWebView();
1820 }
1821
1822 @Override
1823 public WebView getCurrentWebView() {
1824 return mTabControl.getCurrentWebView();
1825 }
1826
1827 /*
1828 * This method is called as a result of the user selecting the options
1829 * menu to see the download window. It shows the download window on top of
1830 * the current window.
1831 */
1832 void viewDownloads() {
1833 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1834 mActivity.startActivity(intent);
1835 }
1836
John Reck30b065e2011-07-19 10:58:05 -07001837 int getActionModeHeight() {
1838 TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
1839 new int[] { android.R.attr.actionBarSize });
1840 int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
1841 actionBarSizeTypedArray.recycle();
1842 return size;
1843 }
1844
Michael Kolb8233fac2010-10-26 16:08:53 -07001845 // action mode
1846
1847 void onActionModeStarted(ActionMode mode) {
1848 mUi.onActionModeStarted(mode);
1849 mActionMode = mode;
1850 }
1851
1852 /*
1853 * True if a custom ActionMode (i.e. find or select) is in use.
1854 */
1855 @Override
1856 public boolean isInCustomActionMode() {
1857 return mActionMode != null;
1858 }
1859
1860 /*
1861 * End the current ActionMode.
1862 */
1863 @Override
1864 public void endActionMode() {
1865 if (mActionMode != null) {
1866 mActionMode.finish();
1867 }
1868 }
1869
1870 /*
1871 * Called by find and select when they are finished. Replace title bars
1872 * as necessary.
1873 */
1874 public void onActionModeFinished(ActionMode mode) {
1875 if (!isInCustomActionMode()) return;
1876 mUi.onActionModeFinished(mInLoad);
1877 mActionMode = null;
1878 }
1879
1880 boolean isInLoad() {
1881 return mInLoad;
1882 }
1883
1884 // bookmark handling
1885
1886 /**
1887 * add the current page as a bookmark to the given folder id
1888 * @param folderId use -1 for the default folder
John Reckd3e4d5b2011-07-13 15:48:43 -07001889 * @param editExisting If true, check to see whether the site is already
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001890 * bookmarked, and if it is, edit that bookmark. If false, and
1891 * the site is already bookmarked, do not attempt to edit the
1892 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001893 */
1894 @Override
John Reckd3e4d5b2011-07-13 15:48:43 -07001895 public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
John Recka60fffa2011-09-06 16:30:29 -07001896 WebView w = getCurrentTopWebView();
1897 if (w == null) {
1898 return null;
1899 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001900 Intent i = new Intent(mActivity,
1901 AddBookmarkPage.class);
Michael Kolb8233fac2010-10-26 16:08:53 -07001902 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1903 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1904 String touchIconUrl = w.getTouchIconUrl();
1905 if (touchIconUrl != null) {
1906 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1907 WebSettings settings = w.getSettings();
1908 if (settings != null) {
1909 i.putExtra(AddBookmarkPage.USER_AGENT,
1910 settings.getUserAgentString());
1911 }
1912 }
1913 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1914 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1915 getDesiredThumbnailHeight(mActivity)));
1916 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07001917 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001918 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1919 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001920 // Put the dialog at the upper right of the screen, covering the
1921 // star on the title bar.
1922 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07001923 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07001924 }
1925
1926 // file chooser
1927 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1928 mUploadHandler = new UploadHandler(this);
1929 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1930 }
1931
1932 // thumbnails
1933
1934 /**
1935 * Return the desired width for thumbnail screenshots, which are stored in
1936 * the database, and used on the bookmarks screen.
1937 * @param context Context for finding out the density of the screen.
1938 * @return desired width for thumbnail screenshot.
1939 */
1940 static int getDesiredThumbnailWidth(Context context) {
1941 return context.getResources().getDimensionPixelOffset(
1942 R.dimen.bookmarkThumbnailWidth);
1943 }
1944
1945 /**
1946 * Return the desired height for thumbnail screenshots, which are stored in
1947 * the database, and used on the bookmarks screen.
1948 * @param context Context for finding out the density of the screen.
1949 * @return desired height for thumbnail screenshot.
1950 */
1951 static int getDesiredThumbnailHeight(Context context) {
1952 return context.getResources().getDimensionPixelOffset(
1953 R.dimen.bookmarkThumbnailHeight);
1954 }
1955
John Reck8cc92352011-07-06 17:41:52 -07001956 static Bitmap createScreenshot(WebView view, int width, int height) {
John Reckd7dd9b22011-08-30 09:18:29 -07001957 if (view == null || view.getContentHeight() == 0
1958 || view.getContentWidth() == 0) {
1959 return null;
1960 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001961 // We render to a bitmap 2x the desired size so that we can then
1962 // re-scale it with filtering since canvas.scale doesn't filter
1963 // This helps reduce aliasing at the cost of being slightly blurry
1964 final int filter_scale = 2;
John Reckd7dd9b22011-08-30 09:18:29 -07001965 int scaledWidth = width * filter_scale;
1966 int scaledHeight = height * filter_scale;
1967 if (sThumbnailBitmap == null || sThumbnailBitmap.getWidth() != scaledWidth
1968 || sThumbnailBitmap.getHeight() != scaledHeight) {
1969 if (sThumbnailBitmap != null) {
1970 sThumbnailBitmap.recycle();
1971 sThumbnailBitmap = null;
1972 }
1973 sThumbnailBitmap =
1974 Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.RGB_565);
Michael Kolb8233fac2010-10-26 16:08:53 -07001975 }
John Reckd7dd9b22011-08-30 09:18:29 -07001976 Canvas canvas = new Canvas(sThumbnailBitmap);
1977 int contentWidth = view.getContentWidth();
1978 float overviewScale = scaledWidth / (view.getScale() * contentWidth);
1979 if (view instanceof BrowserWebView) {
1980 int dy = -((BrowserWebView)view).getTitleHeight();
1981 canvas.translate(0, dy * overviewScale);
1982 }
1983
1984 canvas.scale(overviewScale, overviewScale);
1985
1986 if (view instanceof BrowserWebView) {
1987 ((BrowserWebView)view).drawContent(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07001988 } else {
John Reckd7dd9b22011-08-30 09:18:29 -07001989 view.draw(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07001990 }
John Reckd7dd9b22011-08-30 09:18:29 -07001991 Bitmap ret = Bitmap.createScaledBitmap(sThumbnailBitmap,
1992 width, height, true);
Dianne Hackborn43cfe8a2011-08-02 16:59:35 -07001993 canvas.setBitmap(null);
John Reck5c6ac2f2011-01-05 10:18:03 -08001994 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001995 }
1996
John Reck34ef2672011-02-10 11:30:55 -08001997 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001998 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07001999 // FIXME: Would like to make sure there is actually something to
2000 // draw, but the API for that (WebViewCore.pictureReady()) is not
2001 // currently accessible here.
2002
John Reck34ef2672011-02-10 11:30:55 -08002003 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08002004 if (view == null) {
2005 // Tab was destroyed
2006 return;
2007 }
John Reck34ef2672011-02-10 11:30:55 -08002008 final String url = tab.getUrl();
2009 final String originalUrl = view.getOriginalUrl();
2010
2011 if (TextUtils.isEmpty(url)) {
2012 return;
2013 }
2014
2015 // Only update thumbnails for web urls (http(s)://), not for
2016 // about:, javascript:, data:, etc...
2017 // Unless it is a bookmarked site, then always update
2018 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2019 return;
2020 }
2021
Michael Kolb8233fac2010-10-26 16:08:53 -07002022 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2023 getDesiredThumbnailHeight(mActivity));
2024 if (bm == null) {
2025 return;
2026 }
2027
2028 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002029 new AsyncTask<Void, Void, Void>() {
2030 @Override
2031 protected Void doInBackground(Void... unused) {
2032 Cursor cursor = null;
2033 try {
2034 // TODO: Clean this up
2035 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2036 if (cursor != null && cursor.moveToFirst()) {
2037 final ByteArrayOutputStream os =
2038 new ByteArrayOutputStream();
2039 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002040
John Reck34ef2672011-02-10 11:30:55 -08002041 ContentValues values = new ContentValues();
2042 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002043
John Reck34ef2672011-02-10 11:30:55 -08002044 do {
John Reck617fd832011-02-16 14:35:59 -08002045 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002046 cr.update(Images.CONTENT_URI, values, null, null);
2047 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002048 }
John Reck34ef2672011-02-10 11:30:55 -08002049 } catch (IllegalStateException e) {
2050 // Ignore
2051 } finally {
2052 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002053 }
John Reck34ef2672011-02-10 11:30:55 -08002054 return null;
2055 }
2056 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002057 }
2058
2059 private class Copy implements OnMenuItemClickListener {
2060 private CharSequence mText;
2061
2062 public boolean onMenuItemClick(MenuItem item) {
2063 copy(mText);
2064 return true;
2065 }
2066
2067 public Copy(CharSequence toCopy) {
2068 mText = toCopy;
2069 }
2070 }
2071
Leon Scroggins63c02662010-11-18 15:16:27 -05002072 private static class Download implements OnMenuItemClickListener {
2073 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002074 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002075 private boolean mPrivateBrowsing;
George Mount387d45d2011-10-07 15:57:53 -07002076 private static final String FALLBACK_EXTENSION = "dat";
2077 private static final String IMAGE_BASE_FORMAT = "yyyy-MM-dd-HH-mm-ss-";
Michael Kolb8233fac2010-10-26 16:08:53 -07002078
2079 public boolean onMenuItemClick(MenuItem item) {
George Mount387d45d2011-10-07 15:57:53 -07002080 if (DataUri.isDataUri(mText)) {
2081 saveDataUri();
2082 } else {
2083 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
2084 null, null, mPrivateBrowsing);
2085 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002086 return true;
2087 }
2088
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002089 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002090 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002091 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002092 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002093 }
George Mount387d45d2011-10-07 15:57:53 -07002094
2095 /**
2096 * Treats mText as a data URI and writes its contents to a file
2097 * based on the current time.
2098 */
2099 private void saveDataUri() {
2100 FileOutputStream outputStream = null;
2101 try {
2102 DataUri uri = new DataUri(mText);
2103 File target = getTarget(uri);
2104 outputStream = new FileOutputStream(target);
2105 outputStream.write(uri.getData());
2106 final DownloadManager manager =
2107 (DownloadManager) mActivity.getSystemService(Context.DOWNLOAD_SERVICE);
2108 manager.addCompletedDownload(target.getName(),
2109 mActivity.getTitle().toString(), false,
2110 uri.getMimeType(), target.getAbsolutePath(),
2111 (long)uri.getData().length, false);
2112 } catch (IOException e) {
2113 Log.e(LOGTAG, "Could not save data URL");
2114 } finally {
2115 if (outputStream != null) {
2116 try {
2117 outputStream.close();
2118 } catch (IOException e) {
2119 // ignore close errors
2120 }
2121 }
2122 }
2123 }
2124
2125 /**
2126 * Creates a File based on the current time stamp and uses
2127 * the mime type of the DataUri to get the extension.
2128 */
2129 private File getTarget(DataUri uri) throws IOException {
2130 File dir = mActivity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
2131 DateFormat format = new SimpleDateFormat(IMAGE_BASE_FORMAT);
2132 String nameBase = format.format(new Date());
2133 String mimeType = uri.getMimeType();
2134 MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
2135 String extension = mimeTypeMap.getExtensionFromMimeType(mimeType);
2136 if (extension == null) {
2137 Log.w(LOGTAG, "Unknown mime type in data URI" + mimeType);
2138 extension = FALLBACK_EXTENSION;
2139 }
2140 extension = "." + extension; // createTempFile needs the '.'
2141 File targetFile = File.createTempFile(nameBase, extension, dir);
2142 return targetFile;
2143 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002144 }
2145
Cary Clark8974d282010-11-22 10:46:05 -05002146 private static class SelectText implements OnMenuItemClickListener {
2147 private WebView mWebView;
2148
2149 public boolean onMenuItemClick(MenuItem item) {
2150 if (mWebView != null) {
2151 return mWebView.selectText();
2152 }
2153 return false;
2154 }
2155
2156 public SelectText(WebView webView) {
2157 mWebView = webView;
2158 }
2159
2160 }
2161
Michael Kolb8233fac2010-10-26 16:08:53 -07002162 /********************** TODO: UI stuff *****************************/
2163
2164 // these methods have been copied, they still need to be cleaned up
2165
2166 /****************** tabs ***************************************************/
2167
2168 // basic tab interactions:
2169
2170 // it is assumed that tabcontrol already knows about the tab
2171 protected void addTab(Tab tab) {
2172 mUi.addTab(tab);
2173 }
2174
2175 protected void removeTab(Tab tab) {
2176 mUi.removeTab(tab);
2177 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002178 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002179 }
2180
Michael Kolbf2055602011-04-09 17:20:03 -07002181 @Override
2182 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002183 // monkey protection against delayed start
2184 if (tab != null) {
2185 mTabControl.setCurrentTab(tab);
2186 // the tab is guaranteed to have a webview after setCurrentTab
2187 mUi.setActiveTab(tab);
2188 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002189 }
2190
John Reck8bcafc12011-08-29 16:43:02 -07002191 protected void closeEmptyTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002192 Tab current = mTabControl.getCurrentTab();
2193 if (current != null
2194 && current.getWebView().copyBackForwardList().getSize() == 0) {
John Reck8bcafc12011-08-29 16:43:02 -07002195 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002196 }
2197 }
2198
John Reck26b18322011-06-21 13:08:58 -07002199 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002200 // Dismiss the subwindow if applicable.
2201 dismissSubWindow(appTab);
2202 // Since we might kill the WebView, remove it from the
2203 // content view first.
2204 mUi.detachTab(appTab);
2205 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002206 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002207 // TODO: analyze why the remove and add are necessary
2208 mUi.attachTab(appTab);
2209 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002210 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002211 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002212 } else {
2213 // If the tab was the current tab, we have to attach
2214 // it to the view system again.
2215 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002216 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002217 }
2218 }
2219
2220 // Remove the sub window if it exists. Also called by TabControl when the
2221 // user clicks the 'X' to dismiss a sub window.
2222 public void dismissSubWindow(Tab tab) {
2223 removeSubWindow(tab);
2224 // dismiss the subwindow. This will destroy the WebView.
2225 tab.dismissSubWindow();
Michael Kolbe8c97572011-11-21 14:03:56 -08002226 WebView wv = getCurrentTopWebView();
2227 if (wv != null) {
2228 wv.requestFocus();
2229 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002230 }
2231
2232 @Override
2233 public void removeSubWindow(Tab t) {
2234 if (t.getSubWebView() != null) {
2235 mUi.removeSubWindow(t.getSubViewContainer());
2236 }
2237 }
2238
2239 @Override
2240 public void attachSubWindow(Tab tab) {
2241 if (tab.getSubWebView() != null) {
2242 mUi.attachSubWindow(tab.getSubViewContainer());
2243 getCurrentTopWebView().requestFocus();
2244 }
2245 }
2246
Mathew Inwood29721c22011-06-29 17:55:24 +01002247 private Tab showPreloadedTab(final UrlData urlData) {
2248 if (!urlData.isPreloaded()) {
2249 return null;
2250 }
2251 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2252 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2253 if (sbQuery != null) {
Mathew Inwood9ad1eac2011-09-15 11:29:50 +01002254 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002255 // Could not submit query. Fallback to regular tab creation
2256 tabControl.destroy();
2257 return null;
2258 }
2259 }
Michael Kolbff6a7482011-07-26 16:37:15 -07002260 // check tab count and make room for new tab
2261 if (!mTabControl.canCreateNewTab()) {
2262 Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
2263 if (leastUsed != null) {
2264 closeTab(leastUsed);
2265 }
2266 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002267 Tab t = tabControl.getTab();
Mathew Inwoode09305e2011-09-02 12:03:26 +01002268 t.refreshIdAfterPreload();
Mathew Inwood29721c22011-06-29 17:55:24 +01002269 mTabControl.addPreloadedTab(t);
2270 addTab(t);
2271 setActiveTab(t);
2272 return t;
2273 }
2274
Michael Kolb7bcafde2011-05-09 13:55:59 -07002275 // open a non inconito tab with the given url data
2276 // and set as active tab
2277 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002278 Tab tab = showPreloadedTab(urlData);
2279 if (tab == null) {
2280 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002281 if ((tab != null) && !urlData.isEmpty()) {
2282 loadUrlDataIn(tab, urlData);
2283 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002284 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002285 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002286 }
2287
Michael Kolb843510f2010-12-09 10:51:49 -08002288 @Override
2289 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002290 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002291 }
2292
Michael Kolb8233fac2010-10-26 16:08:53 -07002293 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002294 public Tab openIncognitoTab() {
2295 return openTab(INCOGNITO_URI, true, true, false);
2296 }
2297
2298 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002299 public Tab openTab(String url, boolean incognito, boolean setActive,
2300 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002301 return openTab(url, incognito, setActive, useCurrent, null);
2302 }
2303
2304 @Override
2305 public Tab openTab(String url, Tab parent, boolean setActive,
2306 boolean useCurrent) {
2307 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2308 setActive, useCurrent, parent);
2309 }
2310
2311 public Tab openTab(String url, boolean incognito, boolean setActive,
2312 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002313 Tab tab = createNewTab(incognito, setActive, useCurrent);
2314 if (tab != null) {
John Reck5949c662011-05-27 09:52:29 -07002315 if (parent != null && parent != tab) {
2316 parent.addChildTab(tab);
2317 }
Michael Kolb519d2282011-05-09 17:03:19 -07002318 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002319 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002320 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002321 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002322 return tab;
2323 }
2324
2325 // this method will attempt to create a new tab
2326 // incognito: private browsing tab
2327 // setActive: ste tab as current tab
2328 // useCurrent: if no new tab can be created, return current tab
2329 private Tab createNewTab(boolean incognito, boolean setActive,
2330 boolean useCurrent) {
2331 Tab tab = null;
2332 if (mTabControl.canCreateNewTab()) {
2333 tab = mTabControl.createNewTab(incognito);
2334 addTab(tab);
2335 if (setActive) {
2336 setActiveTab(tab);
2337 }
2338 } else {
2339 if (useCurrent) {
2340 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002341 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002342 } else {
2343 mUi.showMaxTabsWarning();
2344 }
2345 }
2346 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002347 }
2348
John Reck2bc80422011-06-30 15:11:49 -07002349 @Override
2350 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2351 SnapshotTab tab = null;
2352 if (mTabControl.canCreateNewTab()) {
2353 tab = mTabControl.createSnapshotTab(snapshotId);
2354 addTab(tab);
2355 if (setActive) {
2356 setActiveTab(tab);
2357 }
2358 } else {
2359 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07002360 }
2361 return tab;
2362 }
2363
Michael Kolb8233fac2010-10-26 16:08:53 -07002364 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002365 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002366 * @return boolean True if we successfully switched to a different tab. If
2367 * the indexth tab is null, or if that tab is the same as
2368 * the current one, return false.
2369 */
2370 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002371 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002372 Tab currentTab = mTabControl.getCurrentTab();
2373 if (tab == null || tab == currentTab) {
2374 return false;
2375 }
2376 setActiveTab(tab);
2377 return true;
2378 }
2379
2380 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002381 public void closeCurrentTab() {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002382 closeCurrentTab(false);
2383 }
2384
2385 protected void closeCurrentTab(boolean andQuit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002386 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07002387 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07002388 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08002389 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002390 return;
2391 }
Michael Kolbc831b632011-05-11 09:30:34 -07002392 final Tab current = mTabControl.getCurrentTab();
2393 final int pos = mTabControl.getCurrentPosition();
2394 Tab newTab = current.getParent();
2395 if (newTab == null) {
2396 newTab = mTabControl.getTab(pos + 1);
2397 if (newTab == null) {
2398 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002399 }
2400 }
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002401 if (andQuit) {
2402 mTabControl.setCurrentTab(newTab);
2403 closeTab(current);
2404 } else if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002405 // Close window
2406 closeTab(current);
2407 }
2408 }
2409
2410 /**
2411 * Close the tab, remove its associated title bar, and adjust mTabControl's
2412 * current tab to a valid value.
2413 */
2414 @Override
2415 public void closeTab(Tab tab) {
John Reck28263772011-10-11 17:13:42 -07002416 if (tab == mTabControl.getCurrentTab()) {
2417 closeCurrentTab();
2418 } else {
2419 removeTab(tab);
2420 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002421 }
2422
Michael Kolb8233fac2010-10-26 16:08:53 -07002423 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07002424 protected void loadUrlFromContext(String url) {
2425 Tab tab = getCurrentTab();
2426 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002427 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07002428 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002429 url = UrlUtils.smartUrlFilter(url);
2430 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07002431 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07002432 }
2433 }
2434 }
2435
2436 /**
2437 * Load the URL into the given WebView and update the title bar
2438 * to reflect the new load. Call this instead of WebView.loadUrl
2439 * directly.
2440 * @param view The WebView used to load url.
2441 * @param url The URL to load.
2442 */
John Reck71e51422011-07-01 16:49:28 -07002443 @Override
2444 public void loadUrl(Tab tab, String url) {
John Reck26b18322011-06-21 13:08:58 -07002445 loadUrl(tab, url, null);
2446 }
2447
2448 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
2449 if (tab != null) {
2450 dismissSubWindow(tab);
2451 tab.loadUrl(url, headers);
Michael Kolba53c9892011-10-05 13:31:40 -07002452 mUi.onProgressChanged(tab);
John Reck26b18322011-06-21 13:08:58 -07002453 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002454 }
2455
2456 /**
2457 * Load UrlData into a Tab and update the title bar to reflect the new
2458 * load. Call this instead of UrlData.loadIn directly.
2459 * @param t The Tab used to load.
2460 * @param data The UrlData being loaded.
2461 */
2462 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07002463 if (data != null) {
2464 if (data.mVoiceIntent != null) {
2465 t.activateVoiceSearchMode(data.mVoiceIntent);
Michael Kolb14612442011-06-24 13:06:29 -07002466 } else if (data.isPreloaded()) {
2467 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07002468 } else {
2469 loadUrl(t, data.mUrl, data.mHeaders);
2470 }
2471 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002472 }
2473
John Reck30c714c2010-12-16 17:30:34 -08002474 @Override
2475 public void onUserCanceledSsl(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08002476 // TODO: Figure out the "right" behavior
John Reckef654f12011-07-12 16:42:08 -07002477 if (tab.canGoBack()) {
2478 tab.goBack();
John Reck30c714c2010-12-16 17:30:34 -08002479 } else {
John Reckef654f12011-07-12 16:42:08 -07002480 tab.loadUrl(mSettings.getHomePage(), null);
John Reck30c714c2010-12-16 17:30:34 -08002481 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002482 }
2483
2484 void goBackOnePageOrQuit() {
2485 Tab current = mTabControl.getCurrentTab();
2486 if (current == null) {
2487 /*
2488 * Instead of finishing the activity, simply push this to the back
2489 * of the stack and let ActivityManager to choose the foreground
2490 * activity. As BrowserActivity is singleTask, it will be always the
2491 * root of the task. So we can use either true or false for
2492 * moveTaskToBack().
2493 */
2494 mActivity.moveTaskToBack(true);
2495 return;
2496 }
John Reckef654f12011-07-12 16:42:08 -07002497 if (current.canGoBack()) {
2498 current.goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07002499 } else {
2500 // Check to see if we are closing a window that was created by
2501 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002502 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002503 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002504 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002505 // Now we close the other tab
2506 closeTab(current);
2507 } else {
Michael Kolbe28b3472011-08-04 16:54:31 -07002508 if ((current.getAppId() != null) || current.closeOnBack()) {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002509 closeCurrentTab(true);
Michael Kolbe28b3472011-08-04 16:54:31 -07002510 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002511 /*
2512 * Instead of finishing the activity, simply push this to the back
2513 * of the stack and let ActivityManager to choose the foreground
2514 * activity. As BrowserActivity is singleTask, it will be always the
2515 * root of the task. So we can use either true or false for
2516 * moveTaskToBack().
2517 */
2518 mActivity.moveTaskToBack(true);
2519 }
2520 }
2521 }
2522
2523 /**
2524 * Feed the previously stored results strings to the BrowserProvider so that
2525 * the SearchDialog will show them instead of the standard searches.
2526 * @param result String to show on the editable line of the SearchDialog.
2527 */
2528 @Override
2529 public void showVoiceSearchResults(String result) {
2530 ContentProviderClient client = mActivity.getContentResolver()
2531 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2532 ContentProvider prov = client.getLocalContentProvider();
2533 BrowserProvider bp = (BrowserProvider) prov;
2534 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2535 client.release();
2536
2537 Bundle bundle = createGoogleSearchSourceBundle(
2538 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2539 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2540 startSearch(result, false, bundle, false);
2541 }
2542
2543 private void startSearch(String initialQuery, boolean selectInitialQuery,
2544 Bundle appSearchData, boolean globalSearch) {
2545 if (appSearchData == null) {
2546 appSearchData = createGoogleSearchSourceBundle(
2547 GOOGLE_SEARCH_SOURCE_TYPE);
2548 }
2549
2550 SearchEngine searchEngine = mSettings.getSearchEngine();
2551 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2552 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2553 }
2554 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2555 globalSearch);
2556 }
2557
2558 private Bundle createGoogleSearchSourceBundle(String source) {
2559 Bundle bundle = new Bundle();
2560 bundle.putString(Search.SOURCE, source);
2561 return bundle;
2562 }
2563
2564 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002565 * helper method for key handler
2566 * returns the current tab if it can't advance
2567 */
Michael Kolbc831b632011-05-11 09:30:34 -07002568 private Tab getNextTab() {
2569 return mTabControl.getTab(Math.min(mTabControl.getTabCount() - 1,
2570 mTabControl.getCurrentPosition() + 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002571 }
2572
2573 /**
2574 * helper method for key handler
2575 * returns the current tab if it can't advance
2576 */
Michael Kolbc831b632011-05-11 09:30:34 -07002577 private Tab getPrevTab() {
2578 return mTabControl.getTab(Math.max(0,
2579 mTabControl.getCurrentPosition() - 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002580 }
2581
2582 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002583 * handle key events in browser
2584 *
2585 * @param keyCode
2586 * @param event
2587 * @return true if handled, false to pass to super
2588 */
2589 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002590 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002591 // Even if MENU is already held down, we need to call to super to open
2592 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002593 if (!noModifiers
2594 && ((KeyEvent.KEYCODE_MENU == keyCode)
2595 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2596 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002597 mMenuIsDown = true;
2598 return false;
2599 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002600
Cary Clark8ff8c662010-12-29 15:03:05 -05002601 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07002602 Tab tab = getCurrentTab();
2603 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05002604
Cary Clark160bbb92011-01-10 11:17:07 -05002605 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2606 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002607
Michael Kolb8233fac2010-10-26 16:08:53 -07002608 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002609 case KeyEvent.KEYCODE_TAB:
2610 if (event.isCtrlPressed()) {
2611 if (event.isShiftPressed()) {
2612 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002613 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002614 } else {
2615 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002616 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002617 }
2618 return true;
2619 }
2620 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002621 case KeyEvent.KEYCODE_SPACE:
2622 // WebView/WebTextView handle the keys in the KeyDown. As
2623 // the Activity's shortcut keys are only handled when WebView
2624 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002625 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002626 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002627 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002628 pageDown();
2629 }
2630 return true;
2631 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002632 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002633 event.startTracking();
2634 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07002635 case KeyEvent.KEYCODE_FORWARD:
2636 if (!noModifiers) break;
2637 tab.goForward();
2638 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002639 case KeyEvent.KEYCODE_DPAD_LEFT:
2640 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002641 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05002642 return true;
2643 }
2644 break;
2645 case KeyEvent.KEYCODE_DPAD_RIGHT:
2646 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002647 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05002648 return true;
2649 }
2650 break;
2651 case KeyEvent.KEYCODE_A:
2652 if (ctrl) {
2653 webView.selectAll();
2654 return true;
2655 }
2656 break;
Michael Kolba4183062011-01-16 10:43:21 -08002657// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002658 case KeyEvent.KEYCODE_C:
2659 if (ctrl) {
2660 webView.copySelection();
2661 return true;
2662 }
2663 break;
Michael Kolba4183062011-01-16 10:43:21 -08002664// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002665// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002666// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002667// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002668// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002669// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002670// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002671// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002672// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002673// case KeyEvent.KEYCODE_M: // unused
2674// case KeyEvent.KEYCODE_N: // in Chrome: new window
2675// case KeyEvent.KEYCODE_O: // in Chrome: open file
2676// case KeyEvent.KEYCODE_P: // in Chrome: print page
2677// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002678// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002679// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2680 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002681 // we can't use the ctrl/shift flags, they check for
2682 // exclusive use of a modifier
2683 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002684 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002685 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002686 } else {
2687 openTabToHomePage();
2688 }
2689 return true;
2690 }
2691 break;
2692// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2693// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb5ae15bd2011-08-16 17:09:27 -07002694// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002695// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2696// case KeyEvent.KEYCODE_Y: // unused
2697// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002698 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002699 // it is a regular key and webview is not null
2700 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002701 }
2702
John Recke6bf4ab2011-02-24 15:48:05 -08002703 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2704 switch(keyCode) {
2705 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07002706 if (mUi.isWebShowing()) {
Michael Kolb315d5022011-10-13 12:47:11 -07002707 bookmarksOrHistoryPicker(ComboViews.History);
John Recke6bf4ab2011-02-24 15:48:05 -08002708 return true;
2709 }
2710 break;
2711 }
2712 return false;
2713 }
2714
Michael Kolb8233fac2010-10-26 16:08:53 -07002715 boolean onKeyUp(int keyCode, KeyEvent event) {
Michael Kolb2814a362011-05-19 15:49:41 -07002716 if (KeyEvent.KEYCODE_MENU == keyCode) {
2717 mMenuIsDown = false;
2718 if (event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002719 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002720 }
2721 }
Cary Clark160bbb92011-01-10 11:17:07 -05002722 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002723 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002724 case KeyEvent.KEYCODE_BACK:
2725 if (event.isTracking() && !event.isCanceled()) {
2726 onBackKey();
2727 return true;
2728 }
2729 break;
2730 }
2731 return false;
2732 }
2733
2734 public boolean isMenuDown() {
2735 return mMenuIsDown;
2736 }
2737
Ben Murdoch8029a772010-11-16 11:58:21 +00002738 public void setupAutoFill(Message message) {
2739 // Open the settings activity at the AutoFill profile fragment so that
2740 // the user can create a new profile. When they return, we will dispatch
2741 // the message so that we can autofill the form using their new profile.
2742 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2743 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2744 AutoFillSettingsFragment.class.getName());
2745 mAutoFillSetupMessage = message;
2746 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2747 }
John Reckb3417f02011-01-14 11:01:05 -08002748
Michael Kolbfbc579a2011-07-07 15:59:33 -07002749 public boolean onSearchRequested() {
2750 mUi.editUrl(false);
2751 return true;
2752 }
2753
John Reck1cf4b792011-07-26 10:22:22 -07002754 @Override
2755 public boolean shouldCaptureThumbnails() {
2756 return mUi.shouldCaptureThumbnails();
2757 }
2758
Michael Kolbc3af0672011-08-09 10:24:41 -07002759 @Override
2760 public void setBlockEvents(boolean block) {
2761 mBlockEvents = block;
2762 }
2763
2764 public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002765 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002766 }
2767
2768 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002769 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002770 }
2771
2772 public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002773 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002774 }
2775
2776 public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002777 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002778 }
2779
2780 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002781 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002782 }
2783
Michael Kolb8233fac2010-10-26 16:08:53 -07002784}