blob: 9ebef4182d98dec32fa799b15f30e23098d0ba2a [file] [log] [blame]
Michael Kolb8233fac2010-10-26 16:08:53 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
Michael Kolb8233fac2010-10-26 16:08:53 -070019import android.app.Activity;
20import android.app.DownloadManager;
21import android.app.SearchManager;
22import android.content.ClipboardManager;
23import android.content.ContentProvider;
24import android.content.ContentProviderClient;
25import android.content.ContentResolver;
John Reckd8c74522011-06-14 08:45:00 -070026import android.content.ContentUris;
Michael Kolb8233fac2010-10-26 16:08:53 -070027import android.content.ContentValues;
28import android.content.Context;
29import android.content.Intent;
30import android.content.pm.PackageManager;
31import android.content.pm.ResolveInfo;
32import android.content.res.Configuration;
John Reck30b065e2011-07-19 10:58:05 -070033import android.content.res.TypedArray;
Leon Scroggins1961ed22010-12-07 15:22:21 -050034import android.database.ContentObserver;
Michael Kolb8233fac2010-10-26 16:08:53 -070035import android.database.Cursor;
36import android.database.sqlite.SQLiteDatabase;
Michael Kolb8233fac2010-10-26 16:08:53 -070037import android.graphics.Bitmap;
38import android.graphics.Canvas;
Michael Kolb8233fac2010-10-26 16:08:53 -070039import android.net.Uri;
40import android.net.http.SslError;
41import android.os.AsyncTask;
42import android.os.Bundle;
George Mount387d45d2011-10-07 15:57:53 -070043import android.os.Environment;
Michael Kolb8233fac2010-10-26 16:08:53 -070044import android.os.Handler;
45import android.os.Message;
46import android.os.PowerManager;
47import android.os.PowerManager.WakeLock;
Ben Murdoch8029a772010-11-16 11:58:21 +000048import android.preference.PreferenceActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -070049import android.provider.Browser;
50import android.provider.BrowserContract;
Michael Kolb8233fac2010-10-26 16:08:53 -070051import android.provider.BrowserContract.Images;
52import android.provider.ContactsContract;
53import android.provider.ContactsContract.Intents.Insert;
Michael Kolbcfa3af52010-12-14 10:36:11 -080054import android.speech.RecognizerIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070055import android.text.TextUtils;
56import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080057import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070058import android.view.ActionMode;
59import android.view.ContextMenu;
60import android.view.ContextMenu.ContextMenuInfo;
61import android.view.Gravity;
62import android.view.KeyEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070063import android.view.Menu;
64import android.view.MenuInflater;
65import android.view.MenuItem;
66import android.view.MenuItem.OnMenuItemClickListener;
Michael Kolbc3af0672011-08-09 10:24:41 -070067import android.view.MotionEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070068import android.view.View;
69import android.webkit.CookieManager;
70import android.webkit.CookieSyncManager;
71import android.webkit.HttpAuthHandler;
George Mount387d45d2011-10-07 15:57:53 -070072import android.webkit.MimeTypeMap;
Michael Kolb8233fac2010-10-26 16:08:53 -070073import android.webkit.SslErrorHandler;
74import android.webkit.ValueCallback;
75import android.webkit.WebChromeClient;
76import android.webkit.WebIconDatabase;
77import android.webkit.WebSettings;
78import android.webkit.WebView;
Leon Scrogginsac993842011-02-02 12:54:07 -050079import android.widget.Toast;
Michael Kolb8233fac2010-10-26 16:08:53 -070080
Michael Kolb4bd767d2011-05-27 11:33:55 -070081import com.android.browser.IntentHandler.UrlData;
John Reck2bc80422011-06-30 15:11:49 -070082import com.android.browser.UI.ComboViews;
Michael Kolb4bd767d2011-05-27 11:33:55 -070083import com.android.browser.provider.BrowserProvider;
John Reck1cf4b792011-07-26 10:22:22 -070084import com.android.browser.provider.BrowserProvider2.Thumbnails;
John Reck8cc92352011-07-06 17:41:52 -070085import com.android.browser.provider.SnapshotProvider.Snapshots;
Michael Kolb4bd767d2011-05-27 11:33:55 -070086import com.android.browser.search.SearchEngine;
87import com.android.common.Search;
88
Michael Kolb8233fac2010-10-26 16:08:53 -070089import java.io.ByteArrayOutputStream;
George Mount387d45d2011-10-07 15:57:53 -070090import java.io.File;
91import java.io.FileOutputStream;
92import java.io.IOException;
Michael Kolb8233fac2010-10-26 16:08:53 -070093import java.net.URLEncoder;
George Mount387d45d2011-10-07 15:57:53 -070094import java.text.DateFormat;
95import java.text.SimpleDateFormat;
John Reck1cf4b792011-07-26 10:22:22 -070096import java.util.ArrayList;
Michael Kolb8233fac2010-10-26 16:08:53 -070097import java.util.Calendar;
George Mount387d45d2011-10-07 15:57:53 -070098import java.util.Date;
Michael Kolb8233fac2010-10-26 16:08:53 -070099import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -0800100import java.util.List;
John Reck26b18322011-06-21 13:08:58 -0700101import java.util.Map;
Michael Kolb8233fac2010-10-26 16:08:53 -0700102
103/**
104 * Controller for browser
105 */
106public class Controller
107 implements WebViewController, UiController {
108
109 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800110 private static final String SEND_APP_ID_EXTRA =
111 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
Michael Kolba4261fd2011-05-05 11:27:37 -0700112 private static final String INCOGNITO_URI = "browser:incognito";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800113
Michael Kolb8233fac2010-10-26 16:08:53 -0700114
115 // public message ids
116 public final static int LOAD_URL = 1001;
117 public final static int STOP_LOAD = 1002;
118
119 // Message Ids
120 private static final int FOCUS_NODE_HREF = 102;
121 private static final int RELEASE_WAKELOCK = 107;
122
123 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
124
125 private static final int OPEN_BOOKMARKS = 201;
126
127 private static final int EMPTY_MENU = -1;
128
Michael Kolb8233fac2010-10-26 16:08:53 -0700129 // activity requestCode
John Reckd3e4d5b2011-07-13 15:48:43 -0700130 final static int COMBO_VIEW = 1;
Michael Kolb8233fac2010-10-26 16:08:53 -0700131 final static int PREFERENCES_PAGE = 3;
132 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000133 final static int AUTOFILL_SETUP = 5;
134
Michael Kolb8233fac2010-10-26 16:08:53 -0700135 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
136
137 // As the ids are dynamically created, we can't guarantee that they will
138 // be in sequence, so this static array maps ids to a window number.
139 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
140 { R.id.window_one_menu_id, R.id.window_two_menu_id,
141 R.id.window_three_menu_id, R.id.window_four_menu_id,
142 R.id.window_five_menu_id, R.id.window_six_menu_id,
143 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
144
145 // "source" parameter for Google search through search key
146 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
147 // "source" parameter for Google search through simplily type
148 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
149
George Mount387d45d2011-10-07 15:57:53 -0700150 // "no-crash-recovery" parameter in intent to suppress crash recovery
Guang Zhu9e78f512011-05-04 11:45:11 -0700151 final static String NO_CRASH_RECOVERY = "no-crash-recovery";
152
John Reckd7dd9b22011-08-30 09:18:29 -0700153 // A bitmap that is re-used in createScreenshot as scratch space
154 private static Bitmap sThumbnailBitmap;
155
Michael Kolb8233fac2010-10-26 16:08:53 -0700156 private Activity mActivity;
157 private UI mUi;
158 private TabControl mTabControl;
159 private BrowserSettings mSettings;
160 private WebViewFactory mFactory;
161
162 private WakeLock mWakeLock;
163
164 private UrlHandler mUrlHandler;
165 private UploadHandler mUploadHandler;
166 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700167 private PageDialogsHandler mPageDialogsHandler;
168 private NetworkStateHandler mNetworkHandler;
169
Ben Murdoch8029a772010-11-16 11:58:21 +0000170 private Message mAutoFillSetupMessage;
171
Michael Kolb8233fac2010-10-26 16:08:53 -0700172 private boolean mShouldShowErrorConsole;
173
174 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
175
176 // FIXME, temp address onPrepareMenu performance problem.
177 // When we move everything out of view, we should rewrite this.
178 private int mCurrentMenuState = 0;
179 private int mMenuState = R.id.MAIN_MENU;
180 private int mOldMenuState = EMPTY_MENU;
181 private Menu mCachedMenu;
182
Michael Kolb8233fac2010-10-26 16:08:53 -0700183 private boolean mMenuIsDown;
184
185 // For select and find, we keep track of the ActionMode so that
186 // finish() can be called as desired.
187 private ActionMode mActionMode;
188
189 /**
190 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
191 * of whether the configuration has changed. The first onMenuOpened call
192 * after a configuration change is simply a reopening of the same menu
193 * (i.e. mIconView did not change).
194 */
195 private boolean mConfigChanged;
196
197 /**
198 * Keeps track of whether the options menu is open. This is important in
199 * determining whether to show or hide the title bar overlay
200 */
201 private boolean mOptionsMenuOpen;
202
203 /**
204 * Whether or not the options menu is in its bigger, popup menu form. When
205 * true, we want the title bar overlay to be gone. When false, we do not.
206 * Only meaningful if mOptionsMenuOpen is true.
207 */
208 private boolean mExtendedMenuOpen;
209
Michael Kolb8233fac2010-10-26 16:08:53 -0700210 private boolean mActivityPaused = true;
211 private boolean mLoadStopped;
212
213 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500214 // Checks to see when the bookmarks database has changed, and updates the
215 // Tabs' notion of whether they represent bookmarked sites.
216 private ContentObserver mBookmarksObserver;
John Reck847b5322011-04-14 17:02:18 -0700217 private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700218
Michael Kolbc3af0672011-08-09 10:24:41 -0700219 private boolean mBlockEvents;
220
George Mount3636d0a2011-11-21 09:08:21 -0800221 public Controller(Activity browser) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700222 mActivity = browser;
223 mSettings = BrowserSettings.getInstance();
224 mTabControl = new TabControl(this);
225 mSettings.setController(this);
John Reck378a4102011-06-09 16:23:01 -0700226 mCrashRecoveryHandler = CrashRecoveryHandler.initialize(this);
George Mount3636d0a2011-11-21 09:08:21 -0800227 mCrashRecoveryHandler.preloadCrashState();
Michael Kolb14612442011-06-24 13:06:29 -0700228 mFactory = new BrowserWebViewFactory(browser);
Michael Kolb8233fac2010-10-26 16:08:53 -0700229
230 mUrlHandler = new UrlHandler(this);
231 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700232 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
233
Michael Kolb8233fac2010-10-26 16:08:53 -0700234 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500235 mBookmarksObserver = new ContentObserver(mHandler) {
236 @Override
237 public void onChange(boolean selfChange) {
238 int size = mTabControl.getTabCount();
239 for (int i = 0; i < size; i++) {
240 mTabControl.getTab(i).updateBookmarkedStatus();
241 }
242 }
243
244 };
245 browser.getContentResolver().registerContentObserver(
246 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700247
248 mNetworkHandler = new NetworkStateHandler(mActivity, this);
249 // Start watching the default geolocation permissions
250 mSystemAllowGeolocationOrigins =
251 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
252 mSystemAllowGeolocationOrigins.start();
253
John Reckaf262e72011-07-25 13:55:44 -0700254 openIconDatabase();
Michael Kolb8233fac2010-10-26 16:08:53 -0700255 }
256
George Mount3636d0a2011-11-21 09:08:21 -0800257 void start(final Intent intent) {
258 // mCrashRecoverHandler has any previously saved state.
259 mCrashRecoveryHandler.startRecovery(intent);
John Reck847b5322011-04-14 17:02:18 -0700260 }
261
George Mount3636d0a2011-11-21 09:08:21 -0800262 void doStart(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700263 // Unless the last browser usage was within 24 hours, destroy any
264 // remaining incognito tabs.
265
266 Calendar lastActiveDate = icicle != null ?
267 (Calendar) icicle.getSerializable("lastActiveDate") : null;
268 Calendar today = Calendar.getInstance();
269 Calendar yesterday = Calendar.getInstance();
270 yesterday.add(Calendar.DATE, -1);
271
Patrick Scott7d50a932011-02-04 09:27:26 -0500272 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700273 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800274 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700275
Patrick Scott7d50a932011-02-04 09:27:26 -0500276 // Find out if we will restore any state and remember the tab.
Michael Kolbc831b632011-05-11 09:30:34 -0700277 final long currentTabId =
Patrick Scott7d50a932011-02-04 09:27:26 -0500278 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000279
Michael Kolbc831b632011-05-11 09:30:34 -0700280 if (currentTabId == -1) {
Patrick Scott7d50a932011-02-04 09:27:26 -0500281 // Not able to restore so we go ahead and clear session cookies. We
282 // must do this before trying to login the user as we don't want to
283 // clear any session cookies set during login.
284 CookieManager.getInstance().removeSessionCookie();
285 }
286
Patrick Scottd43e75a2011-03-14 14:47:23 -0400287 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500288 new Runnable() {
289 @Override public void run() {
George Mount3636d0a2011-11-21 09:08:21 -0800290 onPreloginFinished(icicle, intent, currentTabId,
291 restoreIncognitoTabs);
Patrick Scott7d50a932011-02-04 09:27:26 -0500292 }
293 });
294 }
295
Michael Kolbc831b632011-05-11 09:30:34 -0700296 private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId,
George Mount3636d0a2011-11-21 09:08:21 -0800297 boolean restoreIncognitoTabs) {
Michael Kolbc831b632011-05-11 09:30:34 -0700298 if (currentTabId == -1) {
John Reck1cf4b792011-07-26 10:22:22 -0700299 BackgroundHandler.execute(new PruneThumbnails(mActivity, null));
George Mount3636d0a2011-11-21 09:08:21 -0800300 if (intent == null) {
301 // This won't happen under common scenarios. The icicle is
302 // not null, but there aren't any tabs to restore.
303 openTabToHomePage();
Michael Kolb7bcafde2011-05-09 13:55:59 -0700304 } else {
George Mount3636d0a2011-11-21 09:08:21 -0800305 final Bundle extra = intent.getExtras();
306 // Create an initial tab.
307 // If the intent is ACTION_VIEW and data is not null, the Browser is
308 // invoked to view the content by another application. In this case,
309 // the tab will be close when exit.
310 UrlData urlData = IntentHandler.getUrlDataFromIntent(intent);
311 Tab t = null;
312 if (urlData.isEmpty()) {
313 t = openTabToHomePage();
314 } else {
315 t = openTab(urlData);
316 }
317 if (t != null) {
318 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
319 }
320 WebView webView = t.getWebView();
321 if (extra != null) {
322 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
323 if (scale > 0 && scale <= 1000) {
324 webView.setInitialScale(scale);
325 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700326 }
327 }
John Reckd8c74522011-06-14 08:45:00 -0700328 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700329 } else {
Michael Kolbc831b632011-05-11 09:30:34 -0700330 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
Patrick Scott7d50a932011-02-04 09:27:26 -0500331 mUi.needsRestoreAllTabs());
John Reck1cf4b792011-07-26 10:22:22 -0700332 List<Tab> tabs = mTabControl.getTabs();
333 ArrayList<Long> restoredTabs = new ArrayList<Long>(tabs.size());
334 for (Tab t : tabs) {
335 restoredTabs.add(t.getId());
336 }
337 BackgroundHandler.execute(new PruneThumbnails(mActivity, restoredTabs));
John Reck52be4782011-08-26 15:37:29 -0700338 if (tabs.size() == 0) {
339 openTabToHomePage();
340 }
John Reck1cf4b792011-07-26 10:22:22 -0700341 mUi.updateTabs(tabs);
Michael Kolb8233fac2010-10-26 16:08:53 -0700342 // TabControl.restoreState() will create a new tab even if
343 // restoring the state fails.
344 setActiveTab(mTabControl.getCurrentTab());
George Mount3636d0a2011-11-21 09:08:21 -0800345 // Intent is non-null when framework thinks the browser should be
346 // launching with a new intent (icicle is null).
347 if (intent != null) {
John Reck9dd4a412011-10-05 14:55:30 -0700348 mIntentHandler.onNewIntent(intent);
349 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700350 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700351 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700352 String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb8233fac2010-10-26 16:08:53 -0700353 if (jsFlags.trim().length() != 0) {
354 getCurrentWebView().setJsFlags(jsFlags);
355 }
George Mount3636d0a2011-11-21 09:08:21 -0800356 if (intent != null
357 && BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
Michael Kolb315d5022011-10-13 12:47:11 -0700358 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
John Reck439c9a52010-12-14 10:04:39 -0800359 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700360 }
361
John Reck1cf4b792011-07-26 10:22:22 -0700362 private static class PruneThumbnails implements Runnable {
363 private Context mContext;
364 private List<Long> mIds;
365
366 PruneThumbnails(Context context, List<Long> preserveIds) {
367 mContext = context.getApplicationContext();
368 mIds = preserveIds;
369 }
370
371 @Override
372 public void run() {
373 ContentResolver cr = mContext.getContentResolver();
374 if (mIds == null || mIds.size() == 0) {
375 cr.delete(Thumbnails.CONTENT_URI, null, null);
376 } else {
377 int length = mIds.size();
378 StringBuilder where = new StringBuilder();
379 where.append(Thumbnails._ID);
380 where.append(" not in (");
381 for (int i = 0; i < length; i++) {
382 where.append(mIds.get(i));
383 if (i < (length - 1)) {
384 where.append(",");
385 }
386 }
387 where.append(")");
388 cr.delete(Thumbnails.CONTENT_URI, where.toString(), null);
389 }
390 }
391
392 }
393
Michael Kolb1514bb72010-11-22 09:11:48 -0800394 @Override
395 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700396 return mFactory;
397 }
398
399 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800400 public void onSetWebView(Tab tab, WebView view) {
401 mUi.onSetWebView(tab, view);
402 }
403
404 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800405 public void createSubWindow(Tab tab) {
406 endActionMode();
407 WebView mainView = tab.getWebView();
408 WebView subView = mFactory.createWebView((mainView == null)
409 ? false
410 : mainView.isPrivateBrowsingEnabled());
411 mUi.createSubWindow(tab, subView);
412 }
413
414 @Override
Michael Kolb14612442011-06-24 13:06:29 -0700415 public Context getContext() {
416 return mActivity;
417 }
418
419 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700420 public Activity getActivity() {
421 return mActivity;
422 }
423
424 void setUi(UI ui) {
425 mUi = ui;
426 }
427
428 BrowserSettings getSettings() {
429 return mSettings;
430 }
431
432 IntentHandler getIntentHandler() {
433 return mIntentHandler;
434 }
435
436 @Override
437 public UI getUi() {
438 return mUi;
439 }
440
441 int getMaxTabs() {
442 return mActivity.getResources().getInteger(R.integer.max_tabs);
443 }
444
445 @Override
446 public TabControl getTabControl() {
447 return mTabControl;
448 }
449
Michael Kolb1bf23132010-11-19 12:55:12 -0800450 @Override
451 public List<Tab> getTabs() {
452 return mTabControl.getTabs();
453 }
454
John Reckaf262e72011-07-25 13:55:44 -0700455 // Open the icon database.
456 private void openIconDatabase() {
457 // We have to call getInstance on the UI thread
458 final WebIconDatabase instance = WebIconDatabase.getInstance();
459 BackgroundHandler.execute(new Runnable() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000460
John Reckaf262e72011-07-25 13:55:44 -0700461 @Override
462 public void run() {
463 instance.open(mActivity.getDir("icons", 0).getPath());
Michael Kolb8233fac2010-10-26 16:08:53 -0700464 }
John Reckaf262e72011-07-25 13:55:44 -0700465 });
Michael Kolb8233fac2010-10-26 16:08:53 -0700466 }
467
468 private void startHandler() {
469 mHandler = new Handler() {
470
471 @Override
472 public void handleMessage(Message msg) {
473 switch (msg.what) {
474 case OPEN_BOOKMARKS:
Michael Kolb315d5022011-10-13 12:47:11 -0700475 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
Michael Kolb8233fac2010-10-26 16:08:53 -0700476 break;
477 case FOCUS_NODE_HREF:
478 {
479 String url = (String) msg.getData().get("url");
480 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500481 String src = (String) msg.getData().get("src");
482 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700483 if (TextUtils.isEmpty(url)) {
484 break;
485 }
486 HashMap focusNodeMap = (HashMap) msg.obj;
487 WebView view = (WebView) focusNodeMap.get("webview");
488 // Only apply the action if the top window did not change.
489 if (getCurrentTopWebView() != view) {
490 break;
491 }
492 switch (msg.arg1) {
493 case R.id.open_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700494 loadUrlFromContext(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700495 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500496 case R.id.view_image_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700497 loadUrlFromContext(src);
Cary Clark043c2d62010-12-15 11:19:39 -0500498 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500499 case R.id.open_newtab_context_menu_id:
500 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -0700501 openTab(url, parent,
502 !mSettings.openInBackground(), true);
Leon Scroggins026f2542010-11-22 13:26:12 -0500503 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700504 case R.id.copy_link_context_menu_id:
505 copy(url);
506 break;
507 case R.id.save_link_context_menu_id:
508 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500509 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000510 mActivity, url, null, null, null,
511 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700512 break;
513 }
514 break;
515 }
516
517 case LOAD_URL:
John Reck26b18322011-06-21 13:08:58 -0700518 loadUrlFromContext((String) msg.obj);
Michael Kolb8233fac2010-10-26 16:08:53 -0700519 break;
520
521 case STOP_LOAD:
522 stopLoading();
523 break;
524
525 case RELEASE_WAKELOCK:
John Reckf57c0292011-07-21 18:15:39 -0700526 if (mWakeLock != null && mWakeLock.isHeld()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700527 mWakeLock.release();
528 // if we reach here, Browser should be still in the
529 // background loading after WAKELOCK_TIMEOUT (5-min).
530 // To avoid burning the battery, stop loading.
531 mTabControl.stopAllLoading();
532 }
533 break;
534
535 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800536 Tab tab = (Tab) msg.obj;
537 if (tab != null) {
538 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700539 }
540 break;
541 }
542 }
543 };
544
545 }
546
John Reckef654f12011-07-12 16:42:08 -0700547 @Override
Martijn Coenenb2f93552011-06-14 10:48:35 +0200548 public Tab getCurrentTab() {
549 return mTabControl.getCurrentTab();
550 }
551
Michael Kolbba99c5d2010-11-29 14:57:41 -0800552 @Override
553 public void shareCurrentPage() {
554 shareCurrentPage(mTabControl.getCurrentTab());
555 }
556
557 private void shareCurrentPage(Tab tab) {
558 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800559 sharePage(mActivity, tab.getTitle(),
560 tab.getUrl(), tab.getFavicon(),
561 createScreenshot(tab.getWebView(),
562 getDesiredThumbnailWidth(mActivity),
563 getDesiredThumbnailHeight(mActivity)));
564 }
565 }
566
Michael Kolb8233fac2010-10-26 16:08:53 -0700567 /**
568 * Share a page, providing the title, url, favicon, and a screenshot. Uses
569 * an {@link Intent} to launch the Activity chooser.
570 * @param c Context used to launch a new Activity.
571 * @param title Title of the page. Stored in the Intent with
572 * {@link Intent#EXTRA_SUBJECT}
573 * @param url URL of the page. Stored in the Intent with
574 * {@link Intent#EXTRA_TEXT}
575 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
576 * with {@link Browser#EXTRA_SHARE_FAVICON}
577 * @param screenshot Bitmap of a screenshot of the page. Stored in the
578 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
579 */
580 static final void sharePage(Context c, String title, String url,
581 Bitmap favicon, Bitmap screenshot) {
582 Intent send = new Intent(Intent.ACTION_SEND);
583 send.setType("text/plain");
584 send.putExtra(Intent.EXTRA_TEXT, url);
585 send.putExtra(Intent.EXTRA_SUBJECT, title);
586 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
587 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
588 try {
589 c.startActivity(Intent.createChooser(send, c.getString(
590 R.string.choosertitle_sharevia)));
591 } catch(android.content.ActivityNotFoundException ex) {
592 // if no app handles it, do nothing
593 }
594 }
595
596 private void copy(CharSequence text) {
597 ClipboardManager cm = (ClipboardManager) mActivity
598 .getSystemService(Context.CLIPBOARD_SERVICE);
599 cm.setText(text);
600 }
601
602 // lifecycle
603
604 protected void onConfgurationChanged(Configuration config) {
605 mConfigChanged = true;
606 if (mPageDialogsHandler != null) {
607 mPageDialogsHandler.onConfigurationChanged(config);
608 }
609 mUi.onConfigurationChanged(config);
610 }
611
612 @Override
613 public void handleNewIntent(Intent intent) {
Michael Kolb59e232c2011-08-18 17:19:53 -0700614 if (!mUi.isWebShowing()) {
615 mUi.showWeb(false);
616 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700617 mIntentHandler.onNewIntent(intent);
618 }
619
620 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800621 if (mUi.isCustomViewShowing()) {
622 hideCustomView();
623 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700624 if (mActivityPaused) {
625 Log.e(LOGTAG, "BrowserActivity is already paused.");
626 return;
627 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700628 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800629 Tab tab = mTabControl.getCurrentTab();
630 if (tab != null) {
631 tab.pause();
632 if (!pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700633 if (mWakeLock == null) {
634 PowerManager pm = (PowerManager) mActivity
635 .getSystemService(Context.POWER_SERVICE);
636 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
637 }
Michael Kolb70976932010-11-30 11:34:01 -0800638 mWakeLock.acquire();
639 mHandler.sendMessageDelayed(mHandler
640 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
641 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700642 }
643 mUi.onPause();
644 mNetworkHandler.onPause();
645
646 WebView.disablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100647 NfcHandler.unregister(mActivity);
John Reckd7dd9b22011-08-30 09:18:29 -0700648 if (sThumbnailBitmap != null) {
649 sThumbnailBitmap.recycle();
650 sThumbnailBitmap = null;
651 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700652 }
653
John Reck1cf4b792011-07-26 10:22:22 -0700654 void onSaveInstanceState(Bundle outState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700655 // Save all the tabs
George Mount3636d0a2011-11-21 09:08:21 -0800656 Bundle saveState = createSaveState();
657
658 // crash recovery manages all save & restore state
659 mCrashRecoveryHandler.writeState(saveState);
660 mSettings.setLastRunPaused(true);
661 }
662
663 /**
664 * Save the current state to outState. Does not write the state to
665 * disk.
666 * @return Bundle containing the current state of all tabs.
667 */
668 /* package */ Bundle createSaveState() {
669 Bundle saveState = new Bundle();
670 mTabControl.saveState(saveState);
671 if (!saveState.isEmpty()) {
John Reck24f18262011-06-17 14:47:20 -0700672 // Save time so that we know how old incognito tabs (if any) are.
George Mount3636d0a2011-11-21 09:08:21 -0800673 saveState.putSerializable("lastActiveDate", Calendar.getInstance());
John Reck24f18262011-06-17 14:47:20 -0700674 }
George Mount3636d0a2011-11-21 09:08:21 -0800675 return saveState;
Michael Kolb8233fac2010-10-26 16:08:53 -0700676 }
677
678 void onResume() {
679 if (!mActivityPaused) {
680 Log.e(LOGTAG, "BrowserActivity is already resumed.");
681 return;
682 }
George Mount3636d0a2011-11-21 09:08:21 -0800683 mSettings.setLastRunPaused(false);
Michael Kolb8233fac2010-10-26 16:08:53 -0700684 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800685 Tab current = mTabControl.getCurrentTab();
686 if (current != null) {
687 current.resume();
688 resumeWebViewTimers(current);
689 }
John Reckf57c0292011-07-21 18:15:39 -0700690 releaseWakeLock();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200691
Michael Kolb8233fac2010-10-26 16:08:53 -0700692 mUi.onResume();
693 mNetworkHandler.onResume();
694 WebView.enablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100695 NfcHandler.register(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700696 }
697
John Reckf57c0292011-07-21 18:15:39 -0700698 private void releaseWakeLock() {
699 if (mWakeLock != null && mWakeLock.isHeld()) {
700 mHandler.removeMessages(RELEASE_WAKELOCK);
701 mWakeLock.release();
702 }
703 }
704
Michael Kolb70976932010-11-30 11:34:01 -0800705 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800706 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800707 * @param tab guaranteed non-null
708 */
709 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700710 boolean inLoad = tab.inPageLoad();
711 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
712 CookieSyncManager.getInstance().startSync();
713 WebView w = tab.getWebView();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100714 WebViewTimersControl.getInstance().onBrowserActivityResume(w);
Michael Kolb8233fac2010-10-26 16:08:53 -0700715 }
716 }
717
Michael Kolb70976932010-11-30 11:34:01 -0800718 /**
719 * Pause all WebView timers using the WebView of the given tab
720 * @param tab
721 * @return true if the timers are paused or tab is null
722 */
723 private boolean pauseWebViewTimers(Tab tab) {
724 if (tab == null) {
725 return true;
726 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700727 CookieSyncManager.getInstance().stopSync();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100728 WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView());
Michael Kolb8233fac2010-10-26 16:08:53 -0700729 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700730 }
Michael Kolb70976932010-11-30 11:34:01 -0800731 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700732 }
733
734 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800735 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700736 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
737 mUploadHandler = null;
738 }
739 if (mTabControl == null) return;
740 mUi.onDestroy();
741 // Remove the current tab and sub window
742 Tab t = mTabControl.getCurrentTab();
743 if (t != null) {
744 dismissSubWindow(t);
745 removeTab(t);
746 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500747 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700748 // Destroy all the tabs
749 mTabControl.destroy();
750 WebIconDatabase.getInstance().close();
751 // Stop watching the default geolocation permissions
752 mSystemAllowGeolocationOrigins.stop();
753 mSystemAllowGeolocationOrigins = null;
754 }
755
756 protected boolean isActivityPaused() {
757 return mActivityPaused;
758 }
759
760 protected void onLowMemory() {
761 mTabControl.freeMemory();
762 }
763
764 @Override
765 public boolean shouldShowErrorConsole() {
766 return mShouldShowErrorConsole;
767 }
768
769 protected void setShouldShowErrorConsole(boolean show) {
770 if (show == mShouldShowErrorConsole) {
771 // Nothing to do.
772 return;
773 }
774 mShouldShowErrorConsole = show;
775 Tab t = mTabControl.getCurrentTab();
776 if (t == null) {
777 // There is no current tab so we cannot toggle the error console
778 return;
779 }
780 mUi.setShouldShowErrorConsole(t, show);
781 }
782
783 @Override
784 public void stopLoading() {
785 mLoadStopped = true;
786 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700787 WebView w = getCurrentTopWebView();
788 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700789 mUi.onPageStopped(tab);
790 }
791
792 boolean didUserStopLoading() {
793 return mLoadStopped;
794 }
795
796 // WebViewController
797
798 @Override
John Reck324d4402011-01-11 16:56:42 -0800799 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700800
801 // We've started to load a new page. If there was a pending message
802 // to save a screenshot then we will now take the new page and save
803 // an incorrect screenshot. Therefore, remove any pending thumbnail
804 // messages from the queue.
805 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800806 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700807
808 // reset sync timer to avoid sync starts during loading a page
809 CookieSyncManager.getInstance().resetSync();
810
811 if (!mNetworkHandler.isNetworkUp()) {
812 view.setNetworkAvailable(false);
813 }
814
815 // when BrowserActivity just starts, onPageStarted may be called before
816 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
817 // to start the timer. As we won't switch tabs while an activity is in
818 // pause state, we can ensure calling resume and pause in pair.
819 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800820 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700821 }
822 mLoadStopped = false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700823 endActionMode();
824
John Reck30c714c2010-12-16 17:30:34 -0800825 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700826
John Reck324d4402011-01-11 16:56:42 -0800827 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700828 // update the bookmark database for favicon
829 maybeUpdateFavicon(tab, null, url, favicon);
830
831 Performance.tracePageStart(url);
832
833 // Performance probe
834 if (false) {
835 Performance.onPageStarted();
836 }
837
838 }
839
840 @Override
John Reck324d4402011-01-11 16:56:42 -0800841 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800842 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800843 if (!tab.isPrivateBrowsingEnabled()
John Reckd8c74522011-06-14 08:45:00 -0700844 && !TextUtils.isEmpty(tab.getUrl())
Michael Kolbdcd90e32011-12-16 13:45:22 -0800845 && !tab.isSnapshot()
846 && !tab.inPageLoad()) {
John Recka1696282011-07-08 14:10:37 -0700847 // Only update the bookmark screenshot if the user did not
848 // cancel the load early and there is not already
849 // a pending update for the tab.
Michael Kolb8233fac2010-10-26 16:08:53 -0700850 if (tab.inForeground() && !didUserStopLoading()
851 || !tab.inForeground()) {
John Recka1696282011-07-08 14:10:37 -0700852 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
853 mHandler.sendMessageDelayed(mHandler.obtainMessage(
854 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
855 500);
856 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700857 }
858 }
859 // pause the WebView timer and release the wake lock if it is finished
860 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800861 if (mActivityPaused && pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700862 releaseWakeLock();
Michael Kolb8233fac2010-10-26 16:08:53 -0700863 }
Martijn Coenenb2f93552011-06-14 10:48:35 +0200864
Michael Kolb8233fac2010-10-26 16:08:53 -0700865 // Performance probe
866 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800867 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700868 }
869
870 Performance.tracePageFinished();
871 }
872
873 @Override
John Reck30c714c2010-12-16 17:30:34 -0800874 public void onProgressChanged(Tab tab) {
John Reck6c2e2f32011-08-22 13:41:23 -0700875 mCrashRecoveryHandler.backupState();
John Reck30c714c2010-12-16 17:30:34 -0800876 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700877
878 if (newProgress == 100) {
879 CookieSyncManager.getInstance().sync();
880 // onProgressChanged() may continue to be called after the main
881 // frame has finished loading, as any remaining sub frames continue
882 // to load. We'll only get called once though with newProgress as
883 // 100 when everything is loaded. (onPageFinished is called once
884 // when the main frame completes loading regardless of the state of
885 // any sub frames so calls to onProgressChanges may continue after
886 // onPageFinished has executed)
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800887 if (tab.inPageLoad()) {
888 updateInLoadMenuItems(mCachedMenu, tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700889 }
890 } else {
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800891 if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700892 // onPageFinished may have already been called but a subframe is
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800893 // still loading
894 // updating the progress and
Michael Kolb8233fac2010-10-26 16:08:53 -0700895 // update the menu items.
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800896 updateInLoadMenuItems(mCachedMenu, tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700897 }
898 }
John Reck30c714c2010-12-16 17:30:34 -0800899 mUi.onProgressChanged(tab);
900 }
901
902 @Override
Steve Block2466eff2011-10-03 15:33:09 +0100903 public void onUpdatedSecurityState(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800904 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700905 }
906
907 @Override
908 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800909 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800910 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800911 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700912 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
913 return;
914 }
915 // Update the title in the history database if not in private browsing mode
916 if (!tab.isPrivateBrowsingEnabled()) {
John Reckf57c0292011-07-21 18:15:39 -0700917 DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700918 }
919 }
920
921 @Override
922 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800923 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700924 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
925 }
926
927 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800928 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
929 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700930 }
931
932 @Override
933 public boolean shouldOverrideKeyEvent(KeyEvent event) {
934 if (mMenuIsDown) {
935 // only check shortcut key when MENU is held
936 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
937 event);
938 } else {
939 return false;
940 }
941 }
942
943 @Override
944 public void onUnhandledKeyEvent(KeyEvent event) {
945 if (!isActivityPaused()) {
946 if (event.getAction() == KeyEvent.ACTION_DOWN) {
947 mActivity.onKeyDown(event.getKeyCode(), event);
948 } else {
949 mActivity.onKeyUp(event.getKeyCode(), event);
950 }
951 }
952 }
953
954 @Override
John Reck324d4402011-01-11 16:56:42 -0800955 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700956 // Don't save anything in private browsing mode
957 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800958 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700959
John Reck324d4402011-01-11 16:56:42 -0800960 if (TextUtils.isEmpty(url)
961 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700962 return;
963 }
John Reckf57c0292011-07-21 18:15:39 -0700964 DataController.getInstance(mActivity).updateVisitedHistory(url);
John Reck6c2e2f32011-08-22 13:41:23 -0700965 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -0700966 }
967
968 @Override
969 public void getVisitedHistory(final ValueCallback<String[]> callback) {
970 AsyncTask<Void, Void, String[]> task =
971 new AsyncTask<Void, Void, String[]>() {
972 @Override
973 public String[] doInBackground(Void... unused) {
974 return Browser.getVisitedHistory(mActivity.getContentResolver());
975 }
976 @Override
977 public void onPostExecute(String[] result) {
978 callback.onReceiveValue(result);
979 }
980 };
981 task.execute();
982 }
983
984 @Override
985 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
986 final HttpAuthHandler handler, final String host,
987 final String realm) {
988 String username = null;
989 String password = null;
990
991 boolean reuseHttpAuthUsernamePassword
992 = handler.useHttpAuthUsernamePassword();
993
994 if (reuseHttpAuthUsernamePassword && view != null) {
995 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
996 if (credentials != null && credentials.length == 2) {
997 username = credentials[0];
998 password = credentials[1];
999 }
1000 }
1001
1002 if (username != null && password != null) {
1003 handler.proceed(username, password);
1004 } else {
Ben Murdochfdd37112011-08-05 15:48:14 +01001005 if (tab.inForeground() && !handler.suppressDialog()) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001006 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
1007 } else {
1008 handler.cancel();
1009 }
1010 }
1011 }
1012
1013 @Override
1014 public void onDownloadStart(Tab tab, String url, String userAgent,
1015 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001016 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -05001017 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001018 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
1019 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001020 // This Tab was opened for the sole purpose of downloading a
1021 // file. Remove it.
1022 if (tab == mTabControl.getCurrentTab()) {
1023 // In this case, the Tab is still on top.
1024 goBackOnePageOrQuit();
1025 } else {
1026 // In this case, it is not.
1027 closeTab(tab);
1028 }
1029 }
1030 }
1031
1032 @Override
1033 public Bitmap getDefaultVideoPoster() {
1034 return mUi.getDefaultVideoPoster();
1035 }
1036
1037 @Override
1038 public View getVideoLoadingProgressView() {
1039 return mUi.getVideoLoadingProgressView();
1040 }
1041
1042 @Override
1043 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1044 SslError error) {
1045 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1046 }
1047
Patrick Scott92066772011-03-10 08:46:27 -05001048 @Override
1049 public void showAutoLogin(Tab tab) {
1050 assert tab.inForeground();
1051 // Update the title bar to show the auto-login request.
1052 mUi.showAutoLogin(tab);
1053 }
1054
1055 @Override
1056 public void hideAutoLogin(Tab tab) {
1057 assert tab.inForeground();
1058 mUi.hideAutoLogin(tab);
1059 }
1060
Michael Kolb8233fac2010-10-26 16:08:53 -07001061 // helper method
1062
1063 /*
1064 * Update the favorites icon if the private browsing isn't enabled and the
1065 * icon is valid.
1066 */
1067 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1068 final String url, Bitmap favicon) {
1069 if (favicon == null) {
1070 return;
1071 }
1072 if (!tab.isPrivateBrowsingEnabled()) {
1073 Bookmarks.updateFavicon(mActivity
1074 .getContentResolver(), originalUrl, url, favicon);
1075 }
1076 }
1077
Leon Scroggins4cd97792010-12-03 15:31:56 -05001078 @Override
1079 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001080 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001081 mUi.bookmarkedStatusHasChanged(tab);
1082 }
1083
Michael Kolb8233fac2010-10-26 16:08:53 -07001084 // end WebViewController
1085
1086 protected void pageUp() {
1087 getCurrentTopWebView().pageUp(false);
1088 }
1089
1090 protected void pageDown() {
1091 getCurrentTopWebView().pageDown(false);
1092 }
1093
1094 // callback from phone title bar
1095 public void editUrl() {
1096 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001097 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001098 }
1099
Michael Kolbcfa3af52010-12-14 10:36:11 -08001100 public void startVoiceSearch() {
1101 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1102 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1103 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1104 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1105 mActivity.getComponentName().flattenToString());
1106 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001107 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001108 mActivity.startActivity(intent);
1109 }
1110
Michael Kolb11d19782011-03-20 10:17:40 -07001111 @Override
1112 public void activateVoiceSearchMode(String title, List<String> results) {
1113 mUi.showVoiceTitleBar(title, results);
Michael Kolb8233fac2010-10-26 16:08:53 -07001114 }
1115
1116 public void revertVoiceSearchMode(Tab tab) {
1117 mUi.revertVoiceTitleBar(tab);
1118 }
1119
Michael Kolb736990c2011-03-20 10:01:20 -07001120 public boolean supportsVoiceSearch() {
John Reck35e9dd62011-04-25 09:01:54 -07001121 SearchEngine searchEngine = getSettings().getSearchEngine();
Michael Kolb736990c2011-03-20 10:01:20 -07001122 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1123 }
1124
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001125 public void showCustomView(Tab tab, View view, int requestedOrientation,
Michael Kolb8233fac2010-10-26 16:08:53 -07001126 WebChromeClient.CustomViewCallback callback) {
1127 if (tab.inForeground()) {
1128 if (mUi.isCustomViewShowing()) {
1129 callback.onCustomViewHidden();
1130 return;
1131 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001132 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001133 // Save the menu state and set it to empty while the custom
1134 // view is showing.
1135 mOldMenuState = mMenuState;
1136 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001137 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001138 }
1139 }
1140
1141 @Override
1142 public void hideCustomView() {
1143 if (mUi.isCustomViewShowing()) {
1144 mUi.onHideCustomView();
1145 // Reset the old menu state.
1146 mMenuState = mOldMenuState;
1147 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001148 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001149 }
1150 }
1151
1152 protected void onActivityResult(int requestCode, int resultCode,
1153 Intent intent) {
1154 if (getCurrentTopWebView() == null) return;
1155 switch (requestCode) {
1156 case PREFERENCES_PAGE:
1157 if (resultCode == Activity.RESULT_OK && intent != null) {
1158 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001159 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001160 mTabControl.removeParentChildRelationShips();
1161 }
1162 }
1163 break;
1164 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001165 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001166 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001167 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001168 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001169 case AUTOFILL_SETUP:
1170 // Determine whether a profile was actually set up or not
1171 // and if so, send the message back to the WebTextView to
1172 // fill the form with the new profile.
1173 if (getSettings().getAutoFillProfile() != null) {
1174 mAutoFillSetupMessage.sendToTarget();
1175 mAutoFillSetupMessage = null;
1176 }
1177 break;
John Reckd3e4d5b2011-07-13 15:48:43 -07001178 case COMBO_VIEW:
1179 if (intent == null || resultCode != Activity.RESULT_OK) {
1180 break;
1181 }
John Reck3ba45532011-08-11 16:26:53 -07001182 mUi.showWeb(false);
John Reckd3e4d5b2011-07-13 15:48:43 -07001183 if (Intent.ACTION_VIEW.equals(intent.getAction())) {
1184 Tab t = getCurrentTab();
1185 Uri uri = intent.getData();
1186 loadUrl(t, uri.toString());
1187 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
1188 String[] urls = intent.getStringArrayExtra(
1189 ComboViewActivity.EXTRA_OPEN_ALL);
1190 Tab parent = getCurrentTab();
1191 for (String url : urls) {
1192 parent = openTab(url, parent,
1193 !mSettings.openInBackground(), true);
1194 }
1195 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
1196 long id = intent.getLongExtra(
1197 ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
1198 if (id >= 0) {
1199 createNewSnapshotTab(id, true);
1200 }
1201 }
1202 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001203 default:
1204 break;
1205 }
1206 getCurrentTopWebView().requestFocus();
1207 }
1208
1209 /**
1210 * Open the Go page.
1211 * @param startWithHistory If true, open starting on the history tab.
1212 * Otherwise, start with the bookmarks tab.
1213 */
1214 @Override
Michael Kolb315d5022011-10-13 12:47:11 -07001215 public void bookmarksOrHistoryPicker(ComboViews startView) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001216 if (mTabControl.getCurrentWebView() == null) {
1217 return;
1218 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001219 // clear action mode
1220 if (isInCustomActionMode()) {
1221 endActionMode();
1222 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001223 Bundle extras = new Bundle();
1224 // Disable opening in a new window if we have maxed out the windows
1225 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1226 !mTabControl.canCreateNewTab());
Michael Kolb315d5022011-10-13 12:47:11 -07001227 mUi.showComboView(startView, extras);
Michael Kolb8233fac2010-10-26 16:08:53 -07001228 }
1229
1230 // combo view callbacks
1231
Michael Kolb8233fac2010-10-26 16:08:53 -07001232 // key handling
1233 protected void onBackKey() {
1234 if (!mUi.onBackKey()) {
1235 WebView subwindow = mTabControl.getCurrentSubWindow();
1236 if (subwindow != null) {
1237 if (subwindow.canGoBack()) {
1238 subwindow.goBack();
1239 } else {
1240 dismissSubWindow(mTabControl.getCurrentTab());
1241 }
1242 } else {
1243 goBackOnePageOrQuit();
1244 }
1245 }
1246 }
1247
Michael Kolb4bd767d2011-05-27 11:33:55 -07001248 protected boolean onMenuKey() {
1249 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001250 }
1251
Michael Kolb8233fac2010-10-26 16:08:53 -07001252 // menu handling and state
1253 // TODO: maybe put into separate handler
1254
1255 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckd73c5a22010-12-22 10:22:50 -08001256 if (mMenuState == EMPTY_MENU) {
1257 return false;
1258 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001259 MenuInflater inflater = mActivity.getMenuInflater();
1260 inflater.inflate(R.menu.browser, menu);
John Reckefe66742012-01-26 10:38:27 -08001261 menu.findItem(R.id.save_snapshot_menu_id).setEnabled(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001262 return true;
1263 }
1264
1265 protected void onCreateContextMenu(ContextMenu menu, View v,
1266 ContextMenuInfo menuInfo) {
John Reck0f602f32011-07-07 15:38:43 -07001267 if (v instanceof TitleBar) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001268 return;
1269 }
1270 if (!(v instanceof WebView)) {
1271 return;
1272 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001273 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001274 WebView.HitTestResult result = webview.getHitTestResult();
1275 if (result == null) {
1276 return;
1277 }
1278
1279 int type = result.getType();
1280 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1281 Log.w(LOGTAG,
1282 "We should not show context menu when nothing is touched");
1283 return;
1284 }
1285 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1286 // let TextView handles context menu
1287 return;
1288 }
1289
1290 // Note, http://b/issue?id=1106666 is requesting that
1291 // an inflated menu can be used again. This is not available
1292 // yet, so inflate each time (yuk!)
1293 MenuInflater inflater = mActivity.getMenuInflater();
1294 inflater.inflate(R.menu.browsercontext, menu);
1295
1296 // Show the correct menu group
1297 final String extra = result.getExtra();
Michael Kolbc159c1a2011-12-15 16:06:38 -08001298 if (extra == null) return;
Michael Kolb8233fac2010-10-26 16:08:53 -07001299 menu.setGroupVisible(R.id.PHONE_MENU,
1300 type == WebView.HitTestResult.PHONE_TYPE);
1301 menu.setGroupVisible(R.id.EMAIL_MENU,
1302 type == WebView.HitTestResult.EMAIL_TYPE);
1303 menu.setGroupVisible(R.id.GEO_MENU,
1304 type == WebView.HitTestResult.GEO_TYPE);
1305 menu.setGroupVisible(R.id.IMAGE_MENU,
1306 type == WebView.HitTestResult.IMAGE_TYPE
1307 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1308 menu.setGroupVisible(R.id.ANCHOR_MENU,
1309 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1310 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001311 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1312 || type == WebView.HitTestResult.PHONE_TYPE
1313 || type == WebView.HitTestResult.EMAIL_TYPE
1314 || type == WebView.HitTestResult.GEO_TYPE;
1315 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1316 if (hitText) {
1317 menu.findItem(R.id.select_text_menu_id)
1318 .setOnMenuItemClickListener(new SelectText(webview));
1319 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001320 // Setup custom handling depending on the type
1321 switch (type) {
1322 case WebView.HitTestResult.PHONE_TYPE:
1323 menu.setHeaderTitle(Uri.decode(extra));
1324 menu.findItem(R.id.dial_context_menu_id).setIntent(
1325 new Intent(Intent.ACTION_VIEW, Uri
1326 .parse(WebView.SCHEME_TEL + extra)));
1327 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1328 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1329 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1330 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1331 addIntent);
1332 menu.findItem(R.id.copy_phone_context_menu_id)
1333 .setOnMenuItemClickListener(
1334 new Copy(extra));
1335 break;
1336
1337 case WebView.HitTestResult.EMAIL_TYPE:
1338 menu.setHeaderTitle(extra);
1339 menu.findItem(R.id.email_context_menu_id).setIntent(
1340 new Intent(Intent.ACTION_VIEW, Uri
1341 .parse(WebView.SCHEME_MAILTO + extra)));
1342 menu.findItem(R.id.copy_mail_context_menu_id)
1343 .setOnMenuItemClickListener(
1344 new Copy(extra));
1345 break;
1346
1347 case WebView.HitTestResult.GEO_TYPE:
1348 menu.setHeaderTitle(extra);
1349 menu.findItem(R.id.map_context_menu_id).setIntent(
1350 new Intent(Intent.ACTION_VIEW, Uri
1351 .parse(WebView.SCHEME_GEO
1352 + URLEncoder.encode(extra))));
1353 menu.findItem(R.id.copy_geo_context_menu_id)
1354 .setOnMenuItemClickListener(
1355 new Copy(extra));
1356 break;
1357
1358 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1359 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001360 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001361 // decide whether to show the open link in new tab option
1362 boolean showNewTab = mTabControl.canCreateNewTab();
1363 MenuItem newTabItem
1364 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001365 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001366 ? R.string.contextmenu_openlink_newwindow_background
1367 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001368 newTabItem.setVisible(showNewTab);
1369 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001370 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1371 newTabItem.setOnMenuItemClickListener(
1372 new MenuItem.OnMenuItemClickListener() {
1373 @Override
1374 public boolean onMenuItemClick(MenuItem item) {
1375 final HashMap<String, WebView> hrefMap =
1376 new HashMap<String, WebView>();
1377 hrefMap.put("webview", webview);
1378 final Message msg = mHandler.obtainMessage(
1379 FOCUS_NODE_HREF,
1380 R.id.open_newtab_context_menu_id,
1381 0, hrefMap);
1382 webview.requestFocusNodeHref(msg);
1383 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001384 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001385 });
1386 } else {
1387 newTabItem.setOnMenuItemClickListener(
1388 new MenuItem.OnMenuItemClickListener() {
1389 @Override
1390 public boolean onMenuItemClick(MenuItem item) {
1391 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001392 openTab(extra, parent,
1393 !mSettings.openInBackground(),
1394 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001395 return true;
1396 }
1397 });
1398 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001399 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001400 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1401 break;
1402 }
1403 // otherwise fall through to handle image part
1404 case WebView.HitTestResult.IMAGE_TYPE:
1405 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1406 menu.setHeaderTitle(extra);
1407 }
Michael Kolb3639c4c2011-09-28 15:36:40 -07001408 menu.findItem(R.id.view_image_context_menu_id)
1409 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1410 @Override
1411 public boolean onMenuItemClick(MenuItem item) {
1412 openTab(extra, mTabControl.getCurrentTab(), true, true);
1413 return false;
1414 }
1415 });
Michael Kolb8233fac2010-10-26 16:08:53 -07001416 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001417 setOnMenuItemClickListener(
1418 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001419 menu.findItem(R.id.set_wallpaper_context_menu_id).
1420 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1421 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001422 break;
1423
1424 default:
1425 Log.w(LOGTAG, "We should not get here.");
1426 break;
1427 }
1428 //update the ui
1429 mUi.onContextMenuCreated(menu);
1430 }
1431
1432 /**
1433 * As the menu can be open when loading state changes
1434 * we must manually update the state of the stop/reload menu
1435 * item
1436 */
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001437 private void updateInLoadMenuItems(Menu menu, Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001438 if (menu == null) {
1439 return;
1440 }
1441 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolbb8337132011-11-28 15:07:39 -08001442 MenuItem src = ((tab != null) && tab.inPageLoad()) ?
Michael Kolb8233fac2010-10-26 16:08:53 -07001443 menu.findItem(R.id.stop_menu_id):
1444 menu.findItem(R.id.reload_menu_id);
1445 if (src != null) {
1446 dest.setIcon(src.getIcon());
1447 dest.setTitle(src.getTitle());
1448 }
1449 }
1450
John Reckb3417f02011-01-14 11:01:05 -08001451 boolean onPrepareOptionsMenu(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001452 updateInLoadMenuItems(menu, getCurrentTab());
John Recke1a03a32011-09-14 17:04:16 -07001453 // hold on to the menu reference here; it is used by the page callbacks
1454 // to update the menu based on loading state
1455 mCachedMenu = menu;
Michael Kolb8233fac2010-10-26 16:08:53 -07001456 // Note: setVisible will decide whether an item is visible; while
1457 // setEnabled() will decide whether an item is enabled, which also means
1458 // whether the matching shortcut key will function.
1459 switch (mMenuState) {
1460 case EMPTY_MENU:
1461 if (mCurrentMenuState != mMenuState) {
1462 menu.setGroupVisible(R.id.MAIN_MENU, false);
1463 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1464 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1465 }
1466 break;
1467 default:
1468 if (mCurrentMenuState != mMenuState) {
1469 menu.setGroupVisible(R.id.MAIN_MENU, true);
1470 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1471 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1472 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001473 updateMenuState(getCurrentTab(), menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001474 break;
1475 }
1476 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001477 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001478 }
1479
Michael Kolb4bf79712011-07-14 14:18:12 -07001480 @Override
1481 public void updateMenuState(Tab tab, Menu menu) {
1482 boolean canGoBack = false;
1483 boolean canGoForward = false;
1484 boolean isHome = false;
John Reck42229bc2011-08-19 13:26:43 -07001485 boolean isDesktopUa = false;
John Recke1a03a32011-09-14 17:04:16 -07001486 boolean isLive = false;
Michael Kolb4bf79712011-07-14 14:18:12 -07001487 if (tab != null) {
1488 canGoBack = tab.canGoBack();
1489 canGoForward = tab.canGoForward();
1490 isHome = mSettings.getHomePage().equals(tab.getUrl());
John Reck42229bc2011-08-19 13:26:43 -07001491 isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
John Recke1a03a32011-09-14 17:04:16 -07001492 isLive = !tab.isSnapshot();
Michael Kolb4bf79712011-07-14 14:18:12 -07001493 }
1494 final MenuItem back = menu.findItem(R.id.back_menu_id);
1495 back.setEnabled(canGoBack);
1496
1497 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1498 home.setEnabled(!isHome);
1499
1500 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1501 forward.setEnabled(canGoForward);
1502
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001503 final MenuItem source = menu.findItem(isInLoad() ? R.id.stop_menu_id
1504 : R.id.reload_menu_id);
Michael Kolb4bf79712011-07-14 14:18:12 -07001505 final MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolb7ab75ee2011-07-14 16:36:38 -07001506 if (source != null && dest != null) {
1507 dest.setTitle(source.getTitle());
1508 dest.setIcon(source.getIcon());
1509 }
John Recke1a03a32011-09-14 17:04:16 -07001510 menu.setGroupVisible(R.id.NAV_MENU, isLive);
Michael Kolb4bf79712011-07-14 14:18:12 -07001511
1512 // decide whether to show the share link option
1513 PackageManager pm = mActivity.getPackageManager();
1514 Intent send = new Intent(Intent.ACTION_SEND);
1515 send.setType("text/plain");
1516 ResolveInfo ri = pm.resolveActivity(send,
1517 PackageManager.MATCH_DEFAULT_ONLY);
1518 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1519
1520 boolean isNavDump = mSettings.enableNavDump();
1521 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1522 nav.setVisible(isNavDump);
1523 nav.setEnabled(isNavDump);
1524
1525 boolean showDebugSettings = mSettings.isDebugEnabled();
John Reck42229bc2011-08-19 13:26:43 -07001526 final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
1527 uaSwitcher.setChecked(isDesktopUa);
John Recke1a03a32011-09-14 17:04:16 -07001528 menu.setGroupVisible(R.id.LIVE_MENU, isLive);
1529 menu.setGroupVisible(R.id.SNAPSHOT_MENU, !isLive);
Michael Kolb315d5022011-10-13 12:47:11 -07001530 menu.setGroupVisible(R.id.COMBO_MENU, false);
Michael Kolb4bf79712011-07-14 14:18:12 -07001531
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001532 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001533 }
1534
Michael Kolb8233fac2010-10-26 16:08:53 -07001535 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001536 if (null == getCurrentTopWebView()) {
1537 return false;
1538 }
1539 if (mMenuIsDown) {
1540 // The shortcut action consumes the MENU. Even if it is still down,
1541 // it won't trigger the next shortcut action. In the case of the
1542 // shortcut action triggering a new activity, like Bookmarks, we
1543 // won't get onKeyUp for MENU. So it is important to reset it here.
1544 mMenuIsDown = false;
1545 }
Michael Kolb3ca12752011-07-20 13:52:25 -07001546 if (mUi.onOptionsItemSelected(item)) {
1547 // ui callback handled it
1548 return true;
1549 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001550 switch (item.getItemId()) {
1551 // -- Main menu
1552 case R.id.new_tab_menu_id:
1553 openTabToHomePage();
1554 break;
1555
1556 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001557 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001558 break;
1559
1560 case R.id.goto_menu_id:
1561 editUrl();
1562 break;
1563
1564 case R.id.bookmarks_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001565 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
1566 break;
1567
1568 case R.id.history_menu_id:
1569 bookmarksOrHistoryPicker(ComboViews.History);
1570 break;
1571
1572 case R.id.snapshots_menu_id:
1573 bookmarksOrHistoryPicker(ComboViews.Snapshots);
Michael Kolb8233fac2010-10-26 16:08:53 -07001574 break;
1575
Michael Kolb8233fac2010-10-26 16:08:53 -07001576 case R.id.add_bookmark_menu_id:
John Recka60fffa2011-09-06 16:30:29 -07001577 Intent bookmarkIntent = createBookmarkCurrentPageIntent(false);
1578 if (bookmarkIntent != null) {
1579 mActivity.startActivity(bookmarkIntent);
1580 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001581 break;
1582
1583 case R.id.stop_reload_menu_id:
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001584 if (isInLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001585 stopLoading();
1586 } else {
1587 getCurrentTopWebView().reload();
1588 }
1589 break;
1590
1591 case R.id.back_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001592 getCurrentTab().goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07001593 break;
1594
1595 case R.id.forward_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001596 getCurrentTab().goForward();
Michael Kolb8233fac2010-10-26 16:08:53 -07001597 break;
1598
1599 case R.id.close_menu_id:
1600 // Close the subwindow if it exists.
1601 if (mTabControl.getCurrentSubWindow() != null) {
1602 dismissSubWindow(mTabControl.getCurrentTab());
1603 break;
1604 }
1605 closeCurrentTab();
1606 break;
1607
1608 case R.id.homepage_menu_id:
1609 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07001610 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07001611 break;
1612
1613 case R.id.preferences_menu_id:
1614 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1615 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1616 getCurrentTopWebView().getUrl());
1617 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1618 break;
1619
1620 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001621 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001622 break;
1623
John Reck2bc80422011-06-30 15:11:49 -07001624 case R.id.save_snapshot_menu_id:
1625 final Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07001626 if (source == null) break;
John Reckd8c74522011-06-14 08:45:00 -07001627 final ContentResolver cr = mActivity.getContentResolver();
1628 final ContentValues values = source.createSnapshotValues();
John Reck2bc80422011-06-30 15:11:49 -07001629 if (values != null) {
1630 new AsyncTask<Tab, Void, Long>() {
John Reckd8c74522011-06-14 08:45:00 -07001631
John Reck2bc80422011-06-30 15:11:49 -07001632 @Override
1633 protected Long doInBackground(Tab... params) {
1634 Uri result = cr.insert(Snapshots.CONTENT_URI, values);
John Reck93384ff2011-11-10 11:29:18 -08001635 if (result == null) {
1636 return null;
1637 }
John Reck2bc80422011-06-30 15:11:49 -07001638 long id = ContentUris.parseId(result);
1639 return id;
John Reckd8c74522011-06-14 08:45:00 -07001640 }
John Reckf33b1632011-06-04 20:00:23 -07001641
John Reck2bc80422011-06-30 15:11:49 -07001642 @Override
1643 protected void onPostExecute(Long id) {
John Reck93384ff2011-11-10 11:29:18 -08001644 if (id == null) {
1645 Toast.makeText(mActivity, R.string.snapshot_failed,
1646 Toast.LENGTH_SHORT).show();
1647 return;
1648 }
John Reck2bc80422011-06-30 15:11:49 -07001649 Bundle b = new Bundle();
1650 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
1651 mUi.showComboView(ComboViews.Snapshots, b);
1652 };
1653 }.execute(source);
1654 } else {
1655 Toast.makeText(mActivity, R.string.snapshot_failed,
Leon Scrogginsac993842011-02-02 12:54:07 -05001656 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001657 }
Leon Scrogginsac993842011-02-02 12:54:07 -05001658 break;
1659
Michael Kolb8233fac2010-10-26 16:08:53 -07001660 case R.id.page_info_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001661 showPageInfo();
Michael Kolb8233fac2010-10-26 16:08:53 -07001662 break;
1663
John Recke1a03a32011-09-14 17:04:16 -07001664 case R.id.snapshot_go_live:
1665 goLive();
1666 return true;
1667
Michael Kolb8233fac2010-10-26 16:08:53 -07001668 case R.id.share_page_menu_id:
1669 Tab currentTab = mTabControl.getCurrentTab();
1670 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001671 return false;
1672 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001673 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001674 break;
1675
1676 case R.id.dump_nav_menu_id:
1677 getCurrentTopWebView().debugDump();
1678 break;
1679
Michael Kolb8233fac2010-10-26 16:08:53 -07001680 case R.id.zoom_in_menu_id:
1681 getCurrentTopWebView().zoomIn();
1682 break;
1683
1684 case R.id.zoom_out_menu_id:
1685 getCurrentTopWebView().zoomOut();
1686 break;
1687
1688 case R.id.view_downloads_menu_id:
1689 viewDownloads();
1690 break;
1691
John Reck42229bc2011-08-19 13:26:43 -07001692 case R.id.ua_desktop_menu_id:
1693 WebView web = getCurrentWebView();
1694 mSettings.toggleDesktopUseragent(web);
1695 web.loadUrl(web.getOriginalUrl());
1696 break;
1697
Michael Kolb8233fac2010-10-26 16:08:53 -07001698 case R.id.window_one_menu_id:
1699 case R.id.window_two_menu_id:
1700 case R.id.window_three_menu_id:
1701 case R.id.window_four_menu_id:
1702 case R.id.window_five_menu_id:
1703 case R.id.window_six_menu_id:
1704 case R.id.window_seven_menu_id:
1705 case R.id.window_eight_menu_id:
1706 {
1707 int menuid = item.getItemId();
1708 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1709 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1710 Tab desiredTab = mTabControl.getTab(id);
1711 if (desiredTab != null &&
1712 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001713 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001714 }
1715 break;
1716 }
1717 }
1718 }
1719 break;
1720
1721 default:
1722 return false;
1723 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001724 return true;
1725 }
1726
John Recke1a03a32011-09-14 17:04:16 -07001727 private void goLive() {
1728 Tab t = getCurrentTab();
1729 t.loadUrl(t.getUrl(), null);
1730 }
1731
Michael Kolb315d5022011-10-13 12:47:11 -07001732 @Override
1733 public void showPageInfo() {
1734 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
1735 }
1736
Michael Kolb8233fac2010-10-26 16:08:53 -07001737 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001738 // Let the History and Bookmark fragments handle menus they created.
1739 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1740 return false;
1741 }
1742
Michael Kolb8233fac2010-10-26 16:08:53 -07001743 int id = item.getItemId();
1744 boolean result = true;
1745 switch (id) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001746 // -- Browser context menu
1747 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001748 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001749 case R.id.copy_link_context_menu_id:
1750 final WebView webView = getCurrentTopWebView();
1751 if (null == webView) {
1752 result = false;
1753 break;
1754 }
1755 final HashMap<String, WebView> hrefMap =
1756 new HashMap<String, WebView>();
1757 hrefMap.put("webview", webView);
1758 final Message msg = mHandler.obtainMessage(
1759 FOCUS_NODE_HREF, id, 0, hrefMap);
1760 webView.requestFocusNodeHref(msg);
1761 break;
1762
1763 default:
1764 // For other context menus
1765 result = onOptionsItemSelected(item);
1766 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001767 return result;
1768 }
1769
1770 /**
1771 * support programmatically opening the context menu
1772 */
1773 public void openContextMenu(View view) {
1774 mActivity.openContextMenu(view);
1775 }
1776
1777 /**
1778 * programmatically open the options menu
1779 */
1780 public void openOptionsMenu() {
1781 mActivity.openOptionsMenu();
1782 }
1783
1784 public boolean onMenuOpened(int featureId, Menu menu) {
1785 if (mOptionsMenuOpen) {
1786 if (mConfigChanged) {
1787 // We do not need to make any changes to the state of the
1788 // title bar, since the only thing that happened was a
1789 // change in orientation
1790 mConfigChanged = false;
1791 } else {
1792 if (!mExtendedMenuOpen) {
1793 mExtendedMenuOpen = true;
1794 mUi.onExtendedMenuOpened();
1795 } else {
1796 // Switching the menu back to icon view, so show the
1797 // title bar once again.
1798 mExtendedMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001799 mUi.onExtendedMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001800 }
1801 }
1802 } else {
1803 // The options menu is closed, so open it, and show the title
1804 mOptionsMenuOpen = true;
1805 mConfigChanged = false;
1806 mExtendedMenuOpen = false;
1807 mUi.onOptionsMenuOpened();
1808 }
1809 return true;
1810 }
1811
1812 public void onOptionsMenuClosed(Menu menu) {
1813 mOptionsMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001814 mUi.onOptionsMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001815 }
1816
1817 public void onContextMenuClosed(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001818 mUi.onContextMenuClosed(menu, isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001819 }
1820
1821 // Helper method for getting the top window.
1822 @Override
1823 public WebView getCurrentTopWebView() {
1824 return mTabControl.getCurrentTopWebView();
1825 }
1826
1827 @Override
1828 public WebView getCurrentWebView() {
1829 return mTabControl.getCurrentWebView();
1830 }
1831
1832 /*
1833 * This method is called as a result of the user selecting the options
1834 * menu to see the download window. It shows the download window on top of
1835 * the current window.
1836 */
1837 void viewDownloads() {
1838 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1839 mActivity.startActivity(intent);
1840 }
1841
John Reck30b065e2011-07-19 10:58:05 -07001842 int getActionModeHeight() {
1843 TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
1844 new int[] { android.R.attr.actionBarSize });
1845 int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
1846 actionBarSizeTypedArray.recycle();
1847 return size;
1848 }
1849
Michael Kolb8233fac2010-10-26 16:08:53 -07001850 // action mode
1851
1852 void onActionModeStarted(ActionMode mode) {
1853 mUi.onActionModeStarted(mode);
1854 mActionMode = mode;
1855 }
1856
1857 /*
1858 * True if a custom ActionMode (i.e. find or select) is in use.
1859 */
1860 @Override
1861 public boolean isInCustomActionMode() {
1862 return mActionMode != null;
1863 }
1864
1865 /*
1866 * End the current ActionMode.
1867 */
1868 @Override
1869 public void endActionMode() {
1870 if (mActionMode != null) {
1871 mActionMode.finish();
1872 }
1873 }
1874
1875 /*
1876 * Called by find and select when they are finished. Replace title bars
1877 * as necessary.
1878 */
1879 public void onActionModeFinished(ActionMode mode) {
1880 if (!isInCustomActionMode()) return;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001881 mUi.onActionModeFinished(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001882 mActionMode = null;
1883 }
1884
1885 boolean isInLoad() {
Michael Kolbc5b0b2d2011-11-29 16:13:35 -08001886 final Tab tab = getCurrentTab();
1887 return (tab != null) && tab.inPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07001888 }
1889
1890 // bookmark handling
1891
1892 /**
1893 * add the current page as a bookmark to the given folder id
1894 * @param folderId use -1 for the default folder
John Reckd3e4d5b2011-07-13 15:48:43 -07001895 * @param editExisting If true, check to see whether the site is already
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001896 * bookmarked, and if it is, edit that bookmark. If false, and
1897 * the site is already bookmarked, do not attempt to edit the
1898 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001899 */
1900 @Override
John Reckd3e4d5b2011-07-13 15:48:43 -07001901 public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
John Recka60fffa2011-09-06 16:30:29 -07001902 WebView w = getCurrentTopWebView();
1903 if (w == null) {
1904 return null;
1905 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001906 Intent i = new Intent(mActivity,
1907 AddBookmarkPage.class);
Michael Kolb8233fac2010-10-26 16:08:53 -07001908 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1909 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1910 String touchIconUrl = w.getTouchIconUrl();
1911 if (touchIconUrl != null) {
1912 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1913 WebSettings settings = w.getSettings();
1914 if (settings != null) {
1915 i.putExtra(AddBookmarkPage.USER_AGENT,
1916 settings.getUserAgentString());
1917 }
1918 }
1919 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1920 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1921 getDesiredThumbnailHeight(mActivity)));
1922 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07001923 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001924 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1925 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001926 // Put the dialog at the upper right of the screen, covering the
1927 // star on the title bar.
1928 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07001929 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07001930 }
1931
1932 // file chooser
1933 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1934 mUploadHandler = new UploadHandler(this);
1935 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1936 }
1937
1938 // thumbnails
1939
1940 /**
1941 * Return the desired width for thumbnail screenshots, which are stored in
1942 * the database, and used on the bookmarks screen.
1943 * @param context Context for finding out the density of the screen.
1944 * @return desired width for thumbnail screenshot.
1945 */
1946 static int getDesiredThumbnailWidth(Context context) {
1947 return context.getResources().getDimensionPixelOffset(
1948 R.dimen.bookmarkThumbnailWidth);
1949 }
1950
1951 /**
1952 * Return the desired height for thumbnail screenshots, which are stored in
1953 * the database, and used on the bookmarks screen.
1954 * @param context Context for finding out the density of the screen.
1955 * @return desired height for thumbnail screenshot.
1956 */
1957 static int getDesiredThumbnailHeight(Context context) {
1958 return context.getResources().getDimensionPixelOffset(
1959 R.dimen.bookmarkThumbnailHeight);
1960 }
1961
John Reck8cc92352011-07-06 17:41:52 -07001962 static Bitmap createScreenshot(WebView view, int width, int height) {
John Reckd7dd9b22011-08-30 09:18:29 -07001963 if (view == null || view.getContentHeight() == 0
1964 || view.getContentWidth() == 0) {
1965 return null;
1966 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001967 // We render to a bitmap 2x the desired size so that we can then
1968 // re-scale it with filtering since canvas.scale doesn't filter
1969 // This helps reduce aliasing at the cost of being slightly blurry
1970 final int filter_scale = 2;
John Reckd7dd9b22011-08-30 09:18:29 -07001971 int scaledWidth = width * filter_scale;
1972 int scaledHeight = height * filter_scale;
1973 if (sThumbnailBitmap == null || sThumbnailBitmap.getWidth() != scaledWidth
1974 || sThumbnailBitmap.getHeight() != scaledHeight) {
1975 if (sThumbnailBitmap != null) {
1976 sThumbnailBitmap.recycle();
1977 sThumbnailBitmap = null;
1978 }
1979 sThumbnailBitmap =
1980 Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.RGB_565);
Michael Kolb8233fac2010-10-26 16:08:53 -07001981 }
John Reckd7dd9b22011-08-30 09:18:29 -07001982 Canvas canvas = new Canvas(sThumbnailBitmap);
1983 int contentWidth = view.getContentWidth();
1984 float overviewScale = scaledWidth / (view.getScale() * contentWidth);
1985 if (view instanceof BrowserWebView) {
1986 int dy = -((BrowserWebView)view).getTitleHeight();
1987 canvas.translate(0, dy * overviewScale);
1988 }
1989
1990 canvas.scale(overviewScale, overviewScale);
1991
1992 if (view instanceof BrowserWebView) {
1993 ((BrowserWebView)view).drawContent(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07001994 } else {
John Reckd7dd9b22011-08-30 09:18:29 -07001995 view.draw(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07001996 }
John Reckd7dd9b22011-08-30 09:18:29 -07001997 Bitmap ret = Bitmap.createScaledBitmap(sThumbnailBitmap,
1998 width, height, true);
Dianne Hackborn43cfe8a2011-08-02 16:59:35 -07001999 canvas.setBitmap(null);
John Reck5c6ac2f2011-01-05 10:18:03 -08002000 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07002001 }
2002
John Reck34ef2672011-02-10 11:30:55 -08002003 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002004 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07002005 // FIXME: Would like to make sure there is actually something to
2006 // draw, but the API for that (WebViewCore.pictureReady()) is not
2007 // currently accessible here.
2008
John Reck34ef2672011-02-10 11:30:55 -08002009 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08002010 if (view == null) {
2011 // Tab was destroyed
2012 return;
2013 }
John Reck34ef2672011-02-10 11:30:55 -08002014 final String url = tab.getUrl();
2015 final String originalUrl = view.getOriginalUrl();
John Reck34ef2672011-02-10 11:30:55 -08002016 if (TextUtils.isEmpty(url)) {
2017 return;
2018 }
2019
2020 // Only update thumbnails for web urls (http(s)://), not for
2021 // about:, javascript:, data:, etc...
2022 // Unless it is a bookmarked site, then always update
2023 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2024 return;
2025 }
2026
Michael Kolb8233fac2010-10-26 16:08:53 -07002027 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2028 getDesiredThumbnailHeight(mActivity));
2029 if (bm == null) {
2030 return;
2031 }
2032
2033 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002034 new AsyncTask<Void, Void, Void>() {
2035 @Override
2036 protected Void doInBackground(Void... unused) {
2037 Cursor cursor = null;
2038 try {
2039 // TODO: Clean this up
2040 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2041 if (cursor != null && cursor.moveToFirst()) {
2042 final ByteArrayOutputStream os =
2043 new ByteArrayOutputStream();
2044 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002045
John Reck34ef2672011-02-10 11:30:55 -08002046 ContentValues values = new ContentValues();
2047 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002048
John Reck34ef2672011-02-10 11:30:55 -08002049 do {
John Reck617fd832011-02-16 14:35:59 -08002050 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002051 cr.update(Images.CONTENT_URI, values, null, null);
2052 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002053 }
John Reck34ef2672011-02-10 11:30:55 -08002054 } catch (IllegalStateException e) {
2055 // Ignore
2056 } finally {
2057 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002058 }
John Reck34ef2672011-02-10 11:30:55 -08002059 return null;
2060 }
2061 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002062 }
2063
2064 private class Copy implements OnMenuItemClickListener {
2065 private CharSequence mText;
2066
2067 public boolean onMenuItemClick(MenuItem item) {
2068 copy(mText);
2069 return true;
2070 }
2071
2072 public Copy(CharSequence toCopy) {
2073 mText = toCopy;
2074 }
2075 }
2076
Leon Scroggins63c02662010-11-18 15:16:27 -05002077 private static class Download implements OnMenuItemClickListener {
2078 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002079 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002080 private boolean mPrivateBrowsing;
George Mount387d45d2011-10-07 15:57:53 -07002081 private static final String FALLBACK_EXTENSION = "dat";
2082 private static final String IMAGE_BASE_FORMAT = "yyyy-MM-dd-HH-mm-ss-";
Michael Kolb8233fac2010-10-26 16:08:53 -07002083
2084 public boolean onMenuItemClick(MenuItem item) {
George Mount387d45d2011-10-07 15:57:53 -07002085 if (DataUri.isDataUri(mText)) {
2086 saveDataUri();
2087 } else {
2088 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
2089 null, null, mPrivateBrowsing);
2090 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002091 return true;
2092 }
2093
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002094 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002095 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002096 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002097 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002098 }
George Mount387d45d2011-10-07 15:57:53 -07002099
2100 /**
2101 * Treats mText as a data URI and writes its contents to a file
2102 * based on the current time.
2103 */
2104 private void saveDataUri() {
2105 FileOutputStream outputStream = null;
2106 try {
2107 DataUri uri = new DataUri(mText);
2108 File target = getTarget(uri);
2109 outputStream = new FileOutputStream(target);
2110 outputStream.write(uri.getData());
2111 final DownloadManager manager =
2112 (DownloadManager) mActivity.getSystemService(Context.DOWNLOAD_SERVICE);
2113 manager.addCompletedDownload(target.getName(),
2114 mActivity.getTitle().toString(), false,
2115 uri.getMimeType(), target.getAbsolutePath(),
George Mount7501bf42011-11-17 11:17:03 -08002116 (long)uri.getData().length, true);
George Mount387d45d2011-10-07 15:57:53 -07002117 } catch (IOException e) {
2118 Log.e(LOGTAG, "Could not save data URL");
2119 } finally {
2120 if (outputStream != null) {
2121 try {
2122 outputStream.close();
2123 } catch (IOException e) {
2124 // ignore close errors
2125 }
2126 }
2127 }
2128 }
2129
2130 /**
2131 * Creates a File based on the current time stamp and uses
2132 * the mime type of the DataUri to get the extension.
2133 */
2134 private File getTarget(DataUri uri) throws IOException {
2135 File dir = mActivity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
2136 DateFormat format = new SimpleDateFormat(IMAGE_BASE_FORMAT);
2137 String nameBase = format.format(new Date());
2138 String mimeType = uri.getMimeType();
2139 MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
2140 String extension = mimeTypeMap.getExtensionFromMimeType(mimeType);
2141 if (extension == null) {
2142 Log.w(LOGTAG, "Unknown mime type in data URI" + mimeType);
2143 extension = FALLBACK_EXTENSION;
2144 }
2145 extension = "." + extension; // createTempFile needs the '.'
2146 File targetFile = File.createTempFile(nameBase, extension, dir);
2147 return targetFile;
2148 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002149 }
2150
Cary Clark8974d282010-11-22 10:46:05 -05002151 private static class SelectText implements OnMenuItemClickListener {
2152 private WebView mWebView;
2153
2154 public boolean onMenuItemClick(MenuItem item) {
2155 if (mWebView != null) {
2156 return mWebView.selectText();
2157 }
2158 return false;
2159 }
2160
2161 public SelectText(WebView webView) {
2162 mWebView = webView;
2163 }
2164
2165 }
2166
Michael Kolb8233fac2010-10-26 16:08:53 -07002167 /********************** TODO: UI stuff *****************************/
2168
2169 // these methods have been copied, they still need to be cleaned up
2170
2171 /****************** tabs ***************************************************/
2172
2173 // basic tab interactions:
2174
2175 // it is assumed that tabcontrol already knows about the tab
2176 protected void addTab(Tab tab) {
2177 mUi.addTab(tab);
2178 }
2179
2180 protected void removeTab(Tab tab) {
2181 mUi.removeTab(tab);
2182 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002183 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002184 }
2185
Michael Kolbf2055602011-04-09 17:20:03 -07002186 @Override
2187 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002188 // monkey protection against delayed start
2189 if (tab != null) {
2190 mTabControl.setCurrentTab(tab);
2191 // the tab is guaranteed to have a webview after setCurrentTab
2192 mUi.setActiveTab(tab);
2193 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002194 }
2195
John Reck8bcafc12011-08-29 16:43:02 -07002196 protected void closeEmptyTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002197 Tab current = mTabControl.getCurrentTab();
2198 if (current != null
2199 && current.getWebView().copyBackForwardList().getSize() == 0) {
John Reck8bcafc12011-08-29 16:43:02 -07002200 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002201 }
2202 }
2203
John Reck26b18322011-06-21 13:08:58 -07002204 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002205 // Dismiss the subwindow if applicable.
2206 dismissSubWindow(appTab);
2207 // Since we might kill the WebView, remove it from the
2208 // content view first.
2209 mUi.detachTab(appTab);
2210 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002211 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002212 // TODO: analyze why the remove and add are necessary
2213 mUi.attachTab(appTab);
2214 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002215 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002216 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002217 } else {
2218 // If the tab was the current tab, we have to attach
2219 // it to the view system again.
2220 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002221 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002222 }
2223 }
2224
2225 // Remove the sub window if it exists. Also called by TabControl when the
2226 // user clicks the 'X' to dismiss a sub window.
2227 public void dismissSubWindow(Tab tab) {
2228 removeSubWindow(tab);
2229 // dismiss the subwindow. This will destroy the WebView.
2230 tab.dismissSubWindow();
Michael Kolbe8c97572011-11-21 14:03:56 -08002231 WebView wv = getCurrentTopWebView();
2232 if (wv != null) {
2233 wv.requestFocus();
2234 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002235 }
2236
2237 @Override
2238 public void removeSubWindow(Tab t) {
2239 if (t.getSubWebView() != null) {
2240 mUi.removeSubWindow(t.getSubViewContainer());
2241 }
2242 }
2243
2244 @Override
2245 public void attachSubWindow(Tab tab) {
2246 if (tab.getSubWebView() != null) {
2247 mUi.attachSubWindow(tab.getSubViewContainer());
2248 getCurrentTopWebView().requestFocus();
2249 }
2250 }
2251
Mathew Inwood29721c22011-06-29 17:55:24 +01002252 private Tab showPreloadedTab(final UrlData urlData) {
2253 if (!urlData.isPreloaded()) {
2254 return null;
2255 }
2256 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2257 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2258 if (sbQuery != null) {
Mathew Inwood9ad1eac2011-09-15 11:29:50 +01002259 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002260 // Could not submit query. Fallback to regular tab creation
2261 tabControl.destroy();
2262 return null;
2263 }
2264 }
Michael Kolbff6a7482011-07-26 16:37:15 -07002265 // check tab count and make room for new tab
2266 if (!mTabControl.canCreateNewTab()) {
2267 Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
2268 if (leastUsed != null) {
2269 closeTab(leastUsed);
2270 }
2271 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002272 Tab t = tabControl.getTab();
Mathew Inwoode09305e2011-09-02 12:03:26 +01002273 t.refreshIdAfterPreload();
Mathew Inwood29721c22011-06-29 17:55:24 +01002274 mTabControl.addPreloadedTab(t);
2275 addTab(t);
2276 setActiveTab(t);
2277 return t;
2278 }
2279
Michael Kolb7bcafde2011-05-09 13:55:59 -07002280 // open a non inconito tab with the given url data
2281 // and set as active tab
2282 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002283 Tab tab = showPreloadedTab(urlData);
2284 if (tab == null) {
2285 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002286 if ((tab != null) && !urlData.isEmpty()) {
2287 loadUrlDataIn(tab, urlData);
2288 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002289 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002290 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002291 }
2292
Michael Kolb843510f2010-12-09 10:51:49 -08002293 @Override
2294 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002295 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002296 }
2297
Michael Kolb8233fac2010-10-26 16:08:53 -07002298 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002299 public Tab openIncognitoTab() {
2300 return openTab(INCOGNITO_URI, true, true, false);
2301 }
2302
2303 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002304 public Tab openTab(String url, boolean incognito, boolean setActive,
2305 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002306 return openTab(url, incognito, setActive, useCurrent, null);
2307 }
2308
2309 @Override
2310 public Tab openTab(String url, Tab parent, boolean setActive,
2311 boolean useCurrent) {
2312 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2313 setActive, useCurrent, parent);
2314 }
2315
2316 public Tab openTab(String url, boolean incognito, boolean setActive,
2317 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002318 Tab tab = createNewTab(incognito, setActive, useCurrent);
2319 if (tab != null) {
John Reck5949c662011-05-27 09:52:29 -07002320 if (parent != null && parent != tab) {
2321 parent.addChildTab(tab);
2322 }
Michael Kolb519d2282011-05-09 17:03:19 -07002323 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002324 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002325 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002326 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002327 return tab;
2328 }
2329
2330 // this method will attempt to create a new tab
2331 // incognito: private browsing tab
2332 // setActive: ste tab as current tab
2333 // useCurrent: if no new tab can be created, return current tab
2334 private Tab createNewTab(boolean incognito, boolean setActive,
2335 boolean useCurrent) {
2336 Tab tab = null;
2337 if (mTabControl.canCreateNewTab()) {
2338 tab = mTabControl.createNewTab(incognito);
2339 addTab(tab);
2340 if (setActive) {
2341 setActiveTab(tab);
2342 }
2343 } else {
2344 if (useCurrent) {
2345 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002346 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002347 } else {
2348 mUi.showMaxTabsWarning();
2349 }
2350 }
2351 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002352 }
2353
John Reck2bc80422011-06-30 15:11:49 -07002354 @Override
2355 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2356 SnapshotTab tab = null;
2357 if (mTabControl.canCreateNewTab()) {
2358 tab = mTabControl.createSnapshotTab(snapshotId);
2359 addTab(tab);
2360 if (setActive) {
2361 setActiveTab(tab);
2362 }
2363 } else {
2364 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07002365 }
2366 return tab;
2367 }
2368
Michael Kolb8233fac2010-10-26 16:08:53 -07002369 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002370 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002371 * @return boolean True if we successfully switched to a different tab. If
2372 * the indexth tab is null, or if that tab is the same as
2373 * the current one, return false.
2374 */
2375 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002376 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002377 Tab currentTab = mTabControl.getCurrentTab();
2378 if (tab == null || tab == currentTab) {
2379 return false;
2380 }
2381 setActiveTab(tab);
2382 return true;
2383 }
2384
2385 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002386 public void closeCurrentTab() {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002387 closeCurrentTab(false);
2388 }
2389
2390 protected void closeCurrentTab(boolean andQuit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002391 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07002392 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07002393 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08002394 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002395 return;
2396 }
Michael Kolbc831b632011-05-11 09:30:34 -07002397 final Tab current = mTabControl.getCurrentTab();
2398 final int pos = mTabControl.getCurrentPosition();
2399 Tab newTab = current.getParent();
2400 if (newTab == null) {
2401 newTab = mTabControl.getTab(pos + 1);
2402 if (newTab == null) {
2403 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002404 }
2405 }
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002406 if (andQuit) {
2407 mTabControl.setCurrentTab(newTab);
2408 closeTab(current);
2409 } else if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002410 // Close window
2411 closeTab(current);
2412 }
2413 }
2414
2415 /**
2416 * Close the tab, remove its associated title bar, and adjust mTabControl's
2417 * current tab to a valid value.
2418 */
2419 @Override
2420 public void closeTab(Tab tab) {
John Reck28263772011-10-11 17:13:42 -07002421 if (tab == mTabControl.getCurrentTab()) {
2422 closeCurrentTab();
2423 } else {
2424 removeTab(tab);
2425 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002426 }
2427
Michael Kolb8233fac2010-10-26 16:08:53 -07002428 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07002429 protected void loadUrlFromContext(String url) {
2430 Tab tab = getCurrentTab();
2431 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002432 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07002433 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002434 url = UrlUtils.smartUrlFilter(url);
2435 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07002436 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07002437 }
2438 }
2439 }
2440
2441 /**
2442 * Load the URL into the given WebView and update the title bar
2443 * to reflect the new load. Call this instead of WebView.loadUrl
2444 * directly.
2445 * @param view The WebView used to load url.
2446 * @param url The URL to load.
2447 */
John Reck71e51422011-07-01 16:49:28 -07002448 @Override
2449 public void loadUrl(Tab tab, String url) {
John Reck26b18322011-06-21 13:08:58 -07002450 loadUrl(tab, url, null);
2451 }
2452
2453 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
2454 if (tab != null) {
2455 dismissSubWindow(tab);
2456 tab.loadUrl(url, headers);
Michael Kolba53c9892011-10-05 13:31:40 -07002457 mUi.onProgressChanged(tab);
John Reck26b18322011-06-21 13:08:58 -07002458 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002459 }
2460
2461 /**
2462 * Load UrlData into a Tab and update the title bar to reflect the new
2463 * load. Call this instead of UrlData.loadIn directly.
2464 * @param t The Tab used to load.
2465 * @param data The UrlData being loaded.
2466 */
2467 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07002468 if (data != null) {
2469 if (data.mVoiceIntent != null) {
2470 t.activateVoiceSearchMode(data.mVoiceIntent);
Michael Kolb14612442011-06-24 13:06:29 -07002471 } else if (data.isPreloaded()) {
2472 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07002473 } else {
2474 loadUrl(t, data.mUrl, data.mHeaders);
2475 }
2476 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002477 }
2478
John Reck30c714c2010-12-16 17:30:34 -08002479 @Override
2480 public void onUserCanceledSsl(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08002481 // TODO: Figure out the "right" behavior
John Reckef654f12011-07-12 16:42:08 -07002482 if (tab.canGoBack()) {
2483 tab.goBack();
John Reck30c714c2010-12-16 17:30:34 -08002484 } else {
John Reckef654f12011-07-12 16:42:08 -07002485 tab.loadUrl(mSettings.getHomePage(), null);
John Reck30c714c2010-12-16 17:30:34 -08002486 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002487 }
2488
2489 void goBackOnePageOrQuit() {
2490 Tab current = mTabControl.getCurrentTab();
2491 if (current == null) {
2492 /*
2493 * Instead of finishing the activity, simply push this to the back
2494 * of the stack and let ActivityManager to choose the foreground
2495 * activity. As BrowserActivity is singleTask, it will be always the
2496 * root of the task. So we can use either true or false for
2497 * moveTaskToBack().
2498 */
2499 mActivity.moveTaskToBack(true);
2500 return;
2501 }
John Reckef654f12011-07-12 16:42:08 -07002502 if (current.canGoBack()) {
2503 current.goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07002504 } else {
2505 // Check to see if we are closing a window that was created by
2506 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002507 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002508 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002509 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002510 // Now we close the other tab
2511 closeTab(current);
2512 } else {
Michael Kolbe28b3472011-08-04 16:54:31 -07002513 if ((current.getAppId() != null) || current.closeOnBack()) {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002514 closeCurrentTab(true);
Michael Kolbe28b3472011-08-04 16:54:31 -07002515 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002516 /*
2517 * Instead of finishing the activity, simply push this to the back
2518 * of the stack and let ActivityManager to choose the foreground
2519 * activity. As BrowserActivity is singleTask, it will be always the
2520 * root of the task. So we can use either true or false for
2521 * moveTaskToBack().
2522 */
2523 mActivity.moveTaskToBack(true);
2524 }
2525 }
2526 }
2527
2528 /**
2529 * Feed the previously stored results strings to the BrowserProvider so that
2530 * the SearchDialog will show them instead of the standard searches.
2531 * @param result String to show on the editable line of the SearchDialog.
2532 */
2533 @Override
2534 public void showVoiceSearchResults(String result) {
2535 ContentProviderClient client = mActivity.getContentResolver()
2536 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2537 ContentProvider prov = client.getLocalContentProvider();
2538 BrowserProvider bp = (BrowserProvider) prov;
2539 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2540 client.release();
2541
2542 Bundle bundle = createGoogleSearchSourceBundle(
2543 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2544 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2545 startSearch(result, false, bundle, false);
2546 }
2547
2548 private void startSearch(String initialQuery, boolean selectInitialQuery,
2549 Bundle appSearchData, boolean globalSearch) {
2550 if (appSearchData == null) {
2551 appSearchData = createGoogleSearchSourceBundle(
2552 GOOGLE_SEARCH_SOURCE_TYPE);
2553 }
2554
2555 SearchEngine searchEngine = mSettings.getSearchEngine();
2556 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2557 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2558 }
2559 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2560 globalSearch);
2561 }
2562
2563 private Bundle createGoogleSearchSourceBundle(String source) {
2564 Bundle bundle = new Bundle();
2565 bundle.putString(Search.SOURCE, source);
2566 return bundle;
2567 }
2568
2569 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002570 * helper method for key handler
2571 * returns the current tab if it can't advance
2572 */
Michael Kolbc831b632011-05-11 09:30:34 -07002573 private Tab getNextTab() {
Michael Kolbf5261da2011-12-15 15:07:35 -08002574 int pos = mTabControl.getCurrentPosition() + 1;
2575 if (pos >= mTabControl.getTabCount()) {
2576 pos = 0;
2577 }
2578 return mTabControl.getTab(pos);
Michael Kolb0035fad2011-03-14 13:25:28 -07002579 }
2580
2581 /**
2582 * helper method for key handler
2583 * returns the current tab if it can't advance
2584 */
Michael Kolbc831b632011-05-11 09:30:34 -07002585 private Tab getPrevTab() {
Michael Kolbf5261da2011-12-15 15:07:35 -08002586 int pos = mTabControl.getCurrentPosition() - 1;
2587 if ( pos < 0) {
2588 pos = mTabControl.getTabCount() - 1;
2589 }
2590 return mTabControl.getTab(pos);
Michael Kolb0035fad2011-03-14 13:25:28 -07002591 }
2592
2593 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002594 * handle key events in browser
2595 *
2596 * @param keyCode
2597 * @param event
2598 * @return true if handled, false to pass to super
2599 */
2600 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002601 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002602 // Even if MENU is already held down, we need to call to super to open
2603 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002604 if (!noModifiers
2605 && ((KeyEvent.KEYCODE_MENU == keyCode)
2606 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2607 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002608 mMenuIsDown = true;
2609 return false;
2610 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002611
Cary Clark8ff8c662010-12-29 15:03:05 -05002612 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07002613 Tab tab = getCurrentTab();
2614 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05002615
Cary Clark160bbb92011-01-10 11:17:07 -05002616 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2617 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002618
Michael Kolb8233fac2010-10-26 16:08:53 -07002619 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002620 case KeyEvent.KEYCODE_TAB:
2621 if (event.isCtrlPressed()) {
2622 if (event.isShiftPressed()) {
2623 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002624 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002625 } else {
2626 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002627 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002628 }
2629 return true;
2630 }
2631 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002632 case KeyEvent.KEYCODE_SPACE:
2633 // WebView/WebTextView handle the keys in the KeyDown. As
2634 // the Activity's shortcut keys are only handled when WebView
2635 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002636 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002637 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002638 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002639 pageDown();
2640 }
2641 return true;
2642 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002643 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002644 event.startTracking();
2645 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07002646 case KeyEvent.KEYCODE_FORWARD:
2647 if (!noModifiers) break;
2648 tab.goForward();
2649 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002650 case KeyEvent.KEYCODE_DPAD_LEFT:
2651 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002652 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05002653 return true;
2654 }
2655 break;
2656 case KeyEvent.KEYCODE_DPAD_RIGHT:
2657 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002658 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05002659 return true;
2660 }
2661 break;
2662 case KeyEvent.KEYCODE_A:
2663 if (ctrl) {
2664 webView.selectAll();
2665 return true;
2666 }
2667 break;
Michael Kolba4183062011-01-16 10:43:21 -08002668// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002669 case KeyEvent.KEYCODE_C:
2670 if (ctrl) {
2671 webView.copySelection();
2672 return true;
2673 }
2674 break;
Michael Kolba4183062011-01-16 10:43:21 -08002675// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002676// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002677// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002678// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002679// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002680// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002681// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002682// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002683// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002684// case KeyEvent.KEYCODE_M: // unused
2685// case KeyEvent.KEYCODE_N: // in Chrome: new window
2686// case KeyEvent.KEYCODE_O: // in Chrome: open file
2687// case KeyEvent.KEYCODE_P: // in Chrome: print page
2688// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002689// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002690// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2691 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002692 // we can't use the ctrl/shift flags, they check for
2693 // exclusive use of a modifier
2694 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002695 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002696 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002697 } else {
2698 openTabToHomePage();
2699 }
2700 return true;
2701 }
2702 break;
2703// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2704// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb5ae15bd2011-08-16 17:09:27 -07002705// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002706// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2707// case KeyEvent.KEYCODE_Y: // unused
2708// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002709 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002710 // it is a regular key and webview is not null
2711 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002712 }
2713
John Recke6bf4ab2011-02-24 15:48:05 -08002714 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2715 switch(keyCode) {
2716 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07002717 if (mUi.isWebShowing()) {
Michael Kolb315d5022011-10-13 12:47:11 -07002718 bookmarksOrHistoryPicker(ComboViews.History);
John Recke6bf4ab2011-02-24 15:48:05 -08002719 return true;
2720 }
2721 break;
2722 }
2723 return false;
2724 }
2725
Michael Kolb8233fac2010-10-26 16:08:53 -07002726 boolean onKeyUp(int keyCode, KeyEvent event) {
Michael Kolb2814a362011-05-19 15:49:41 -07002727 if (KeyEvent.KEYCODE_MENU == keyCode) {
2728 mMenuIsDown = false;
2729 if (event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002730 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002731 }
2732 }
Cary Clark160bbb92011-01-10 11:17:07 -05002733 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002734 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002735 case KeyEvent.KEYCODE_BACK:
2736 if (event.isTracking() && !event.isCanceled()) {
2737 onBackKey();
2738 return true;
2739 }
2740 break;
2741 }
2742 return false;
2743 }
2744
2745 public boolean isMenuDown() {
2746 return mMenuIsDown;
2747 }
2748
Ben Murdoch8029a772010-11-16 11:58:21 +00002749 public void setupAutoFill(Message message) {
2750 // Open the settings activity at the AutoFill profile fragment so that
2751 // the user can create a new profile. When they return, we will dispatch
2752 // the message so that we can autofill the form using their new profile.
2753 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2754 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2755 AutoFillSettingsFragment.class.getName());
2756 mAutoFillSetupMessage = message;
2757 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2758 }
John Reckb3417f02011-01-14 11:01:05 -08002759
Michael Kolbfbc579a2011-07-07 15:59:33 -07002760 public boolean onSearchRequested() {
2761 mUi.editUrl(false);
2762 return true;
2763 }
2764
John Reck1cf4b792011-07-26 10:22:22 -07002765 @Override
2766 public boolean shouldCaptureThumbnails() {
2767 return mUi.shouldCaptureThumbnails();
2768 }
2769
Michael Kolbc3af0672011-08-09 10:24:41 -07002770 @Override
2771 public void setBlockEvents(boolean block) {
2772 mBlockEvents = block;
2773 }
2774
2775 public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002776 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002777 }
2778
2779 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002780 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002781 }
2782
2783 public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002784 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002785 }
2786
2787 public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002788 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002789 }
2790
2791 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002792 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002793 }
2794
Michael Kolb8233fac2010-10-26 16:08:53 -07002795}