blob: 923dfed09d0f4c5056ef9c19f4703d62da9524f5 [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;
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +000079import android.webkit.WebViewClassic;
Leon Scrogginsac993842011-02-02 12:54:07 -050080import android.widget.Toast;
Michael Kolb8233fac2010-10-26 16:08:53 -070081
Michael Kolb4bd767d2011-05-27 11:33:55 -070082import com.android.browser.IntentHandler.UrlData;
John Reck2bc80422011-06-30 15:11:49 -070083import com.android.browser.UI.ComboViews;
Michael Kolb4bd767d2011-05-27 11:33:55 -070084import com.android.browser.provider.BrowserProvider;
John Reck1cf4b792011-07-26 10:22:22 -070085import com.android.browser.provider.BrowserProvider2.Thumbnails;
John Reck8cc92352011-07-06 17:41:52 -070086import com.android.browser.provider.SnapshotProvider.Snapshots;
Michael Kolb4bd767d2011-05-27 11:33:55 -070087import com.android.browser.search.SearchEngine;
88import com.android.common.Search;
89
Michael Kolb8233fac2010-10-26 16:08:53 -070090import java.io.ByteArrayOutputStream;
George Mount387d45d2011-10-07 15:57:53 -070091import java.io.File;
92import java.io.FileOutputStream;
93import java.io.IOException;
Michael Kolb8233fac2010-10-26 16:08:53 -070094import java.net.URLEncoder;
George Mount387d45d2011-10-07 15:57:53 -070095import java.text.DateFormat;
96import java.text.SimpleDateFormat;
John Reck1cf4b792011-07-26 10:22:22 -070097import java.util.ArrayList;
Michael Kolb8233fac2010-10-26 16:08:53 -070098import java.util.Calendar;
George Mount387d45d2011-10-07 15:57:53 -070099import java.util.Date;
Michael Kolb8233fac2010-10-26 16:08:53 -0700100import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -0800101import java.util.List;
John Reck26b18322011-06-21 13:08:58 -0700102import java.util.Map;
Michael Kolb8233fac2010-10-26 16:08:53 -0700103
104/**
105 * Controller for browser
106 */
107public class Controller
108 implements WebViewController, UiController {
109
110 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800111 private static final String SEND_APP_ID_EXTRA =
112 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
Michael Kolba4261fd2011-05-05 11:27:37 -0700113 private static final String INCOGNITO_URI = "browser:incognito";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800114
Michael Kolb8233fac2010-10-26 16:08:53 -0700115
116 // public message ids
117 public final static int LOAD_URL = 1001;
118 public final static int STOP_LOAD = 1002;
119
120 // Message Ids
121 private static final int FOCUS_NODE_HREF = 102;
122 private static final int RELEASE_WAKELOCK = 107;
123
124 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
125
126 private static final int OPEN_BOOKMARKS = 201;
127
128 private static final int EMPTY_MENU = -1;
129
Michael Kolb8233fac2010-10-26 16:08:53 -0700130 // activity requestCode
John Reckd3e4d5b2011-07-13 15:48:43 -0700131 final static int COMBO_VIEW = 1;
Michael Kolb8233fac2010-10-26 16:08:53 -0700132 final static int PREFERENCES_PAGE = 3;
133 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000134 final static int AUTOFILL_SETUP = 5;
135
Michael Kolb8233fac2010-10-26 16:08:53 -0700136 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
137
138 // As the ids are dynamically created, we can't guarantee that they will
139 // be in sequence, so this static array maps ids to a window number.
140 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
141 { R.id.window_one_menu_id, R.id.window_two_menu_id,
142 R.id.window_three_menu_id, R.id.window_four_menu_id,
143 R.id.window_five_menu_id, R.id.window_six_menu_id,
144 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
145
146 // "source" parameter for Google search through search key
147 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
148 // "source" parameter for Google search through simplily type
149 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
150
George Mount387d45d2011-10-07 15:57:53 -0700151 // "no-crash-recovery" parameter in intent to suppress crash recovery
Guang Zhu9e78f512011-05-04 11:45:11 -0700152 final static String NO_CRASH_RECOVERY = "no-crash-recovery";
153
John Reckd7dd9b22011-08-30 09:18:29 -0700154 // A bitmap that is re-used in createScreenshot as scratch space
155 private static Bitmap sThumbnailBitmap;
156
Michael Kolb8233fac2010-10-26 16:08:53 -0700157 private Activity mActivity;
158 private UI mUi;
159 private TabControl mTabControl;
160 private BrowserSettings mSettings;
161 private WebViewFactory mFactory;
162
163 private WakeLock mWakeLock;
164
165 private UrlHandler mUrlHandler;
166 private UploadHandler mUploadHandler;
167 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700168 private PageDialogsHandler mPageDialogsHandler;
169 private NetworkStateHandler mNetworkHandler;
170
Ben Murdoch8029a772010-11-16 11:58:21 +0000171 private Message mAutoFillSetupMessage;
172
Michael Kolb8233fac2010-10-26 16:08:53 -0700173 private boolean mShouldShowErrorConsole;
174
175 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
176
177 // FIXME, temp address onPrepareMenu performance problem.
178 // When we move everything out of view, we should rewrite this.
179 private int mCurrentMenuState = 0;
180 private int mMenuState = R.id.MAIN_MENU;
181 private int mOldMenuState = EMPTY_MENU;
182 private Menu mCachedMenu;
183
Michael Kolb8233fac2010-10-26 16:08:53 -0700184 private boolean mMenuIsDown;
185
186 // For select and find, we keep track of the ActionMode so that
187 // finish() can be called as desired.
188 private ActionMode mActionMode;
189
190 /**
191 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
192 * of whether the configuration has changed. The first onMenuOpened call
193 * after a configuration change is simply a reopening of the same menu
194 * (i.e. mIconView did not change).
195 */
196 private boolean mConfigChanged;
197
198 /**
199 * Keeps track of whether the options menu is open. This is important in
200 * determining whether to show or hide the title bar overlay
201 */
202 private boolean mOptionsMenuOpen;
203
204 /**
205 * Whether or not the options menu is in its bigger, popup menu form. When
206 * true, we want the title bar overlay to be gone. When false, we do not.
207 * Only meaningful if mOptionsMenuOpen is true.
208 */
209 private boolean mExtendedMenuOpen;
210
Michael Kolb8233fac2010-10-26 16:08:53 -0700211 private boolean mActivityPaused = true;
212 private boolean mLoadStopped;
213
214 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500215 // Checks to see when the bookmarks database has changed, and updates the
216 // Tabs' notion of whether they represent bookmarked sites.
217 private ContentObserver mBookmarksObserver;
John Reck847b5322011-04-14 17:02:18 -0700218 private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700219
Michael Kolbc3af0672011-08-09 10:24:41 -0700220 private boolean mBlockEvents;
221
George Mount3636d0a2011-11-21 09:08:21 -0800222 public Controller(Activity browser) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700223 mActivity = browser;
224 mSettings = BrowserSettings.getInstance();
225 mTabControl = new TabControl(this);
226 mSettings.setController(this);
John Reck378a4102011-06-09 16:23:01 -0700227 mCrashRecoveryHandler = CrashRecoveryHandler.initialize(this);
George Mount3636d0a2011-11-21 09:08:21 -0800228 mCrashRecoveryHandler.preloadCrashState();
Michael Kolb14612442011-06-24 13:06:29 -0700229 mFactory = new BrowserWebViewFactory(browser);
Michael Kolb8233fac2010-10-26 16:08:53 -0700230
231 mUrlHandler = new UrlHandler(this);
232 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700233 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
234
Michael Kolb8233fac2010-10-26 16:08:53 -0700235 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500236 mBookmarksObserver = new ContentObserver(mHandler) {
237 @Override
238 public void onChange(boolean selfChange) {
239 int size = mTabControl.getTabCount();
240 for (int i = 0; i < size; i++) {
241 mTabControl.getTab(i).updateBookmarkedStatus();
242 }
243 }
244
245 };
246 browser.getContentResolver().registerContentObserver(
247 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700248
249 mNetworkHandler = new NetworkStateHandler(mActivity, this);
250 // Start watching the default geolocation permissions
251 mSystemAllowGeolocationOrigins =
252 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
253 mSystemAllowGeolocationOrigins.start();
254
John Reckaf262e72011-07-25 13:55:44 -0700255 openIconDatabase();
Michael Kolb8233fac2010-10-26 16:08:53 -0700256 }
257
George Mount3636d0a2011-11-21 09:08:21 -0800258 void start(final Intent intent) {
259 // mCrashRecoverHandler has any previously saved state.
260 mCrashRecoveryHandler.startRecovery(intent);
John Reck847b5322011-04-14 17:02:18 -0700261 }
262
George Mount3636d0a2011-11-21 09:08:21 -0800263 void doStart(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700264 // Unless the last browser usage was within 24 hours, destroy any
265 // remaining incognito tabs.
266
267 Calendar lastActiveDate = icicle != null ?
268 (Calendar) icicle.getSerializable("lastActiveDate") : null;
269 Calendar today = Calendar.getInstance();
270 Calendar yesterday = Calendar.getInstance();
271 yesterday.add(Calendar.DATE, -1);
272
Patrick Scott7d50a932011-02-04 09:27:26 -0500273 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700274 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800275 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700276
Patrick Scott7d50a932011-02-04 09:27:26 -0500277 // Find out if we will restore any state and remember the tab.
Michael Kolbc831b632011-05-11 09:30:34 -0700278 final long currentTabId =
Patrick Scott7d50a932011-02-04 09:27:26 -0500279 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000280
Michael Kolbc831b632011-05-11 09:30:34 -0700281 if (currentTabId == -1) {
Patrick Scott7d50a932011-02-04 09:27:26 -0500282 // Not able to restore so we go ahead and clear session cookies. We
283 // must do this before trying to login the user as we don't want to
284 // clear any session cookies set during login.
285 CookieManager.getInstance().removeSessionCookie();
286 }
287
Patrick Scottd43e75a2011-03-14 14:47:23 -0400288 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500289 new Runnable() {
290 @Override public void run() {
George Mount3636d0a2011-11-21 09:08:21 -0800291 onPreloginFinished(icicle, intent, currentTabId,
292 restoreIncognitoTabs);
Patrick Scott7d50a932011-02-04 09:27:26 -0500293 }
294 });
295 }
296
Michael Kolbc831b632011-05-11 09:30:34 -0700297 private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId,
George Mount3636d0a2011-11-21 09:08:21 -0800298 boolean restoreIncognitoTabs) {
Michael Kolbc831b632011-05-11 09:30:34 -0700299 if (currentTabId == -1) {
John Reck1cf4b792011-07-26 10:22:22 -0700300 BackgroundHandler.execute(new PruneThumbnails(mActivity, null));
George Mount3636d0a2011-11-21 09:08:21 -0800301 if (intent == null) {
302 // This won't happen under common scenarios. The icicle is
303 // not null, but there aren't any tabs to restore.
304 openTabToHomePage();
Michael Kolb7bcafde2011-05-09 13:55:59 -0700305 } else {
George Mount3636d0a2011-11-21 09:08:21 -0800306 final Bundle extra = intent.getExtras();
307 // Create an initial tab.
308 // If the intent is ACTION_VIEW and data is not null, the Browser is
309 // invoked to view the content by another application. In this case,
310 // the tab will be close when exit.
311 UrlData urlData = IntentHandler.getUrlDataFromIntent(intent);
312 Tab t = null;
313 if (urlData.isEmpty()) {
314 t = openTabToHomePage();
315 } else {
316 t = openTab(urlData);
317 }
318 if (t != null) {
319 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
320 }
321 WebView webView = t.getWebView();
322 if (extra != null) {
323 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
324 if (scale > 0 && scale <= 1000) {
325 webView.setInitialScale(scale);
326 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700327 }
328 }
John Reckd8c74522011-06-14 08:45:00 -0700329 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700330 } else {
Michael Kolbc831b632011-05-11 09:30:34 -0700331 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
Patrick Scott7d50a932011-02-04 09:27:26 -0500332 mUi.needsRestoreAllTabs());
John Reck1cf4b792011-07-26 10:22:22 -0700333 List<Tab> tabs = mTabControl.getTabs();
334 ArrayList<Long> restoredTabs = new ArrayList<Long>(tabs.size());
335 for (Tab t : tabs) {
336 restoredTabs.add(t.getId());
337 }
338 BackgroundHandler.execute(new PruneThumbnails(mActivity, restoredTabs));
John Reck52be4782011-08-26 15:37:29 -0700339 if (tabs.size() == 0) {
340 openTabToHomePage();
341 }
John Reck1cf4b792011-07-26 10:22:22 -0700342 mUi.updateTabs(tabs);
Michael Kolb8233fac2010-10-26 16:08:53 -0700343 // TabControl.restoreState() will create a new tab even if
344 // restoring the state fails.
345 setActiveTab(mTabControl.getCurrentTab());
George Mount3636d0a2011-11-21 09:08:21 -0800346 // Intent is non-null when framework thinks the browser should be
347 // launching with a new intent (icicle is null).
348 if (intent != null) {
John Reck9dd4a412011-10-05 14:55:30 -0700349 mIntentHandler.onNewIntent(intent);
350 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700351 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700352 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700353 String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb8233fac2010-10-26 16:08:53 -0700354 if (jsFlags.trim().length() != 0) {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +0000355 WebViewClassic.fromWebView(getCurrentWebView()).setJsFlags(jsFlags);
Michael Kolb8233fac2010-10-26 16:08:53 -0700356 }
George Mount3636d0a2011-11-21 09:08:21 -0800357 if (intent != null
358 && BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
Michael Kolb315d5022011-10-13 12:47:11 -0700359 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
John Reck439c9a52010-12-14 10:04:39 -0800360 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700361 }
362
John Reck1cf4b792011-07-26 10:22:22 -0700363 private static class PruneThumbnails implements Runnable {
364 private Context mContext;
365 private List<Long> mIds;
366
367 PruneThumbnails(Context context, List<Long> preserveIds) {
368 mContext = context.getApplicationContext();
369 mIds = preserveIds;
370 }
371
372 @Override
373 public void run() {
374 ContentResolver cr = mContext.getContentResolver();
375 if (mIds == null || mIds.size() == 0) {
376 cr.delete(Thumbnails.CONTENT_URI, null, null);
377 } else {
378 int length = mIds.size();
379 StringBuilder where = new StringBuilder();
380 where.append(Thumbnails._ID);
381 where.append(" not in (");
382 for (int i = 0; i < length; i++) {
383 where.append(mIds.get(i));
384 if (i < (length - 1)) {
385 where.append(",");
386 }
387 }
388 where.append(")");
389 cr.delete(Thumbnails.CONTENT_URI, where.toString(), null);
390 }
391 }
392
393 }
394
Michael Kolb1514bb72010-11-22 09:11:48 -0800395 @Override
396 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700397 return mFactory;
398 }
399
400 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800401 public void onSetWebView(Tab tab, WebView view) {
402 mUi.onSetWebView(tab, view);
403 }
404
405 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800406 public void createSubWindow(Tab tab) {
407 endActionMode();
408 WebView mainView = tab.getWebView();
409 WebView subView = mFactory.createWebView((mainView == null)
410 ? false
411 : mainView.isPrivateBrowsingEnabled());
412 mUi.createSubWindow(tab, subView);
413 }
414
415 @Override
Michael Kolb14612442011-06-24 13:06:29 -0700416 public Context getContext() {
417 return mActivity;
418 }
419
420 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700421 public Activity getActivity() {
422 return mActivity;
423 }
424
425 void setUi(UI ui) {
426 mUi = ui;
427 }
428
429 BrowserSettings getSettings() {
430 return mSettings;
431 }
432
433 IntentHandler getIntentHandler() {
434 return mIntentHandler;
435 }
436
437 @Override
438 public UI getUi() {
439 return mUi;
440 }
441
442 int getMaxTabs() {
443 return mActivity.getResources().getInteger(R.integer.max_tabs);
444 }
445
446 @Override
447 public TabControl getTabControl() {
448 return mTabControl;
449 }
450
Michael Kolb1bf23132010-11-19 12:55:12 -0800451 @Override
452 public List<Tab> getTabs() {
453 return mTabControl.getTabs();
454 }
455
John Reckaf262e72011-07-25 13:55:44 -0700456 // Open the icon database.
457 private void openIconDatabase() {
458 // We have to call getInstance on the UI thread
459 final WebIconDatabase instance = WebIconDatabase.getInstance();
460 BackgroundHandler.execute(new Runnable() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000461
John Reckaf262e72011-07-25 13:55:44 -0700462 @Override
463 public void run() {
464 instance.open(mActivity.getDir("icons", 0).getPath());
Michael Kolb8233fac2010-10-26 16:08:53 -0700465 }
John Reckaf262e72011-07-25 13:55:44 -0700466 });
Michael Kolb8233fac2010-10-26 16:08:53 -0700467 }
468
469 private void startHandler() {
470 mHandler = new Handler() {
471
472 @Override
473 public void handleMessage(Message msg) {
474 switch (msg.what) {
475 case OPEN_BOOKMARKS:
Michael Kolb315d5022011-10-13 12:47:11 -0700476 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
Michael Kolb8233fac2010-10-26 16:08:53 -0700477 break;
478 case FOCUS_NODE_HREF:
479 {
480 String url = (String) msg.getData().get("url");
481 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500482 String src = (String) msg.getData().get("src");
483 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700484 if (TextUtils.isEmpty(url)) {
485 break;
486 }
487 HashMap focusNodeMap = (HashMap) msg.obj;
488 WebView view = (WebView) focusNodeMap.get("webview");
489 // Only apply the action if the top window did not change.
490 if (getCurrentTopWebView() != view) {
491 break;
492 }
493 switch (msg.arg1) {
494 case R.id.open_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700495 loadUrlFromContext(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700496 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500497 case R.id.view_image_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700498 loadUrlFromContext(src);
Cary Clark043c2d62010-12-15 11:19:39 -0500499 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500500 case R.id.open_newtab_context_menu_id:
501 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -0700502 openTab(url, parent,
503 !mSettings.openInBackground(), true);
Leon Scroggins026f2542010-11-22 13:26:12 -0500504 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700505 case R.id.copy_link_context_menu_id:
506 copy(url);
507 break;
508 case R.id.save_link_context_menu_id:
509 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500510 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000511 mActivity, url, null, null, null,
512 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700513 break;
514 }
515 break;
516 }
517
518 case LOAD_URL:
John Reck26b18322011-06-21 13:08:58 -0700519 loadUrlFromContext((String) msg.obj);
Michael Kolb8233fac2010-10-26 16:08:53 -0700520 break;
521
522 case STOP_LOAD:
523 stopLoading();
524 break;
525
526 case RELEASE_WAKELOCK:
John Reckf57c0292011-07-21 18:15:39 -0700527 if (mWakeLock != null && mWakeLock.isHeld()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700528 mWakeLock.release();
529 // if we reach here, Browser should be still in the
530 // background loading after WAKELOCK_TIMEOUT (5-min).
531 // To avoid burning the battery, stop loading.
532 mTabControl.stopAllLoading();
533 }
534 break;
535
536 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800537 Tab tab = (Tab) msg.obj;
538 if (tab != null) {
539 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700540 }
541 break;
542 }
543 }
544 };
545
546 }
547
John Reckef654f12011-07-12 16:42:08 -0700548 @Override
Martijn Coenenb2f93552011-06-14 10:48:35 +0200549 public Tab getCurrentTab() {
550 return mTabControl.getCurrentTab();
551 }
552
Michael Kolbba99c5d2010-11-29 14:57:41 -0800553 @Override
554 public void shareCurrentPage() {
555 shareCurrentPage(mTabControl.getCurrentTab());
556 }
557
558 private void shareCurrentPage(Tab tab) {
559 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800560 sharePage(mActivity, tab.getTitle(),
561 tab.getUrl(), tab.getFavicon(),
562 createScreenshot(tab.getWebView(),
563 getDesiredThumbnailWidth(mActivity),
564 getDesiredThumbnailHeight(mActivity)));
565 }
566 }
567
Michael Kolb8233fac2010-10-26 16:08:53 -0700568 /**
569 * Share a page, providing the title, url, favicon, and a screenshot. Uses
570 * an {@link Intent} to launch the Activity chooser.
571 * @param c Context used to launch a new Activity.
572 * @param title Title of the page. Stored in the Intent with
573 * {@link Intent#EXTRA_SUBJECT}
574 * @param url URL of the page. Stored in the Intent with
575 * {@link Intent#EXTRA_TEXT}
576 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
577 * with {@link Browser#EXTRA_SHARE_FAVICON}
578 * @param screenshot Bitmap of a screenshot of the page. Stored in the
579 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
580 */
581 static final void sharePage(Context c, String title, String url,
582 Bitmap favicon, Bitmap screenshot) {
583 Intent send = new Intent(Intent.ACTION_SEND);
584 send.setType("text/plain");
585 send.putExtra(Intent.EXTRA_TEXT, url);
586 send.putExtra(Intent.EXTRA_SUBJECT, title);
587 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
588 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
589 try {
590 c.startActivity(Intent.createChooser(send, c.getString(
591 R.string.choosertitle_sharevia)));
592 } catch(android.content.ActivityNotFoundException ex) {
593 // if no app handles it, do nothing
594 }
595 }
596
597 private void copy(CharSequence text) {
598 ClipboardManager cm = (ClipboardManager) mActivity
599 .getSystemService(Context.CLIPBOARD_SERVICE);
600 cm.setText(text);
601 }
602
603 // lifecycle
604
605 protected void onConfgurationChanged(Configuration config) {
606 mConfigChanged = true;
607 if (mPageDialogsHandler != null) {
608 mPageDialogsHandler.onConfigurationChanged(config);
609 }
610 mUi.onConfigurationChanged(config);
611 }
612
613 @Override
614 public void handleNewIntent(Intent intent) {
Michael Kolb59e232c2011-08-18 17:19:53 -0700615 if (!mUi.isWebShowing()) {
616 mUi.showWeb(false);
617 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700618 mIntentHandler.onNewIntent(intent);
619 }
620
621 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800622 if (mUi.isCustomViewShowing()) {
623 hideCustomView();
624 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700625 if (mActivityPaused) {
626 Log.e(LOGTAG, "BrowserActivity is already paused.");
627 return;
628 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700629 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800630 Tab tab = mTabControl.getCurrentTab();
631 if (tab != null) {
632 tab.pause();
633 if (!pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700634 if (mWakeLock == null) {
635 PowerManager pm = (PowerManager) mActivity
636 .getSystemService(Context.POWER_SERVICE);
637 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
638 }
Michael Kolb70976932010-11-30 11:34:01 -0800639 mWakeLock.acquire();
640 mHandler.sendMessageDelayed(mHandler
641 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
642 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700643 }
644 mUi.onPause();
645 mNetworkHandler.onPause();
646
647 WebView.disablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100648 NfcHandler.unregister(mActivity);
John Reckd7dd9b22011-08-30 09:18:29 -0700649 if (sThumbnailBitmap != null) {
650 sThumbnailBitmap.recycle();
651 sThumbnailBitmap = null;
652 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700653 }
654
John Reck1cf4b792011-07-26 10:22:22 -0700655 void onSaveInstanceState(Bundle outState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700656 // Save all the tabs
George Mount3636d0a2011-11-21 09:08:21 -0800657 Bundle saveState = createSaveState();
658
659 // crash recovery manages all save & restore state
660 mCrashRecoveryHandler.writeState(saveState);
661 mSettings.setLastRunPaused(true);
662 }
663
664 /**
665 * Save the current state to outState. Does not write the state to
666 * disk.
667 * @return Bundle containing the current state of all tabs.
668 */
669 /* package */ Bundle createSaveState() {
670 Bundle saveState = new Bundle();
671 mTabControl.saveState(saveState);
672 if (!saveState.isEmpty()) {
John Reck24f18262011-06-17 14:47:20 -0700673 // Save time so that we know how old incognito tabs (if any) are.
George Mount3636d0a2011-11-21 09:08:21 -0800674 saveState.putSerializable("lastActiveDate", Calendar.getInstance());
John Reck24f18262011-06-17 14:47:20 -0700675 }
George Mount3636d0a2011-11-21 09:08:21 -0800676 return saveState;
Michael Kolb8233fac2010-10-26 16:08:53 -0700677 }
678
679 void onResume() {
680 if (!mActivityPaused) {
681 Log.e(LOGTAG, "BrowserActivity is already resumed.");
682 return;
683 }
George Mount3636d0a2011-11-21 09:08:21 -0800684 mSettings.setLastRunPaused(false);
Michael Kolb8233fac2010-10-26 16:08:53 -0700685 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800686 Tab current = mTabControl.getCurrentTab();
687 if (current != null) {
688 current.resume();
689 resumeWebViewTimers(current);
690 }
John Reckf57c0292011-07-21 18:15:39 -0700691 releaseWakeLock();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200692
Michael Kolb8233fac2010-10-26 16:08:53 -0700693 mUi.onResume();
694 mNetworkHandler.onResume();
695 WebView.enablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100696 NfcHandler.register(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700697 }
698
John Reckf57c0292011-07-21 18:15:39 -0700699 private void releaseWakeLock() {
700 if (mWakeLock != null && mWakeLock.isHeld()) {
701 mHandler.removeMessages(RELEASE_WAKELOCK);
702 mWakeLock.release();
703 }
704 }
705
Michael Kolb70976932010-11-30 11:34:01 -0800706 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800707 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800708 * @param tab guaranteed non-null
709 */
710 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700711 boolean inLoad = tab.inPageLoad();
712 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
713 CookieSyncManager.getInstance().startSync();
714 WebView w = tab.getWebView();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100715 WebViewTimersControl.getInstance().onBrowserActivityResume(w);
Michael Kolb8233fac2010-10-26 16:08:53 -0700716 }
717 }
718
Michael Kolb70976932010-11-30 11:34:01 -0800719 /**
720 * Pause all WebView timers using the WebView of the given tab
721 * @param tab
722 * @return true if the timers are paused or tab is null
723 */
724 private boolean pauseWebViewTimers(Tab tab) {
725 if (tab == null) {
726 return true;
727 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700728 CookieSyncManager.getInstance().stopSync();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100729 WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView());
Michael Kolb8233fac2010-10-26 16:08:53 -0700730 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700731 }
Michael Kolb70976932010-11-30 11:34:01 -0800732 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700733 }
734
735 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800736 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700737 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
738 mUploadHandler = null;
739 }
740 if (mTabControl == null) return;
741 mUi.onDestroy();
742 // Remove the current tab and sub window
743 Tab t = mTabControl.getCurrentTab();
744 if (t != null) {
745 dismissSubWindow(t);
746 removeTab(t);
747 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500748 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700749 // Destroy all the tabs
750 mTabControl.destroy();
751 WebIconDatabase.getInstance().close();
752 // Stop watching the default geolocation permissions
753 mSystemAllowGeolocationOrigins.stop();
754 mSystemAllowGeolocationOrigins = null;
755 }
756
757 protected boolean isActivityPaused() {
758 return mActivityPaused;
759 }
760
761 protected void onLowMemory() {
762 mTabControl.freeMemory();
763 }
764
765 @Override
766 public boolean shouldShowErrorConsole() {
767 return mShouldShowErrorConsole;
768 }
769
770 protected void setShouldShowErrorConsole(boolean show) {
771 if (show == mShouldShowErrorConsole) {
772 // Nothing to do.
773 return;
774 }
775 mShouldShowErrorConsole = show;
776 Tab t = mTabControl.getCurrentTab();
777 if (t == null) {
778 // There is no current tab so we cannot toggle the error console
779 return;
780 }
781 mUi.setShouldShowErrorConsole(t, show);
782 }
783
784 @Override
785 public void stopLoading() {
786 mLoadStopped = true;
787 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700788 WebView w = getCurrentTopWebView();
789 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700790 mUi.onPageStopped(tab);
791 }
792
793 boolean didUserStopLoading() {
794 return mLoadStopped;
795 }
796
797 // WebViewController
798
799 @Override
John Reck324d4402011-01-11 16:56:42 -0800800 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700801
802 // We've started to load a new page. If there was a pending message
803 // to save a screenshot then we will now take the new page and save
804 // an incorrect screenshot. Therefore, remove any pending thumbnail
805 // messages from the queue.
806 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800807 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700808
809 // reset sync timer to avoid sync starts during loading a page
810 CookieSyncManager.getInstance().resetSync();
811
812 if (!mNetworkHandler.isNetworkUp()) {
813 view.setNetworkAvailable(false);
814 }
815
816 // when BrowserActivity just starts, onPageStarted may be called before
817 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
818 // to start the timer. As we won't switch tabs while an activity is in
819 // pause state, we can ensure calling resume and pause in pair.
820 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800821 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700822 }
823 mLoadStopped = false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700824 endActionMode();
825
John Reck30c714c2010-12-16 17:30:34 -0800826 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700827
John Reck324d4402011-01-11 16:56:42 -0800828 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700829 // update the bookmark database for favicon
830 maybeUpdateFavicon(tab, null, url, favicon);
831
832 Performance.tracePageStart(url);
833
834 // Performance probe
835 if (false) {
836 Performance.onPageStarted();
837 }
838
839 }
840
841 @Override
John Reck324d4402011-01-11 16:56:42 -0800842 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800843 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700844 // pause the WebView timer and release the wake lock if it is finished
845 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800846 if (mActivityPaused && pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700847 releaseWakeLock();
Michael Kolb8233fac2010-10-26 16:08:53 -0700848 }
Martijn Coenenb2f93552011-06-14 10:48:35 +0200849
Michael Kolb8233fac2010-10-26 16:08:53 -0700850 // Performance probe
851 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800852 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700853 }
854
855 Performance.tracePageFinished();
856 }
857
858 @Override
John Reck30c714c2010-12-16 17:30:34 -0800859 public void onProgressChanged(Tab tab) {
John Reck6c2e2f32011-08-22 13:41:23 -0700860 mCrashRecoveryHandler.backupState();
John Reck30c714c2010-12-16 17:30:34 -0800861 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700862
863 if (newProgress == 100) {
864 CookieSyncManager.getInstance().sync();
865 // onProgressChanged() may continue to be called after the main
866 // frame has finished loading, as any remaining sub frames continue
867 // to load. We'll only get called once though with newProgress as
868 // 100 when everything is loaded. (onPageFinished is called once
869 // when the main frame completes loading regardless of the state of
870 // any sub frames so calls to onProgressChanges may continue after
871 // onPageFinished has executed)
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800872 if (tab.inPageLoad()) {
873 updateInLoadMenuItems(mCachedMenu, tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700874 }
John Reckd9862372012-02-21 15:04:50 -0800875 if (!tab.isPrivateBrowsingEnabled()
876 && !TextUtils.isEmpty(tab.getUrl())
877 && !tab.isSnapshot()) {
878 // Only update the bookmark screenshot if the user did not
879 // cancel the load early and there is not already
880 // a pending update for the tab.
881 if (tab.inForeground() && !didUserStopLoading()
882 || !tab.inForeground()) {
883 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
884 mHandler.sendMessageDelayed(mHandler.obtainMessage(
885 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
886 500);
887 }
888 }
889 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700890 } 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);
Michael Kolb8233fac2010-10-26 16:08:53 -07001261 return true;
1262 }
1263
1264 protected void onCreateContextMenu(ContextMenu menu, View v,
1265 ContextMenuInfo menuInfo) {
John Reck0f602f32011-07-07 15:38:43 -07001266 if (v instanceof TitleBar) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001267 return;
1268 }
1269 if (!(v instanceof WebView)) {
1270 return;
1271 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001272 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001273 WebView.HitTestResult result = webview.getHitTestResult();
1274 if (result == null) {
1275 return;
1276 }
1277
1278 int type = result.getType();
1279 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1280 Log.w(LOGTAG,
1281 "We should not show context menu when nothing is touched");
1282 return;
1283 }
1284 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1285 // let TextView handles context menu
1286 return;
1287 }
1288
1289 // Note, http://b/issue?id=1106666 is requesting that
1290 // an inflated menu can be used again. This is not available
1291 // yet, so inflate each time (yuk!)
1292 MenuInflater inflater = mActivity.getMenuInflater();
1293 inflater.inflate(R.menu.browsercontext, menu);
1294
1295 // Show the correct menu group
1296 final String extra = result.getExtra();
Michael Kolbc159c1a2011-12-15 16:06:38 -08001297 if (extra == null) return;
Michael Kolb8233fac2010-10-26 16:08:53 -07001298 menu.setGroupVisible(R.id.PHONE_MENU,
1299 type == WebView.HitTestResult.PHONE_TYPE);
1300 menu.setGroupVisible(R.id.EMAIL_MENU,
1301 type == WebView.HitTestResult.EMAIL_TYPE);
1302 menu.setGroupVisible(R.id.GEO_MENU,
1303 type == WebView.HitTestResult.GEO_TYPE);
1304 menu.setGroupVisible(R.id.IMAGE_MENU,
1305 type == WebView.HitTestResult.IMAGE_TYPE
1306 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1307 menu.setGroupVisible(R.id.ANCHOR_MENU,
1308 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1309 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001310 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1311 || type == WebView.HitTestResult.PHONE_TYPE
1312 || type == WebView.HitTestResult.EMAIL_TYPE
1313 || type == WebView.HitTestResult.GEO_TYPE;
1314 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1315 if (hitText) {
1316 menu.findItem(R.id.select_text_menu_id)
1317 .setOnMenuItemClickListener(new SelectText(webview));
1318 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001319 // Setup custom handling depending on the type
1320 switch (type) {
1321 case WebView.HitTestResult.PHONE_TYPE:
1322 menu.setHeaderTitle(Uri.decode(extra));
1323 menu.findItem(R.id.dial_context_menu_id).setIntent(
1324 new Intent(Intent.ACTION_VIEW, Uri
1325 .parse(WebView.SCHEME_TEL + extra)));
1326 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1327 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1328 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1329 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1330 addIntent);
1331 menu.findItem(R.id.copy_phone_context_menu_id)
1332 .setOnMenuItemClickListener(
1333 new Copy(extra));
1334 break;
1335
1336 case WebView.HitTestResult.EMAIL_TYPE:
1337 menu.setHeaderTitle(extra);
1338 menu.findItem(R.id.email_context_menu_id).setIntent(
1339 new Intent(Intent.ACTION_VIEW, Uri
1340 .parse(WebView.SCHEME_MAILTO + extra)));
1341 menu.findItem(R.id.copy_mail_context_menu_id)
1342 .setOnMenuItemClickListener(
1343 new Copy(extra));
1344 break;
1345
1346 case WebView.HitTestResult.GEO_TYPE:
1347 menu.setHeaderTitle(extra);
1348 menu.findItem(R.id.map_context_menu_id).setIntent(
1349 new Intent(Intent.ACTION_VIEW, Uri
1350 .parse(WebView.SCHEME_GEO
1351 + URLEncoder.encode(extra))));
1352 menu.findItem(R.id.copy_geo_context_menu_id)
1353 .setOnMenuItemClickListener(
1354 new Copy(extra));
1355 break;
1356
1357 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1358 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001359 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001360 // decide whether to show the open link in new tab option
1361 boolean showNewTab = mTabControl.canCreateNewTab();
1362 MenuItem newTabItem
1363 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001364 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001365 ? R.string.contextmenu_openlink_newwindow_background
1366 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001367 newTabItem.setVisible(showNewTab);
1368 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001369 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1370 newTabItem.setOnMenuItemClickListener(
1371 new MenuItem.OnMenuItemClickListener() {
1372 @Override
1373 public boolean onMenuItemClick(MenuItem item) {
1374 final HashMap<String, WebView> hrefMap =
1375 new HashMap<String, WebView>();
1376 hrefMap.put("webview", webview);
1377 final Message msg = mHandler.obtainMessage(
1378 FOCUS_NODE_HREF,
1379 R.id.open_newtab_context_menu_id,
1380 0, hrefMap);
1381 webview.requestFocusNodeHref(msg);
1382 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001383 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001384 });
1385 } else {
1386 newTabItem.setOnMenuItemClickListener(
1387 new MenuItem.OnMenuItemClickListener() {
1388 @Override
1389 public boolean onMenuItemClick(MenuItem item) {
1390 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001391 openTab(extra, parent,
1392 !mSettings.openInBackground(),
1393 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001394 return true;
1395 }
1396 });
1397 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001398 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001399 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1400 break;
1401 }
1402 // otherwise fall through to handle image part
1403 case WebView.HitTestResult.IMAGE_TYPE:
1404 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1405 menu.setHeaderTitle(extra);
1406 }
Michael Kolb3639c4c2011-09-28 15:36:40 -07001407 menu.findItem(R.id.view_image_context_menu_id)
1408 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1409 @Override
1410 public boolean onMenuItemClick(MenuItem item) {
1411 openTab(extra, mTabControl.getCurrentTab(), true, true);
1412 return false;
1413 }
1414 });
Michael Kolb8233fac2010-10-26 16:08:53 -07001415 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001416 setOnMenuItemClickListener(
1417 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001418 menu.findItem(R.id.set_wallpaper_context_menu_id).
1419 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1420 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001421 break;
1422
1423 default:
1424 Log.w(LOGTAG, "We should not get here.");
1425 break;
1426 }
1427 //update the ui
1428 mUi.onContextMenuCreated(menu);
1429 }
1430
1431 /**
1432 * As the menu can be open when loading state changes
1433 * we must manually update the state of the stop/reload menu
1434 * item
1435 */
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001436 private void updateInLoadMenuItems(Menu menu, Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001437 if (menu == null) {
1438 return;
1439 }
1440 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolbb8337132011-11-28 15:07:39 -08001441 MenuItem src = ((tab != null) && tab.inPageLoad()) ?
Michael Kolb8233fac2010-10-26 16:08:53 -07001442 menu.findItem(R.id.stop_menu_id):
1443 menu.findItem(R.id.reload_menu_id);
1444 if (src != null) {
1445 dest.setIcon(src.getIcon());
1446 dest.setTitle(src.getTitle());
1447 }
1448 }
1449
John Reckb3417f02011-01-14 11:01:05 -08001450 boolean onPrepareOptionsMenu(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001451 updateInLoadMenuItems(menu, getCurrentTab());
John Recke1a03a32011-09-14 17:04:16 -07001452 // hold on to the menu reference here; it is used by the page callbacks
1453 // to update the menu based on loading state
1454 mCachedMenu = menu;
Michael Kolb8233fac2010-10-26 16:08:53 -07001455 // Note: setVisible will decide whether an item is visible; while
1456 // setEnabled() will decide whether an item is enabled, which also means
1457 // whether the matching shortcut key will function.
1458 switch (mMenuState) {
1459 case EMPTY_MENU:
1460 if (mCurrentMenuState != mMenuState) {
1461 menu.setGroupVisible(R.id.MAIN_MENU, false);
1462 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1463 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1464 }
1465 break;
1466 default:
1467 if (mCurrentMenuState != mMenuState) {
1468 menu.setGroupVisible(R.id.MAIN_MENU, true);
1469 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1470 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1471 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001472 updateMenuState(getCurrentTab(), menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001473 break;
1474 }
1475 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001476 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001477 }
1478
Michael Kolb4bf79712011-07-14 14:18:12 -07001479 @Override
1480 public void updateMenuState(Tab tab, Menu menu) {
1481 boolean canGoBack = false;
1482 boolean canGoForward = false;
1483 boolean isHome = false;
John Reck42229bc2011-08-19 13:26:43 -07001484 boolean isDesktopUa = false;
John Recke1a03a32011-09-14 17:04:16 -07001485 boolean isLive = false;
Michael Kolb4bf79712011-07-14 14:18:12 -07001486 if (tab != null) {
1487 canGoBack = tab.canGoBack();
1488 canGoForward = tab.canGoForward();
1489 isHome = mSettings.getHomePage().equals(tab.getUrl());
John Reck42229bc2011-08-19 13:26:43 -07001490 isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
John Recke1a03a32011-09-14 17:04:16 -07001491 isLive = !tab.isSnapshot();
Michael Kolb4bf79712011-07-14 14:18:12 -07001492 }
1493 final MenuItem back = menu.findItem(R.id.back_menu_id);
1494 back.setEnabled(canGoBack);
1495
1496 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1497 home.setEnabled(!isHome);
1498
1499 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1500 forward.setEnabled(canGoForward);
1501
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001502 final MenuItem source = menu.findItem(isInLoad() ? R.id.stop_menu_id
1503 : R.id.reload_menu_id);
Michael Kolb4bf79712011-07-14 14:18:12 -07001504 final MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolb7ab75ee2011-07-14 16:36:38 -07001505 if (source != null && dest != null) {
1506 dest.setTitle(source.getTitle());
1507 dest.setIcon(source.getIcon());
1508 }
John Recke1a03a32011-09-14 17:04:16 -07001509 menu.setGroupVisible(R.id.NAV_MENU, isLive);
Michael Kolb4bf79712011-07-14 14:18:12 -07001510
1511 // decide whether to show the share link option
1512 PackageManager pm = mActivity.getPackageManager();
1513 Intent send = new Intent(Intent.ACTION_SEND);
1514 send.setType("text/plain");
1515 ResolveInfo ri = pm.resolveActivity(send,
1516 PackageManager.MATCH_DEFAULT_ONLY);
1517 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1518
1519 boolean isNavDump = mSettings.enableNavDump();
1520 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1521 nav.setVisible(isNavDump);
1522 nav.setEnabled(isNavDump);
1523
1524 boolean showDebugSettings = mSettings.isDebugEnabled();
John Reck42229bc2011-08-19 13:26:43 -07001525 final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
1526 uaSwitcher.setChecked(isDesktopUa);
John Recke1a03a32011-09-14 17:04:16 -07001527 menu.setGroupVisible(R.id.LIVE_MENU, isLive);
1528 menu.setGroupVisible(R.id.SNAPSHOT_MENU, !isLive);
Michael Kolb315d5022011-10-13 12:47:11 -07001529 menu.setGroupVisible(R.id.COMBO_MENU, false);
Michael Kolb4bf79712011-07-14 14:18:12 -07001530
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001531 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001532 }
1533
Michael Kolb8233fac2010-10-26 16:08:53 -07001534 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001535 if (null == getCurrentTopWebView()) {
1536 return false;
1537 }
1538 if (mMenuIsDown) {
1539 // The shortcut action consumes the MENU. Even if it is still down,
1540 // it won't trigger the next shortcut action. In the case of the
1541 // shortcut action triggering a new activity, like Bookmarks, we
1542 // won't get onKeyUp for MENU. So it is important to reset it here.
1543 mMenuIsDown = false;
1544 }
Michael Kolb3ca12752011-07-20 13:52:25 -07001545 if (mUi.onOptionsItemSelected(item)) {
1546 // ui callback handled it
1547 return true;
1548 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001549 switch (item.getItemId()) {
1550 // -- Main menu
1551 case R.id.new_tab_menu_id:
1552 openTabToHomePage();
1553 break;
1554
1555 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001556 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001557 break;
1558
1559 case R.id.goto_menu_id:
1560 editUrl();
1561 break;
1562
1563 case R.id.bookmarks_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001564 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
1565 break;
1566
1567 case R.id.history_menu_id:
1568 bookmarksOrHistoryPicker(ComboViews.History);
1569 break;
1570
1571 case R.id.snapshots_menu_id:
1572 bookmarksOrHistoryPicker(ComboViews.Snapshots);
Michael Kolb8233fac2010-10-26 16:08:53 -07001573 break;
1574
Michael Kolb8233fac2010-10-26 16:08:53 -07001575 case R.id.add_bookmark_menu_id:
John Recka60fffa2011-09-06 16:30:29 -07001576 Intent bookmarkIntent = createBookmarkCurrentPageIntent(false);
1577 if (bookmarkIntent != null) {
1578 mActivity.startActivity(bookmarkIntent);
1579 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001580 break;
1581
1582 case R.id.stop_reload_menu_id:
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001583 if (isInLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001584 stopLoading();
1585 } else {
1586 getCurrentTopWebView().reload();
1587 }
1588 break;
1589
1590 case R.id.back_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001591 getCurrentTab().goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07001592 break;
1593
1594 case R.id.forward_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001595 getCurrentTab().goForward();
Michael Kolb8233fac2010-10-26 16:08:53 -07001596 break;
1597
1598 case R.id.close_menu_id:
1599 // Close the subwindow if it exists.
1600 if (mTabControl.getCurrentSubWindow() != null) {
1601 dismissSubWindow(mTabControl.getCurrentTab());
1602 break;
1603 }
1604 closeCurrentTab();
1605 break;
1606
1607 case R.id.homepage_menu_id:
1608 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07001609 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07001610 break;
1611
1612 case R.id.preferences_menu_id:
1613 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1614 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1615 getCurrentTopWebView().getUrl());
1616 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1617 break;
1618
1619 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001620 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001621 break;
1622
John Reck2bc80422011-06-30 15:11:49 -07001623 case R.id.save_snapshot_menu_id:
1624 final Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07001625 if (source == null) break;
John Reckd8c74522011-06-14 08:45:00 -07001626 final ContentResolver cr = mActivity.getContentResolver();
1627 final ContentValues values = source.createSnapshotValues();
John Reck2bc80422011-06-30 15:11:49 -07001628 if (values != null) {
1629 new AsyncTask<Tab, Void, Long>() {
John Reckd8c74522011-06-14 08:45:00 -07001630
John Reck2bc80422011-06-30 15:11:49 -07001631 @Override
1632 protected Long doInBackground(Tab... params) {
1633 Uri result = cr.insert(Snapshots.CONTENT_URI, values);
John Reck93384ff2011-11-10 11:29:18 -08001634 if (result == null) {
1635 return null;
1636 }
John Reck2bc80422011-06-30 15:11:49 -07001637 long id = ContentUris.parseId(result);
1638 return id;
John Reckd8c74522011-06-14 08:45:00 -07001639 }
John Reckf33b1632011-06-04 20:00:23 -07001640
John Reck2bc80422011-06-30 15:11:49 -07001641 @Override
1642 protected void onPostExecute(Long id) {
John Reck93384ff2011-11-10 11:29:18 -08001643 if (id == null) {
1644 Toast.makeText(mActivity, R.string.snapshot_failed,
1645 Toast.LENGTH_SHORT).show();
1646 return;
1647 }
John Reck2bc80422011-06-30 15:11:49 -07001648 Bundle b = new Bundle();
1649 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
1650 mUi.showComboView(ComboViews.Snapshots, b);
1651 };
1652 }.execute(source);
1653 } else {
1654 Toast.makeText(mActivity, R.string.snapshot_failed,
Leon Scrogginsac993842011-02-02 12:54:07 -05001655 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001656 }
Leon Scrogginsac993842011-02-02 12:54:07 -05001657 break;
1658
Michael Kolb8233fac2010-10-26 16:08:53 -07001659 case R.id.page_info_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001660 showPageInfo();
Michael Kolb8233fac2010-10-26 16:08:53 -07001661 break;
1662
John Recke1a03a32011-09-14 17:04:16 -07001663 case R.id.snapshot_go_live:
1664 goLive();
1665 return true;
1666
Michael Kolb8233fac2010-10-26 16:08:53 -07001667 case R.id.share_page_menu_id:
1668 Tab currentTab = mTabControl.getCurrentTab();
1669 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001670 return false;
1671 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001672 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001673 break;
1674
1675 case R.id.dump_nav_menu_id:
1676 getCurrentTopWebView().debugDump();
1677 break;
1678
Michael Kolb8233fac2010-10-26 16:08:53 -07001679 case R.id.zoom_in_menu_id:
1680 getCurrentTopWebView().zoomIn();
1681 break;
1682
1683 case R.id.zoom_out_menu_id:
1684 getCurrentTopWebView().zoomOut();
1685 break;
1686
1687 case R.id.view_downloads_menu_id:
1688 viewDownloads();
1689 break;
1690
John Reck42229bc2011-08-19 13:26:43 -07001691 case R.id.ua_desktop_menu_id:
1692 WebView web = getCurrentWebView();
1693 mSettings.toggleDesktopUseragent(web);
1694 web.loadUrl(web.getOriginalUrl());
1695 break;
1696
Michael Kolb8233fac2010-10-26 16:08:53 -07001697 case R.id.window_one_menu_id:
1698 case R.id.window_two_menu_id:
1699 case R.id.window_three_menu_id:
1700 case R.id.window_four_menu_id:
1701 case R.id.window_five_menu_id:
1702 case R.id.window_six_menu_id:
1703 case R.id.window_seven_menu_id:
1704 case R.id.window_eight_menu_id:
1705 {
1706 int menuid = item.getItemId();
1707 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1708 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1709 Tab desiredTab = mTabControl.getTab(id);
1710 if (desiredTab != null &&
1711 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001712 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001713 }
1714 break;
1715 }
1716 }
1717 }
1718 break;
1719
1720 default:
1721 return false;
1722 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001723 return true;
1724 }
1725
John Recke1a03a32011-09-14 17:04:16 -07001726 private void goLive() {
1727 Tab t = getCurrentTab();
1728 t.loadUrl(t.getUrl(), null);
1729 }
1730
Michael Kolb315d5022011-10-13 12:47:11 -07001731 @Override
1732 public void showPageInfo() {
1733 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
1734 }
1735
Michael Kolb8233fac2010-10-26 16:08:53 -07001736 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001737 // Let the History and Bookmark fragments handle menus they created.
1738 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1739 return false;
1740 }
1741
Michael Kolb8233fac2010-10-26 16:08:53 -07001742 int id = item.getItemId();
1743 boolean result = true;
1744 switch (id) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001745 // -- Browser context menu
1746 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001747 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001748 case R.id.copy_link_context_menu_id:
1749 final WebView webView = getCurrentTopWebView();
1750 if (null == webView) {
1751 result = false;
1752 break;
1753 }
1754 final HashMap<String, WebView> hrefMap =
1755 new HashMap<String, WebView>();
1756 hrefMap.put("webview", webView);
1757 final Message msg = mHandler.obtainMessage(
1758 FOCUS_NODE_HREF, id, 0, hrefMap);
1759 webView.requestFocusNodeHref(msg);
1760 break;
1761
1762 default:
1763 // For other context menus
1764 result = onOptionsItemSelected(item);
1765 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001766 return result;
1767 }
1768
1769 /**
1770 * support programmatically opening the context menu
1771 */
1772 public void openContextMenu(View view) {
1773 mActivity.openContextMenu(view);
1774 }
1775
1776 /**
1777 * programmatically open the options menu
1778 */
1779 public void openOptionsMenu() {
1780 mActivity.openOptionsMenu();
1781 }
1782
1783 public boolean onMenuOpened(int featureId, Menu menu) {
1784 if (mOptionsMenuOpen) {
1785 if (mConfigChanged) {
1786 // We do not need to make any changes to the state of the
1787 // title bar, since the only thing that happened was a
1788 // change in orientation
1789 mConfigChanged = false;
1790 } else {
1791 if (!mExtendedMenuOpen) {
1792 mExtendedMenuOpen = true;
1793 mUi.onExtendedMenuOpened();
1794 } else {
1795 // Switching the menu back to icon view, so show the
1796 // title bar once again.
1797 mExtendedMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001798 mUi.onExtendedMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001799 }
1800 }
1801 } else {
1802 // The options menu is closed, so open it, and show the title
1803 mOptionsMenuOpen = true;
1804 mConfigChanged = false;
1805 mExtendedMenuOpen = false;
1806 mUi.onOptionsMenuOpened();
1807 }
1808 return true;
1809 }
1810
1811 public void onOptionsMenuClosed(Menu menu) {
1812 mOptionsMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001813 mUi.onOptionsMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001814 }
1815
1816 public void onContextMenuClosed(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001817 mUi.onContextMenuClosed(menu, isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001818 }
1819
1820 // Helper method for getting the top window.
1821 @Override
1822 public WebView getCurrentTopWebView() {
1823 return mTabControl.getCurrentTopWebView();
1824 }
1825
1826 @Override
1827 public WebView getCurrentWebView() {
1828 return mTabControl.getCurrentWebView();
1829 }
1830
1831 /*
1832 * This method is called as a result of the user selecting the options
1833 * menu to see the download window. It shows the download window on top of
1834 * the current window.
1835 */
1836 void viewDownloads() {
1837 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1838 mActivity.startActivity(intent);
1839 }
1840
John Reck30b065e2011-07-19 10:58:05 -07001841 int getActionModeHeight() {
1842 TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
1843 new int[] { android.R.attr.actionBarSize });
1844 int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
1845 actionBarSizeTypedArray.recycle();
1846 return size;
1847 }
1848
Michael Kolb8233fac2010-10-26 16:08:53 -07001849 // action mode
1850
1851 void onActionModeStarted(ActionMode mode) {
1852 mUi.onActionModeStarted(mode);
1853 mActionMode = mode;
1854 }
1855
1856 /*
1857 * True if a custom ActionMode (i.e. find or select) is in use.
1858 */
1859 @Override
1860 public boolean isInCustomActionMode() {
1861 return mActionMode != null;
1862 }
1863
1864 /*
1865 * End the current ActionMode.
1866 */
1867 @Override
1868 public void endActionMode() {
1869 if (mActionMode != null) {
1870 mActionMode.finish();
1871 }
1872 }
1873
1874 /*
1875 * Called by find and select when they are finished. Replace title bars
1876 * as necessary.
1877 */
1878 public void onActionModeFinished(ActionMode mode) {
1879 if (!isInCustomActionMode()) return;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001880 mUi.onActionModeFinished(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001881 mActionMode = null;
1882 }
1883
1884 boolean isInLoad() {
Michael Kolbc5b0b2d2011-11-29 16:13:35 -08001885 final Tab tab = getCurrentTab();
1886 return (tab != null) && tab.inPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07001887 }
1888
1889 // bookmark handling
1890
1891 /**
1892 * add the current page as a bookmark to the given folder id
1893 * @param folderId use -1 for the default folder
John Reckd3e4d5b2011-07-13 15:48:43 -07001894 * @param editExisting If true, check to see whether the site is already
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001895 * bookmarked, and if it is, edit that bookmark. If false, and
1896 * the site is already bookmarked, do not attempt to edit the
1897 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001898 */
1899 @Override
John Reckd3e4d5b2011-07-13 15:48:43 -07001900 public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
John Recka60fffa2011-09-06 16:30:29 -07001901 WebView w = getCurrentTopWebView();
1902 if (w == null) {
1903 return null;
1904 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001905 Intent i = new Intent(mActivity,
1906 AddBookmarkPage.class);
Michael Kolb8233fac2010-10-26 16:08:53 -07001907 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1908 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1909 String touchIconUrl = w.getTouchIconUrl();
1910 if (touchIconUrl != null) {
1911 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1912 WebSettings settings = w.getSettings();
1913 if (settings != null) {
1914 i.putExtra(AddBookmarkPage.USER_AGENT,
1915 settings.getUserAgentString());
1916 }
1917 }
1918 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1919 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1920 getDesiredThumbnailHeight(mActivity)));
1921 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07001922 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001923 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1924 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001925 // Put the dialog at the upper right of the screen, covering the
1926 // star on the title bar.
1927 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07001928 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07001929 }
1930
1931 // file chooser
1932 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1933 mUploadHandler = new UploadHandler(this);
1934 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1935 }
1936
1937 // thumbnails
1938
1939 /**
1940 * Return the desired width for thumbnail screenshots, which are stored in
1941 * the database, and used on the bookmarks screen.
1942 * @param context Context for finding out the density of the screen.
1943 * @return desired width for thumbnail screenshot.
1944 */
1945 static int getDesiredThumbnailWidth(Context context) {
1946 return context.getResources().getDimensionPixelOffset(
1947 R.dimen.bookmarkThumbnailWidth);
1948 }
1949
1950 /**
1951 * Return the desired height for thumbnail screenshots, which are stored in
1952 * the database, and used on the bookmarks screen.
1953 * @param context Context for finding out the density of the screen.
1954 * @return desired height for thumbnail screenshot.
1955 */
1956 static int getDesiredThumbnailHeight(Context context) {
1957 return context.getResources().getDimensionPixelOffset(
1958 R.dimen.bookmarkThumbnailHeight);
1959 }
1960
John Reck8cc92352011-07-06 17:41:52 -07001961 static Bitmap createScreenshot(WebView view, int width, int height) {
John Reckd7dd9b22011-08-30 09:18:29 -07001962 if (view == null || view.getContentHeight() == 0
1963 || view.getContentWidth() == 0) {
1964 return null;
1965 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001966 // We render to a bitmap 2x the desired size so that we can then
1967 // re-scale it with filtering since canvas.scale doesn't filter
1968 // This helps reduce aliasing at the cost of being slightly blurry
1969 final int filter_scale = 2;
John Reckd7dd9b22011-08-30 09:18:29 -07001970 int scaledWidth = width * filter_scale;
1971 int scaledHeight = height * filter_scale;
1972 if (sThumbnailBitmap == null || sThumbnailBitmap.getWidth() != scaledWidth
1973 || sThumbnailBitmap.getHeight() != scaledHeight) {
1974 if (sThumbnailBitmap != null) {
1975 sThumbnailBitmap.recycle();
1976 sThumbnailBitmap = null;
1977 }
1978 sThumbnailBitmap =
1979 Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.RGB_565);
Michael Kolb8233fac2010-10-26 16:08:53 -07001980 }
John Reckd7dd9b22011-08-30 09:18:29 -07001981 Canvas canvas = new Canvas(sThumbnailBitmap);
1982 int contentWidth = view.getContentWidth();
1983 float overviewScale = scaledWidth / (view.getScale() * contentWidth);
1984 if (view instanceof BrowserWebView) {
1985 int dy = -((BrowserWebView)view).getTitleHeight();
1986 canvas.translate(0, dy * overviewScale);
1987 }
1988
1989 canvas.scale(overviewScale, overviewScale);
1990
1991 if (view instanceof BrowserWebView) {
1992 ((BrowserWebView)view).drawContent(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07001993 } else {
John Reckd7dd9b22011-08-30 09:18:29 -07001994 view.draw(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07001995 }
John Reckd7dd9b22011-08-30 09:18:29 -07001996 Bitmap ret = Bitmap.createScaledBitmap(sThumbnailBitmap,
1997 width, height, true);
Dianne Hackborn43cfe8a2011-08-02 16:59:35 -07001998 canvas.setBitmap(null);
John Reck5c6ac2f2011-01-05 10:18:03 -08001999 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07002000 }
2001
John Reck34ef2672011-02-10 11:30:55 -08002002 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002003 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07002004 // FIXME: Would like to make sure there is actually something to
2005 // draw, but the API for that (WebViewCore.pictureReady()) is not
2006 // currently accessible here.
2007
John Reck34ef2672011-02-10 11:30:55 -08002008 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08002009 if (view == null) {
2010 // Tab was destroyed
2011 return;
2012 }
John Reck34ef2672011-02-10 11:30:55 -08002013 final String url = tab.getUrl();
2014 final String originalUrl = view.getOriginalUrl();
John Reck34ef2672011-02-10 11:30:55 -08002015 if (TextUtils.isEmpty(url)) {
2016 return;
2017 }
2018
2019 // Only update thumbnails for web urls (http(s)://), not for
2020 // about:, javascript:, data:, etc...
2021 // Unless it is a bookmarked site, then always update
2022 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2023 return;
2024 }
2025
Michael Kolb8233fac2010-10-26 16:08:53 -07002026 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2027 getDesiredThumbnailHeight(mActivity));
2028 if (bm == null) {
2029 return;
2030 }
2031
2032 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002033 new AsyncTask<Void, Void, Void>() {
2034 @Override
2035 protected Void doInBackground(Void... unused) {
2036 Cursor cursor = null;
2037 try {
2038 // TODO: Clean this up
2039 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2040 if (cursor != null && cursor.moveToFirst()) {
2041 final ByteArrayOutputStream os =
2042 new ByteArrayOutputStream();
2043 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002044
John Reck34ef2672011-02-10 11:30:55 -08002045 ContentValues values = new ContentValues();
2046 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002047
John Reck34ef2672011-02-10 11:30:55 -08002048 do {
John Reck617fd832011-02-16 14:35:59 -08002049 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002050 cr.update(Images.CONTENT_URI, values, null, null);
2051 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002052 }
John Reck34ef2672011-02-10 11:30:55 -08002053 } catch (IllegalStateException e) {
2054 // Ignore
2055 } finally {
2056 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002057 }
John Reck34ef2672011-02-10 11:30:55 -08002058 return null;
2059 }
2060 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002061 }
2062
2063 private class Copy implements OnMenuItemClickListener {
2064 private CharSequence mText;
2065
2066 public boolean onMenuItemClick(MenuItem item) {
2067 copy(mText);
2068 return true;
2069 }
2070
2071 public Copy(CharSequence toCopy) {
2072 mText = toCopy;
2073 }
2074 }
2075
Leon Scroggins63c02662010-11-18 15:16:27 -05002076 private static class Download implements OnMenuItemClickListener {
2077 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002078 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002079 private boolean mPrivateBrowsing;
George Mount387d45d2011-10-07 15:57:53 -07002080 private static final String FALLBACK_EXTENSION = "dat";
2081 private static final String IMAGE_BASE_FORMAT = "yyyy-MM-dd-HH-mm-ss-";
Michael Kolb8233fac2010-10-26 16:08:53 -07002082
2083 public boolean onMenuItemClick(MenuItem item) {
George Mount387d45d2011-10-07 15:57:53 -07002084 if (DataUri.isDataUri(mText)) {
2085 saveDataUri();
2086 } else {
2087 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
2088 null, null, mPrivateBrowsing);
2089 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002090 return true;
2091 }
2092
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002093 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002094 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002095 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002096 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002097 }
George Mount387d45d2011-10-07 15:57:53 -07002098
2099 /**
2100 * Treats mText as a data URI and writes its contents to a file
2101 * based on the current time.
2102 */
2103 private void saveDataUri() {
2104 FileOutputStream outputStream = null;
2105 try {
2106 DataUri uri = new DataUri(mText);
2107 File target = getTarget(uri);
2108 outputStream = new FileOutputStream(target);
2109 outputStream.write(uri.getData());
2110 final DownloadManager manager =
2111 (DownloadManager) mActivity.getSystemService(Context.DOWNLOAD_SERVICE);
2112 manager.addCompletedDownload(target.getName(),
2113 mActivity.getTitle().toString(), false,
2114 uri.getMimeType(), target.getAbsolutePath(),
George Mount7501bf42011-11-17 11:17:03 -08002115 (long)uri.getData().length, true);
George Mount387d45d2011-10-07 15:57:53 -07002116 } catch (IOException e) {
2117 Log.e(LOGTAG, "Could not save data URL");
2118 } finally {
2119 if (outputStream != null) {
2120 try {
2121 outputStream.close();
2122 } catch (IOException e) {
2123 // ignore close errors
2124 }
2125 }
2126 }
2127 }
2128
2129 /**
2130 * Creates a File based on the current time stamp and uses
2131 * the mime type of the DataUri to get the extension.
2132 */
2133 private File getTarget(DataUri uri) throws IOException {
2134 File dir = mActivity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
2135 DateFormat format = new SimpleDateFormat(IMAGE_BASE_FORMAT);
2136 String nameBase = format.format(new Date());
2137 String mimeType = uri.getMimeType();
2138 MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
2139 String extension = mimeTypeMap.getExtensionFromMimeType(mimeType);
2140 if (extension == null) {
2141 Log.w(LOGTAG, "Unknown mime type in data URI" + mimeType);
2142 extension = FALLBACK_EXTENSION;
2143 }
2144 extension = "." + extension; // createTempFile needs the '.'
2145 File targetFile = File.createTempFile(nameBase, extension, dir);
2146 return targetFile;
2147 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002148 }
2149
Cary Clark8974d282010-11-22 10:46:05 -05002150 private static class SelectText implements OnMenuItemClickListener {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002151 private WebViewClassic mWebView;
Cary Clark8974d282010-11-22 10:46:05 -05002152
2153 public boolean onMenuItemClick(MenuItem item) {
2154 if (mWebView != null) {
2155 return mWebView.selectText();
2156 }
2157 return false;
2158 }
2159
2160 public SelectText(WebView webView) {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002161 mWebView = WebViewClassic.fromWebView(webView);
Cary Clark8974d282010-11-22 10:46:05 -05002162 }
2163
2164 }
2165
Michael Kolb8233fac2010-10-26 16:08:53 -07002166 /********************** TODO: UI stuff *****************************/
2167
2168 // these methods have been copied, they still need to be cleaned up
2169
2170 /****************** tabs ***************************************************/
2171
2172 // basic tab interactions:
2173
2174 // it is assumed that tabcontrol already knows about the tab
2175 protected void addTab(Tab tab) {
2176 mUi.addTab(tab);
2177 }
2178
2179 protected void removeTab(Tab tab) {
2180 mUi.removeTab(tab);
2181 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002182 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002183 }
2184
Michael Kolbf2055602011-04-09 17:20:03 -07002185 @Override
2186 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002187 // monkey protection against delayed start
2188 if (tab != null) {
2189 mTabControl.setCurrentTab(tab);
2190 // the tab is guaranteed to have a webview after setCurrentTab
2191 mUi.setActiveTab(tab);
2192 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002193 }
2194
John Reck8bcafc12011-08-29 16:43:02 -07002195 protected void closeEmptyTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002196 Tab current = mTabControl.getCurrentTab();
2197 if (current != null
2198 && current.getWebView().copyBackForwardList().getSize() == 0) {
John Reck8bcafc12011-08-29 16:43:02 -07002199 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002200 }
2201 }
2202
John Reck26b18322011-06-21 13:08:58 -07002203 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002204 // Dismiss the subwindow if applicable.
2205 dismissSubWindow(appTab);
2206 // Since we might kill the WebView, remove it from the
2207 // content view first.
2208 mUi.detachTab(appTab);
2209 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002210 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002211 // TODO: analyze why the remove and add are necessary
2212 mUi.attachTab(appTab);
2213 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002214 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002215 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002216 } else {
2217 // If the tab was the current tab, we have to attach
2218 // it to the view system again.
2219 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002220 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002221 }
2222 }
2223
2224 // Remove the sub window if it exists. Also called by TabControl when the
2225 // user clicks the 'X' to dismiss a sub window.
2226 public void dismissSubWindow(Tab tab) {
2227 removeSubWindow(tab);
2228 // dismiss the subwindow. This will destroy the WebView.
2229 tab.dismissSubWindow();
Michael Kolbe8c97572011-11-21 14:03:56 -08002230 WebView wv = getCurrentTopWebView();
2231 if (wv != null) {
2232 wv.requestFocus();
2233 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002234 }
2235
2236 @Override
2237 public void removeSubWindow(Tab t) {
2238 if (t.getSubWebView() != null) {
2239 mUi.removeSubWindow(t.getSubViewContainer());
2240 }
2241 }
2242
2243 @Override
2244 public void attachSubWindow(Tab tab) {
2245 if (tab.getSubWebView() != null) {
2246 mUi.attachSubWindow(tab.getSubViewContainer());
2247 getCurrentTopWebView().requestFocus();
2248 }
2249 }
2250
Mathew Inwood29721c22011-06-29 17:55:24 +01002251 private Tab showPreloadedTab(final UrlData urlData) {
2252 if (!urlData.isPreloaded()) {
2253 return null;
2254 }
2255 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2256 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2257 if (sbQuery != null) {
Mathew Inwood9ad1eac2011-09-15 11:29:50 +01002258 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002259 // Could not submit query. Fallback to regular tab creation
2260 tabControl.destroy();
2261 return null;
2262 }
2263 }
Michael Kolbff6a7482011-07-26 16:37:15 -07002264 // check tab count and make room for new tab
2265 if (!mTabControl.canCreateNewTab()) {
2266 Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
2267 if (leastUsed != null) {
2268 closeTab(leastUsed);
2269 }
2270 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002271 Tab t = tabControl.getTab();
Mathew Inwoode09305e2011-09-02 12:03:26 +01002272 t.refreshIdAfterPreload();
Mathew Inwood29721c22011-06-29 17:55:24 +01002273 mTabControl.addPreloadedTab(t);
2274 addTab(t);
2275 setActiveTab(t);
2276 return t;
2277 }
2278
Michael Kolb7bcafde2011-05-09 13:55:59 -07002279 // open a non inconito tab with the given url data
2280 // and set as active tab
2281 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002282 Tab tab = showPreloadedTab(urlData);
2283 if (tab == null) {
2284 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002285 if ((tab != null) && !urlData.isEmpty()) {
2286 loadUrlDataIn(tab, urlData);
2287 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002288 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002289 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002290 }
2291
Michael Kolb843510f2010-12-09 10:51:49 -08002292 @Override
2293 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002294 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002295 }
2296
Michael Kolb8233fac2010-10-26 16:08:53 -07002297 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002298 public Tab openIncognitoTab() {
2299 return openTab(INCOGNITO_URI, true, true, false);
2300 }
2301
2302 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002303 public Tab openTab(String url, boolean incognito, boolean setActive,
2304 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002305 return openTab(url, incognito, setActive, useCurrent, null);
2306 }
2307
2308 @Override
2309 public Tab openTab(String url, Tab parent, boolean setActive,
2310 boolean useCurrent) {
2311 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2312 setActive, useCurrent, parent);
2313 }
2314
2315 public Tab openTab(String url, boolean incognito, boolean setActive,
2316 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002317 Tab tab = createNewTab(incognito, setActive, useCurrent);
2318 if (tab != null) {
John Reck5949c662011-05-27 09:52:29 -07002319 if (parent != null && parent != tab) {
2320 parent.addChildTab(tab);
2321 }
Michael Kolb519d2282011-05-09 17:03:19 -07002322 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002323 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002324 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002325 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002326 return tab;
2327 }
2328
2329 // this method will attempt to create a new tab
2330 // incognito: private browsing tab
2331 // setActive: ste tab as current tab
2332 // useCurrent: if no new tab can be created, return current tab
2333 private Tab createNewTab(boolean incognito, boolean setActive,
2334 boolean useCurrent) {
2335 Tab tab = null;
2336 if (mTabControl.canCreateNewTab()) {
2337 tab = mTabControl.createNewTab(incognito);
2338 addTab(tab);
2339 if (setActive) {
2340 setActiveTab(tab);
2341 }
2342 } else {
2343 if (useCurrent) {
2344 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002345 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002346 } else {
2347 mUi.showMaxTabsWarning();
2348 }
2349 }
2350 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002351 }
2352
John Reck2bc80422011-06-30 15:11:49 -07002353 @Override
2354 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2355 SnapshotTab tab = null;
2356 if (mTabControl.canCreateNewTab()) {
2357 tab = mTabControl.createSnapshotTab(snapshotId);
2358 addTab(tab);
2359 if (setActive) {
2360 setActiveTab(tab);
2361 }
2362 } else {
2363 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07002364 }
2365 return tab;
2366 }
2367
Michael Kolb8233fac2010-10-26 16:08:53 -07002368 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002369 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002370 * @return boolean True if we successfully switched to a different tab. If
2371 * the indexth tab is null, or if that tab is the same as
2372 * the current one, return false.
2373 */
2374 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002375 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002376 Tab currentTab = mTabControl.getCurrentTab();
2377 if (tab == null || tab == currentTab) {
2378 return false;
2379 }
2380 setActiveTab(tab);
2381 return true;
2382 }
2383
2384 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002385 public void closeCurrentTab() {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002386 closeCurrentTab(false);
2387 }
2388
2389 protected void closeCurrentTab(boolean andQuit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002390 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07002391 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07002392 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08002393 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002394 return;
2395 }
Michael Kolbc831b632011-05-11 09:30:34 -07002396 final Tab current = mTabControl.getCurrentTab();
2397 final int pos = mTabControl.getCurrentPosition();
2398 Tab newTab = current.getParent();
2399 if (newTab == null) {
2400 newTab = mTabControl.getTab(pos + 1);
2401 if (newTab == null) {
2402 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002403 }
2404 }
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002405 if (andQuit) {
2406 mTabControl.setCurrentTab(newTab);
2407 closeTab(current);
2408 } else if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002409 // Close window
2410 closeTab(current);
2411 }
2412 }
2413
2414 /**
2415 * Close the tab, remove its associated title bar, and adjust mTabControl's
2416 * current tab to a valid value.
2417 */
2418 @Override
2419 public void closeTab(Tab tab) {
John Reck28263772011-10-11 17:13:42 -07002420 if (tab == mTabControl.getCurrentTab()) {
2421 closeCurrentTab();
2422 } else {
2423 removeTab(tab);
2424 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002425 }
2426
Michael Kolb8233fac2010-10-26 16:08:53 -07002427 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07002428 protected void loadUrlFromContext(String url) {
2429 Tab tab = getCurrentTab();
2430 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002431 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07002432 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002433 url = UrlUtils.smartUrlFilter(url);
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002434 if (!WebViewClassic.fromWebView(view).getWebViewClient().
2435 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
John Reckbcef87f2012-02-03 14:58:34 -08002593 boolean isMenuOrCtrlKey(int keyCode) {
2594 return (KeyEvent.KEYCODE_MENU == keyCode)
2595 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2596 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode);
2597 }
2598
Michael Kolb0035fad2011-03-14 13:25:28 -07002599 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002600 * handle key events in browser
2601 *
2602 * @param keyCode
2603 * @param event
2604 * @return true if handled, false to pass to super
2605 */
2606 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002607 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002608 // Even if MENU is already held down, we need to call to super to open
2609 // the IME on long press.
John Reckbcef87f2012-02-03 14:58:34 -08002610 if (!noModifiers && isMenuOrCtrlKey(keyCode)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002611 mMenuIsDown = true;
2612 return false;
2613 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002614
Cary Clark8ff8c662010-12-29 15:03:05 -05002615 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07002616 Tab tab = getCurrentTab();
2617 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05002618
Cary Clark160bbb92011-01-10 11:17:07 -05002619 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2620 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002621
Michael Kolb8233fac2010-10-26 16:08:53 -07002622 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002623 case KeyEvent.KEYCODE_TAB:
2624 if (event.isCtrlPressed()) {
2625 if (event.isShiftPressed()) {
2626 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002627 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002628 } else {
2629 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002630 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002631 }
2632 return true;
2633 }
2634 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002635 case KeyEvent.KEYCODE_SPACE:
2636 // WebView/WebTextView handle the keys in the KeyDown. As
2637 // the Activity's shortcut keys are only handled when WebView
2638 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002639 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002640 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002641 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002642 pageDown();
2643 }
2644 return true;
2645 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002646 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002647 event.startTracking();
2648 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07002649 case KeyEvent.KEYCODE_FORWARD:
2650 if (!noModifiers) break;
2651 tab.goForward();
2652 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002653 case KeyEvent.KEYCODE_DPAD_LEFT:
2654 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002655 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05002656 return true;
2657 }
2658 break;
2659 case KeyEvent.KEYCODE_DPAD_RIGHT:
2660 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002661 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05002662 return true;
2663 }
2664 break;
2665 case KeyEvent.KEYCODE_A:
2666 if (ctrl) {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002667 WebViewClassic.fromWebView(webView).selectAll();
Cary Clark8ff8c662010-12-29 15:03:05 -05002668 return true;
2669 }
2670 break;
Michael Kolba4183062011-01-16 10:43:21 -08002671// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002672 case KeyEvent.KEYCODE_C:
2673 if (ctrl) {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002674 WebViewClassic.fromWebView(webView).copySelection();
Cary Clark8ff8c662010-12-29 15:03:05 -05002675 return true;
2676 }
2677 break;
Michael Kolba4183062011-01-16 10:43:21 -08002678// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002679// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002680// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002681// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002682// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002683// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002684// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002685// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002686// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002687// case KeyEvent.KEYCODE_M: // unused
2688// case KeyEvent.KEYCODE_N: // in Chrome: new window
2689// case KeyEvent.KEYCODE_O: // in Chrome: open file
2690// case KeyEvent.KEYCODE_P: // in Chrome: print page
2691// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002692// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002693// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2694 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002695 // we can't use the ctrl/shift flags, they check for
2696 // exclusive use of a modifier
2697 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002698 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002699 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002700 } else {
2701 openTabToHomePage();
2702 }
2703 return true;
2704 }
2705 break;
2706// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2707// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb5ae15bd2011-08-16 17:09:27 -07002708// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002709// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2710// case KeyEvent.KEYCODE_Y: // unused
2711// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002712 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002713 // it is a regular key and webview is not null
2714 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002715 }
2716
John Recke6bf4ab2011-02-24 15:48:05 -08002717 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2718 switch(keyCode) {
2719 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07002720 if (mUi.isWebShowing()) {
Michael Kolb315d5022011-10-13 12:47:11 -07002721 bookmarksOrHistoryPicker(ComboViews.History);
John Recke6bf4ab2011-02-24 15:48:05 -08002722 return true;
2723 }
2724 break;
2725 }
2726 return false;
2727 }
2728
Michael Kolb8233fac2010-10-26 16:08:53 -07002729 boolean onKeyUp(int keyCode, KeyEvent event) {
John Reckbcef87f2012-02-03 14:58:34 -08002730 if (isMenuOrCtrlKey(keyCode)) {
Michael Kolb2814a362011-05-19 15:49:41 -07002731 mMenuIsDown = false;
John Reckbcef87f2012-02-03 14:58:34 -08002732 if (KeyEvent.KEYCODE_MENU == keyCode
2733 && event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002734 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002735 }
2736 }
Cary Clark160bbb92011-01-10 11:17:07 -05002737 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002738 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002739 case KeyEvent.KEYCODE_BACK:
2740 if (event.isTracking() && !event.isCanceled()) {
2741 onBackKey();
2742 return true;
2743 }
2744 break;
2745 }
2746 return false;
2747 }
2748
2749 public boolean isMenuDown() {
2750 return mMenuIsDown;
2751 }
2752
Ben Murdoch8029a772010-11-16 11:58:21 +00002753 public void setupAutoFill(Message message) {
2754 // Open the settings activity at the AutoFill profile fragment so that
2755 // the user can create a new profile. When they return, we will dispatch
2756 // the message so that we can autofill the form using their new profile.
2757 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2758 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2759 AutoFillSettingsFragment.class.getName());
2760 mAutoFillSetupMessage = message;
2761 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2762 }
John Reckb3417f02011-01-14 11:01:05 -08002763
Michael Kolbfbc579a2011-07-07 15:59:33 -07002764 public boolean onSearchRequested() {
2765 mUi.editUrl(false);
2766 return true;
2767 }
2768
John Reck1cf4b792011-07-26 10:22:22 -07002769 @Override
2770 public boolean shouldCaptureThumbnails() {
2771 return mUi.shouldCaptureThumbnails();
2772 }
2773
Michael Kolbc3af0672011-08-09 10:24:41 -07002774 @Override
2775 public void setBlockEvents(boolean block) {
2776 mBlockEvents = block;
2777 }
2778
2779 public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002780 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002781 }
2782
2783 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002784 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002785 }
2786
2787 public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002788 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002789 }
2790
2791 public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002792 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002793 }
2794
2795 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002796 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002797 }
2798
Michael Kolb8233fac2010-10-26 16:08:53 -07002799}