blob: 0b49affc20b4af4be4275be0437a9ac42bf52291 [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;
Michael Kolb18f252f2012-03-06 13:36:20 -0800607 // update the menu in case of a locale change
608 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -0700609 if (mPageDialogsHandler != null) {
610 mPageDialogsHandler.onConfigurationChanged(config);
611 }
612 mUi.onConfigurationChanged(config);
613 }
614
615 @Override
616 public void handleNewIntent(Intent intent) {
Michael Kolb59e232c2011-08-18 17:19:53 -0700617 if (!mUi.isWebShowing()) {
618 mUi.showWeb(false);
619 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700620 mIntentHandler.onNewIntent(intent);
621 }
622
623 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800624 if (mUi.isCustomViewShowing()) {
625 hideCustomView();
626 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700627 if (mActivityPaused) {
628 Log.e(LOGTAG, "BrowserActivity is already paused.");
629 return;
630 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700631 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800632 Tab tab = mTabControl.getCurrentTab();
633 if (tab != null) {
634 tab.pause();
635 if (!pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700636 if (mWakeLock == null) {
637 PowerManager pm = (PowerManager) mActivity
638 .getSystemService(Context.POWER_SERVICE);
639 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
640 }
Michael Kolb70976932010-11-30 11:34:01 -0800641 mWakeLock.acquire();
642 mHandler.sendMessageDelayed(mHandler
643 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
644 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700645 }
646 mUi.onPause();
647 mNetworkHandler.onPause();
648
649 WebView.disablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100650 NfcHandler.unregister(mActivity);
John Reckd7dd9b22011-08-30 09:18:29 -0700651 if (sThumbnailBitmap != null) {
652 sThumbnailBitmap.recycle();
653 sThumbnailBitmap = null;
654 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700655 }
656
John Reck1cf4b792011-07-26 10:22:22 -0700657 void onSaveInstanceState(Bundle outState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700658 // Save all the tabs
George Mount3636d0a2011-11-21 09:08:21 -0800659 Bundle saveState = createSaveState();
660
661 // crash recovery manages all save & restore state
662 mCrashRecoveryHandler.writeState(saveState);
663 mSettings.setLastRunPaused(true);
664 }
665
666 /**
667 * Save the current state to outState. Does not write the state to
668 * disk.
669 * @return Bundle containing the current state of all tabs.
670 */
671 /* package */ Bundle createSaveState() {
672 Bundle saveState = new Bundle();
673 mTabControl.saveState(saveState);
674 if (!saveState.isEmpty()) {
John Reck24f18262011-06-17 14:47:20 -0700675 // Save time so that we know how old incognito tabs (if any) are.
George Mount3636d0a2011-11-21 09:08:21 -0800676 saveState.putSerializable("lastActiveDate", Calendar.getInstance());
John Reck24f18262011-06-17 14:47:20 -0700677 }
George Mount3636d0a2011-11-21 09:08:21 -0800678 return saveState;
Michael Kolb8233fac2010-10-26 16:08:53 -0700679 }
680
681 void onResume() {
682 if (!mActivityPaused) {
683 Log.e(LOGTAG, "BrowserActivity is already resumed.");
684 return;
685 }
George Mount3636d0a2011-11-21 09:08:21 -0800686 mSettings.setLastRunPaused(false);
Michael Kolb8233fac2010-10-26 16:08:53 -0700687 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800688 Tab current = mTabControl.getCurrentTab();
689 if (current != null) {
690 current.resume();
691 resumeWebViewTimers(current);
692 }
John Reckf57c0292011-07-21 18:15:39 -0700693 releaseWakeLock();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200694
Michael Kolb8233fac2010-10-26 16:08:53 -0700695 mUi.onResume();
696 mNetworkHandler.onResume();
697 WebView.enablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100698 NfcHandler.register(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700699 }
700
John Reckf57c0292011-07-21 18:15:39 -0700701 private void releaseWakeLock() {
702 if (mWakeLock != null && mWakeLock.isHeld()) {
703 mHandler.removeMessages(RELEASE_WAKELOCK);
704 mWakeLock.release();
705 }
706 }
707
Michael Kolb70976932010-11-30 11:34:01 -0800708 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800709 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800710 * @param tab guaranteed non-null
711 */
712 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700713 boolean inLoad = tab.inPageLoad();
714 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
715 CookieSyncManager.getInstance().startSync();
716 WebView w = tab.getWebView();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100717 WebViewTimersControl.getInstance().onBrowserActivityResume(w);
Michael Kolb8233fac2010-10-26 16:08:53 -0700718 }
719 }
720
Michael Kolb70976932010-11-30 11:34:01 -0800721 /**
722 * Pause all WebView timers using the WebView of the given tab
723 * @param tab
724 * @return true if the timers are paused or tab is null
725 */
726 private boolean pauseWebViewTimers(Tab tab) {
727 if (tab == null) {
728 return true;
729 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700730 CookieSyncManager.getInstance().stopSync();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100731 WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView());
Michael Kolb8233fac2010-10-26 16:08:53 -0700732 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700733 }
Michael Kolb70976932010-11-30 11:34:01 -0800734 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700735 }
736
737 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800738 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700739 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
740 mUploadHandler = null;
741 }
742 if (mTabControl == null) return;
743 mUi.onDestroy();
744 // Remove the current tab and sub window
745 Tab t = mTabControl.getCurrentTab();
746 if (t != null) {
747 dismissSubWindow(t);
748 removeTab(t);
749 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500750 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700751 // Destroy all the tabs
752 mTabControl.destroy();
753 WebIconDatabase.getInstance().close();
754 // Stop watching the default geolocation permissions
755 mSystemAllowGeolocationOrigins.stop();
756 mSystemAllowGeolocationOrigins = null;
757 }
758
759 protected boolean isActivityPaused() {
760 return mActivityPaused;
761 }
762
763 protected void onLowMemory() {
764 mTabControl.freeMemory();
765 }
766
767 @Override
768 public boolean shouldShowErrorConsole() {
769 return mShouldShowErrorConsole;
770 }
771
772 protected void setShouldShowErrorConsole(boolean show) {
773 if (show == mShouldShowErrorConsole) {
774 // Nothing to do.
775 return;
776 }
777 mShouldShowErrorConsole = show;
778 Tab t = mTabControl.getCurrentTab();
779 if (t == null) {
780 // There is no current tab so we cannot toggle the error console
781 return;
782 }
783 mUi.setShouldShowErrorConsole(t, show);
784 }
785
786 @Override
787 public void stopLoading() {
788 mLoadStopped = true;
789 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700790 WebView w = getCurrentTopWebView();
791 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700792 mUi.onPageStopped(tab);
793 }
794
795 boolean didUserStopLoading() {
796 return mLoadStopped;
797 }
798
799 // WebViewController
800
801 @Override
John Reck324d4402011-01-11 16:56:42 -0800802 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700803
804 // We've started to load a new page. If there was a pending message
805 // to save a screenshot then we will now take the new page and save
806 // an incorrect screenshot. Therefore, remove any pending thumbnail
807 // messages from the queue.
808 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800809 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700810
811 // reset sync timer to avoid sync starts during loading a page
812 CookieSyncManager.getInstance().resetSync();
813
814 if (!mNetworkHandler.isNetworkUp()) {
815 view.setNetworkAvailable(false);
816 }
817
818 // when BrowserActivity just starts, onPageStarted may be called before
819 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
820 // to start the timer. As we won't switch tabs while an activity is in
821 // pause state, we can ensure calling resume and pause in pair.
822 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800823 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700824 }
825 mLoadStopped = false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700826 endActionMode();
827
John Reck30c714c2010-12-16 17:30:34 -0800828 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700829
John Reck324d4402011-01-11 16:56:42 -0800830 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700831 // update the bookmark database for favicon
832 maybeUpdateFavicon(tab, null, url, favicon);
833
834 Performance.tracePageStart(url);
835
836 // Performance probe
837 if (false) {
838 Performance.onPageStarted();
839 }
840
841 }
842
843 @Override
John Reck324d4402011-01-11 16:56:42 -0800844 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800845 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700846 // pause the WebView timer and release the wake lock if it is finished
847 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800848 if (mActivityPaused && pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700849 releaseWakeLock();
Michael Kolb8233fac2010-10-26 16:08:53 -0700850 }
Martijn Coenenb2f93552011-06-14 10:48:35 +0200851
Michael Kolb8233fac2010-10-26 16:08:53 -0700852 // Performance probe
853 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800854 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700855 }
856
857 Performance.tracePageFinished();
858 }
859
860 @Override
John Reck30c714c2010-12-16 17:30:34 -0800861 public void onProgressChanged(Tab tab) {
John Reck6c2e2f32011-08-22 13:41:23 -0700862 mCrashRecoveryHandler.backupState();
John Reck30c714c2010-12-16 17:30:34 -0800863 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700864
865 if (newProgress == 100) {
866 CookieSyncManager.getInstance().sync();
867 // onProgressChanged() may continue to be called after the main
868 // frame has finished loading, as any remaining sub frames continue
869 // to load. We'll only get called once though with newProgress as
870 // 100 when everything is loaded. (onPageFinished is called once
871 // when the main frame completes loading regardless of the state of
872 // any sub frames so calls to onProgressChanges may continue after
873 // onPageFinished has executed)
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800874 if (tab.inPageLoad()) {
875 updateInLoadMenuItems(mCachedMenu, tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700876 }
John Reckd9862372012-02-21 15:04:50 -0800877 if (!tab.isPrivateBrowsingEnabled()
878 && !TextUtils.isEmpty(tab.getUrl())
879 && !tab.isSnapshot()) {
880 // Only update the bookmark screenshot if the user did not
881 // cancel the load early and there is not already
882 // a pending update for the tab.
883 if (tab.inForeground() && !didUserStopLoading()
884 || !tab.inForeground()) {
885 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
886 mHandler.sendMessageDelayed(mHandler.obtainMessage(
887 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
888 500);
889 }
890 }
891 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700892 } else {
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800893 if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700894 // onPageFinished may have already been called but a subframe is
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800895 // still loading
896 // updating the progress and
Michael Kolb8233fac2010-10-26 16:08:53 -0700897 // update the menu items.
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800898 updateInLoadMenuItems(mCachedMenu, tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700899 }
900 }
John Reck30c714c2010-12-16 17:30:34 -0800901 mUi.onProgressChanged(tab);
902 }
903
904 @Override
Steve Block2466eff2011-10-03 15:33:09 +0100905 public void onUpdatedSecurityState(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800906 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700907 }
908
909 @Override
910 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800911 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800912 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800913 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700914 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
915 return;
916 }
917 // Update the title in the history database if not in private browsing mode
918 if (!tab.isPrivateBrowsingEnabled()) {
John Reckf57c0292011-07-21 18:15:39 -0700919 DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700920 }
921 }
922
923 @Override
924 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800925 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700926 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
927 }
928
929 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800930 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
931 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700932 }
933
934 @Override
935 public boolean shouldOverrideKeyEvent(KeyEvent event) {
936 if (mMenuIsDown) {
937 // only check shortcut key when MENU is held
938 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
939 event);
940 } else {
941 return false;
942 }
943 }
944
945 @Override
946 public void onUnhandledKeyEvent(KeyEvent event) {
947 if (!isActivityPaused()) {
948 if (event.getAction() == KeyEvent.ACTION_DOWN) {
949 mActivity.onKeyDown(event.getKeyCode(), event);
950 } else {
951 mActivity.onKeyUp(event.getKeyCode(), event);
952 }
953 }
954 }
955
956 @Override
John Reck324d4402011-01-11 16:56:42 -0800957 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700958 // Don't save anything in private browsing mode
959 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800960 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700961
John Reck324d4402011-01-11 16:56:42 -0800962 if (TextUtils.isEmpty(url)
963 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700964 return;
965 }
John Reckf57c0292011-07-21 18:15:39 -0700966 DataController.getInstance(mActivity).updateVisitedHistory(url);
John Reck6c2e2f32011-08-22 13:41:23 -0700967 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -0700968 }
969
970 @Override
971 public void getVisitedHistory(final ValueCallback<String[]> callback) {
972 AsyncTask<Void, Void, String[]> task =
973 new AsyncTask<Void, Void, String[]>() {
974 @Override
975 public String[] doInBackground(Void... unused) {
976 return Browser.getVisitedHistory(mActivity.getContentResolver());
977 }
978 @Override
979 public void onPostExecute(String[] result) {
980 callback.onReceiveValue(result);
981 }
982 };
983 task.execute();
984 }
985
986 @Override
987 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
988 final HttpAuthHandler handler, final String host,
989 final String realm) {
990 String username = null;
991 String password = null;
992
993 boolean reuseHttpAuthUsernamePassword
994 = handler.useHttpAuthUsernamePassword();
995
996 if (reuseHttpAuthUsernamePassword && view != null) {
997 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
998 if (credentials != null && credentials.length == 2) {
999 username = credentials[0];
1000 password = credentials[1];
1001 }
1002 }
1003
1004 if (username != null && password != null) {
1005 handler.proceed(username, password);
1006 } else {
Ben Murdochfdd37112011-08-05 15:48:14 +01001007 if (tab.inForeground() && !handler.suppressDialog()) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001008 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
1009 } else {
1010 handler.cancel();
1011 }
1012 }
1013 }
1014
1015 @Override
1016 public void onDownloadStart(Tab tab, String url, String userAgent,
1017 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001018 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -05001019 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001020 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
1021 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001022 // This Tab was opened for the sole purpose of downloading a
1023 // file. Remove it.
1024 if (tab == mTabControl.getCurrentTab()) {
1025 // In this case, the Tab is still on top.
1026 goBackOnePageOrQuit();
1027 } else {
1028 // In this case, it is not.
1029 closeTab(tab);
1030 }
1031 }
1032 }
1033
1034 @Override
1035 public Bitmap getDefaultVideoPoster() {
1036 return mUi.getDefaultVideoPoster();
1037 }
1038
1039 @Override
1040 public View getVideoLoadingProgressView() {
1041 return mUi.getVideoLoadingProgressView();
1042 }
1043
1044 @Override
1045 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1046 SslError error) {
1047 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1048 }
1049
Patrick Scott92066772011-03-10 08:46:27 -05001050 @Override
1051 public void showAutoLogin(Tab tab) {
1052 assert tab.inForeground();
1053 // Update the title bar to show the auto-login request.
1054 mUi.showAutoLogin(tab);
1055 }
1056
1057 @Override
1058 public void hideAutoLogin(Tab tab) {
1059 assert tab.inForeground();
1060 mUi.hideAutoLogin(tab);
1061 }
1062
Michael Kolb8233fac2010-10-26 16:08:53 -07001063 // helper method
1064
1065 /*
1066 * Update the favorites icon if the private browsing isn't enabled and the
1067 * icon is valid.
1068 */
1069 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1070 final String url, Bitmap favicon) {
1071 if (favicon == null) {
1072 return;
1073 }
1074 if (!tab.isPrivateBrowsingEnabled()) {
1075 Bookmarks.updateFavicon(mActivity
1076 .getContentResolver(), originalUrl, url, favicon);
1077 }
1078 }
1079
Leon Scroggins4cd97792010-12-03 15:31:56 -05001080 @Override
1081 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001082 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001083 mUi.bookmarkedStatusHasChanged(tab);
1084 }
1085
Michael Kolb8233fac2010-10-26 16:08:53 -07001086 // end WebViewController
1087
1088 protected void pageUp() {
1089 getCurrentTopWebView().pageUp(false);
1090 }
1091
1092 protected void pageDown() {
1093 getCurrentTopWebView().pageDown(false);
1094 }
1095
1096 // callback from phone title bar
1097 public void editUrl() {
1098 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001099 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001100 }
1101
Michael Kolbcfa3af52010-12-14 10:36:11 -08001102 public void startVoiceSearch() {
1103 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1104 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1105 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1106 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1107 mActivity.getComponentName().flattenToString());
1108 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001109 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001110 mActivity.startActivity(intent);
1111 }
1112
Michael Kolb11d19782011-03-20 10:17:40 -07001113 @Override
1114 public void activateVoiceSearchMode(String title, List<String> results) {
1115 mUi.showVoiceTitleBar(title, results);
Michael Kolb8233fac2010-10-26 16:08:53 -07001116 }
1117
1118 public void revertVoiceSearchMode(Tab tab) {
1119 mUi.revertVoiceTitleBar(tab);
1120 }
1121
Michael Kolb736990c2011-03-20 10:01:20 -07001122 public boolean supportsVoiceSearch() {
John Reck35e9dd62011-04-25 09:01:54 -07001123 SearchEngine searchEngine = getSettings().getSearchEngine();
Michael Kolb736990c2011-03-20 10:01:20 -07001124 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1125 }
1126
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001127 public void showCustomView(Tab tab, View view, int requestedOrientation,
Michael Kolb8233fac2010-10-26 16:08:53 -07001128 WebChromeClient.CustomViewCallback callback) {
1129 if (tab.inForeground()) {
1130 if (mUi.isCustomViewShowing()) {
1131 callback.onCustomViewHidden();
1132 return;
1133 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001134 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001135 // Save the menu state and set it to empty while the custom
1136 // view is showing.
1137 mOldMenuState = mMenuState;
1138 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001139 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001140 }
1141 }
1142
1143 @Override
1144 public void hideCustomView() {
1145 if (mUi.isCustomViewShowing()) {
1146 mUi.onHideCustomView();
1147 // Reset the old menu state.
1148 mMenuState = mOldMenuState;
1149 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001150 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001151 }
1152 }
1153
1154 protected void onActivityResult(int requestCode, int resultCode,
1155 Intent intent) {
1156 if (getCurrentTopWebView() == null) return;
1157 switch (requestCode) {
1158 case PREFERENCES_PAGE:
1159 if (resultCode == Activity.RESULT_OK && intent != null) {
1160 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001161 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001162 mTabControl.removeParentChildRelationShips();
1163 }
1164 }
1165 break;
1166 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001167 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001168 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001169 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001170 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001171 case AUTOFILL_SETUP:
1172 // Determine whether a profile was actually set up or not
1173 // and if so, send the message back to the WebTextView to
1174 // fill the form with the new profile.
1175 if (getSettings().getAutoFillProfile() != null) {
1176 mAutoFillSetupMessage.sendToTarget();
1177 mAutoFillSetupMessage = null;
1178 }
1179 break;
John Reckd3e4d5b2011-07-13 15:48:43 -07001180 case COMBO_VIEW:
1181 if (intent == null || resultCode != Activity.RESULT_OK) {
1182 break;
1183 }
John Reck3ba45532011-08-11 16:26:53 -07001184 mUi.showWeb(false);
John Reckd3e4d5b2011-07-13 15:48:43 -07001185 if (Intent.ACTION_VIEW.equals(intent.getAction())) {
1186 Tab t = getCurrentTab();
1187 Uri uri = intent.getData();
1188 loadUrl(t, uri.toString());
1189 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
1190 String[] urls = intent.getStringArrayExtra(
1191 ComboViewActivity.EXTRA_OPEN_ALL);
1192 Tab parent = getCurrentTab();
1193 for (String url : urls) {
1194 parent = openTab(url, parent,
1195 !mSettings.openInBackground(), true);
1196 }
1197 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
1198 long id = intent.getLongExtra(
1199 ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
1200 if (id >= 0) {
1201 createNewSnapshotTab(id, true);
1202 }
1203 }
1204 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001205 default:
1206 break;
1207 }
1208 getCurrentTopWebView().requestFocus();
1209 }
1210
1211 /**
1212 * Open the Go page.
1213 * @param startWithHistory If true, open starting on the history tab.
1214 * Otherwise, start with the bookmarks tab.
1215 */
1216 @Override
Michael Kolb315d5022011-10-13 12:47:11 -07001217 public void bookmarksOrHistoryPicker(ComboViews startView) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001218 if (mTabControl.getCurrentWebView() == null) {
1219 return;
1220 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001221 // clear action mode
1222 if (isInCustomActionMode()) {
1223 endActionMode();
1224 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001225 Bundle extras = new Bundle();
1226 // Disable opening in a new window if we have maxed out the windows
1227 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1228 !mTabControl.canCreateNewTab());
Michael Kolb315d5022011-10-13 12:47:11 -07001229 mUi.showComboView(startView, extras);
Michael Kolb8233fac2010-10-26 16:08:53 -07001230 }
1231
1232 // combo view callbacks
1233
Michael Kolb8233fac2010-10-26 16:08:53 -07001234 // key handling
1235 protected void onBackKey() {
1236 if (!mUi.onBackKey()) {
1237 WebView subwindow = mTabControl.getCurrentSubWindow();
1238 if (subwindow != null) {
1239 if (subwindow.canGoBack()) {
1240 subwindow.goBack();
1241 } else {
1242 dismissSubWindow(mTabControl.getCurrentTab());
1243 }
1244 } else {
1245 goBackOnePageOrQuit();
1246 }
1247 }
1248 }
1249
Michael Kolb4bd767d2011-05-27 11:33:55 -07001250 protected boolean onMenuKey() {
1251 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001252 }
1253
Michael Kolb8233fac2010-10-26 16:08:53 -07001254 // menu handling and state
1255 // TODO: maybe put into separate handler
1256
1257 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckd73c5a22010-12-22 10:22:50 -08001258 if (mMenuState == EMPTY_MENU) {
1259 return false;
1260 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001261 MenuInflater inflater = mActivity.getMenuInflater();
1262 inflater.inflate(R.menu.browser, menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001263 return true;
1264 }
1265
1266 protected void onCreateContextMenu(ContextMenu menu, View v,
1267 ContextMenuInfo menuInfo) {
John Reck0f602f32011-07-07 15:38:43 -07001268 if (v instanceof TitleBar) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001269 return;
1270 }
1271 if (!(v instanceof WebView)) {
1272 return;
1273 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001274 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001275 WebView.HitTestResult result = webview.getHitTestResult();
1276 if (result == null) {
1277 return;
1278 }
1279
1280 int type = result.getType();
1281 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1282 Log.w(LOGTAG,
1283 "We should not show context menu when nothing is touched");
1284 return;
1285 }
1286 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1287 // let TextView handles context menu
1288 return;
1289 }
1290
1291 // Note, http://b/issue?id=1106666 is requesting that
1292 // an inflated menu can be used again. This is not available
1293 // yet, so inflate each time (yuk!)
1294 MenuInflater inflater = mActivity.getMenuInflater();
1295 inflater.inflate(R.menu.browsercontext, menu);
1296
1297 // Show the correct menu group
1298 final String extra = result.getExtra();
Michael Kolbc159c1a2011-12-15 16:06:38 -08001299 if (extra == null) return;
Michael Kolb8233fac2010-10-26 16:08:53 -07001300 menu.setGroupVisible(R.id.PHONE_MENU,
1301 type == WebView.HitTestResult.PHONE_TYPE);
1302 menu.setGroupVisible(R.id.EMAIL_MENU,
1303 type == WebView.HitTestResult.EMAIL_TYPE);
1304 menu.setGroupVisible(R.id.GEO_MENU,
1305 type == WebView.HitTestResult.GEO_TYPE);
1306 menu.setGroupVisible(R.id.IMAGE_MENU,
1307 type == WebView.HitTestResult.IMAGE_TYPE
1308 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1309 menu.setGroupVisible(R.id.ANCHOR_MENU,
1310 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1311 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001312 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1313 || type == WebView.HitTestResult.PHONE_TYPE
1314 || type == WebView.HitTestResult.EMAIL_TYPE
1315 || type == WebView.HitTestResult.GEO_TYPE;
1316 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1317 if (hitText) {
1318 menu.findItem(R.id.select_text_menu_id)
1319 .setOnMenuItemClickListener(new SelectText(webview));
1320 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001321 // Setup custom handling depending on the type
1322 switch (type) {
1323 case WebView.HitTestResult.PHONE_TYPE:
1324 menu.setHeaderTitle(Uri.decode(extra));
1325 menu.findItem(R.id.dial_context_menu_id).setIntent(
1326 new Intent(Intent.ACTION_VIEW, Uri
1327 .parse(WebView.SCHEME_TEL + extra)));
1328 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1329 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1330 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1331 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1332 addIntent);
1333 menu.findItem(R.id.copy_phone_context_menu_id)
1334 .setOnMenuItemClickListener(
1335 new Copy(extra));
1336 break;
1337
1338 case WebView.HitTestResult.EMAIL_TYPE:
1339 menu.setHeaderTitle(extra);
1340 menu.findItem(R.id.email_context_menu_id).setIntent(
1341 new Intent(Intent.ACTION_VIEW, Uri
1342 .parse(WebView.SCHEME_MAILTO + extra)));
1343 menu.findItem(R.id.copy_mail_context_menu_id)
1344 .setOnMenuItemClickListener(
1345 new Copy(extra));
1346 break;
1347
1348 case WebView.HitTestResult.GEO_TYPE:
1349 menu.setHeaderTitle(extra);
1350 menu.findItem(R.id.map_context_menu_id).setIntent(
1351 new Intent(Intent.ACTION_VIEW, Uri
1352 .parse(WebView.SCHEME_GEO
1353 + URLEncoder.encode(extra))));
1354 menu.findItem(R.id.copy_geo_context_menu_id)
1355 .setOnMenuItemClickListener(
1356 new Copy(extra));
1357 break;
1358
1359 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1360 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001361 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001362 // decide whether to show the open link in new tab option
1363 boolean showNewTab = mTabControl.canCreateNewTab();
1364 MenuItem newTabItem
1365 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001366 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001367 ? R.string.contextmenu_openlink_newwindow_background
1368 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001369 newTabItem.setVisible(showNewTab);
1370 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001371 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1372 newTabItem.setOnMenuItemClickListener(
1373 new MenuItem.OnMenuItemClickListener() {
1374 @Override
1375 public boolean onMenuItemClick(MenuItem item) {
1376 final HashMap<String, WebView> hrefMap =
1377 new HashMap<String, WebView>();
1378 hrefMap.put("webview", webview);
1379 final Message msg = mHandler.obtainMessage(
1380 FOCUS_NODE_HREF,
1381 R.id.open_newtab_context_menu_id,
1382 0, hrefMap);
1383 webview.requestFocusNodeHref(msg);
1384 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001385 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001386 });
1387 } else {
1388 newTabItem.setOnMenuItemClickListener(
1389 new MenuItem.OnMenuItemClickListener() {
1390 @Override
1391 public boolean onMenuItemClick(MenuItem item) {
1392 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001393 openTab(extra, parent,
1394 !mSettings.openInBackground(),
1395 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001396 return true;
1397 }
1398 });
1399 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001400 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001401 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1402 break;
1403 }
1404 // otherwise fall through to handle image part
1405 case WebView.HitTestResult.IMAGE_TYPE:
1406 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1407 menu.setHeaderTitle(extra);
1408 }
Michael Kolb3639c4c2011-09-28 15:36:40 -07001409 menu.findItem(R.id.view_image_context_menu_id)
1410 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1411 @Override
1412 public boolean onMenuItemClick(MenuItem item) {
1413 openTab(extra, mTabControl.getCurrentTab(), true, true);
1414 return false;
1415 }
1416 });
Michael Kolb8233fac2010-10-26 16:08:53 -07001417 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001418 setOnMenuItemClickListener(
1419 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001420 menu.findItem(R.id.set_wallpaper_context_menu_id).
1421 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1422 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001423 break;
1424
1425 default:
1426 Log.w(LOGTAG, "We should not get here.");
1427 break;
1428 }
1429 //update the ui
1430 mUi.onContextMenuCreated(menu);
1431 }
1432
1433 /**
1434 * As the menu can be open when loading state changes
1435 * we must manually update the state of the stop/reload menu
1436 * item
1437 */
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001438 private void updateInLoadMenuItems(Menu menu, Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001439 if (menu == null) {
1440 return;
1441 }
1442 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolbb8337132011-11-28 15:07:39 -08001443 MenuItem src = ((tab != null) && tab.inPageLoad()) ?
Michael Kolb8233fac2010-10-26 16:08:53 -07001444 menu.findItem(R.id.stop_menu_id):
1445 menu.findItem(R.id.reload_menu_id);
1446 if (src != null) {
1447 dest.setIcon(src.getIcon());
1448 dest.setTitle(src.getTitle());
1449 }
1450 }
1451
John Reckb3417f02011-01-14 11:01:05 -08001452 boolean onPrepareOptionsMenu(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001453 updateInLoadMenuItems(menu, getCurrentTab());
John Recke1a03a32011-09-14 17:04:16 -07001454 // hold on to the menu reference here; it is used by the page callbacks
1455 // to update the menu based on loading state
1456 mCachedMenu = menu;
Michael Kolb8233fac2010-10-26 16:08:53 -07001457 // Note: setVisible will decide whether an item is visible; while
1458 // setEnabled() will decide whether an item is enabled, which also means
1459 // whether the matching shortcut key will function.
1460 switch (mMenuState) {
1461 case EMPTY_MENU:
1462 if (mCurrentMenuState != mMenuState) {
1463 menu.setGroupVisible(R.id.MAIN_MENU, false);
1464 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1465 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1466 }
1467 break;
1468 default:
1469 if (mCurrentMenuState != mMenuState) {
1470 menu.setGroupVisible(R.id.MAIN_MENU, true);
1471 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1472 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1473 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001474 updateMenuState(getCurrentTab(), menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001475 break;
1476 }
1477 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001478 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001479 }
1480
Michael Kolb4bf79712011-07-14 14:18:12 -07001481 @Override
1482 public void updateMenuState(Tab tab, Menu menu) {
1483 boolean canGoBack = false;
1484 boolean canGoForward = false;
1485 boolean isHome = false;
John Reck42229bc2011-08-19 13:26:43 -07001486 boolean isDesktopUa = false;
John Recke1a03a32011-09-14 17:04:16 -07001487 boolean isLive = false;
Michael Kolb4bf79712011-07-14 14:18:12 -07001488 if (tab != null) {
1489 canGoBack = tab.canGoBack();
1490 canGoForward = tab.canGoForward();
1491 isHome = mSettings.getHomePage().equals(tab.getUrl());
John Reck42229bc2011-08-19 13:26:43 -07001492 isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
John Recke1a03a32011-09-14 17:04:16 -07001493 isLive = !tab.isSnapshot();
Michael Kolb4bf79712011-07-14 14:18:12 -07001494 }
1495 final MenuItem back = menu.findItem(R.id.back_menu_id);
1496 back.setEnabled(canGoBack);
1497
1498 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1499 home.setEnabled(!isHome);
1500
1501 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1502 forward.setEnabled(canGoForward);
1503
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001504 final MenuItem source = menu.findItem(isInLoad() ? R.id.stop_menu_id
1505 : R.id.reload_menu_id);
Michael Kolb4bf79712011-07-14 14:18:12 -07001506 final MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolb7ab75ee2011-07-14 16:36:38 -07001507 if (source != null && dest != null) {
1508 dest.setTitle(source.getTitle());
1509 dest.setIcon(source.getIcon());
1510 }
John Recke1a03a32011-09-14 17:04:16 -07001511 menu.setGroupVisible(R.id.NAV_MENU, isLive);
Michael Kolb4bf79712011-07-14 14:18:12 -07001512
1513 // decide whether to show the share link option
1514 PackageManager pm = mActivity.getPackageManager();
1515 Intent send = new Intent(Intent.ACTION_SEND);
1516 send.setType("text/plain");
1517 ResolveInfo ri = pm.resolveActivity(send,
1518 PackageManager.MATCH_DEFAULT_ONLY);
1519 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1520
1521 boolean isNavDump = mSettings.enableNavDump();
1522 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1523 nav.setVisible(isNavDump);
1524 nav.setEnabled(isNavDump);
1525
1526 boolean showDebugSettings = mSettings.isDebugEnabled();
John Reck42229bc2011-08-19 13:26:43 -07001527 final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
1528 uaSwitcher.setChecked(isDesktopUa);
John Recke1a03a32011-09-14 17:04:16 -07001529 menu.setGroupVisible(R.id.LIVE_MENU, isLive);
1530 menu.setGroupVisible(R.id.SNAPSHOT_MENU, !isLive);
Michael Kolb315d5022011-10-13 12:47:11 -07001531 menu.setGroupVisible(R.id.COMBO_MENU, false);
Michael Kolb4bf79712011-07-14 14:18:12 -07001532
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001533 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001534 }
1535
Michael Kolb8233fac2010-10-26 16:08:53 -07001536 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001537 if (null == getCurrentTopWebView()) {
1538 return false;
1539 }
1540 if (mMenuIsDown) {
1541 // The shortcut action consumes the MENU. Even if it is still down,
1542 // it won't trigger the next shortcut action. In the case of the
1543 // shortcut action triggering a new activity, like Bookmarks, we
1544 // won't get onKeyUp for MENU. So it is important to reset it here.
1545 mMenuIsDown = false;
1546 }
Michael Kolb3ca12752011-07-20 13:52:25 -07001547 if (mUi.onOptionsItemSelected(item)) {
1548 // ui callback handled it
1549 return true;
1550 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001551 switch (item.getItemId()) {
1552 // -- Main menu
1553 case R.id.new_tab_menu_id:
1554 openTabToHomePage();
1555 break;
1556
1557 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001558 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001559 break;
1560
1561 case R.id.goto_menu_id:
1562 editUrl();
1563 break;
1564
1565 case R.id.bookmarks_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001566 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
1567 break;
1568
1569 case R.id.history_menu_id:
1570 bookmarksOrHistoryPicker(ComboViews.History);
1571 break;
1572
1573 case R.id.snapshots_menu_id:
1574 bookmarksOrHistoryPicker(ComboViews.Snapshots);
Michael Kolb8233fac2010-10-26 16:08:53 -07001575 break;
1576
Michael Kolb8233fac2010-10-26 16:08:53 -07001577 case R.id.add_bookmark_menu_id:
John Recka60fffa2011-09-06 16:30:29 -07001578 Intent bookmarkIntent = createBookmarkCurrentPageIntent(false);
1579 if (bookmarkIntent != null) {
1580 mActivity.startActivity(bookmarkIntent);
1581 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001582 break;
1583
1584 case R.id.stop_reload_menu_id:
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001585 if (isInLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001586 stopLoading();
1587 } else {
1588 getCurrentTopWebView().reload();
1589 }
1590 break;
1591
1592 case R.id.back_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001593 getCurrentTab().goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07001594 break;
1595
1596 case R.id.forward_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001597 getCurrentTab().goForward();
Michael Kolb8233fac2010-10-26 16:08:53 -07001598 break;
1599
1600 case R.id.close_menu_id:
1601 // Close the subwindow if it exists.
1602 if (mTabControl.getCurrentSubWindow() != null) {
1603 dismissSubWindow(mTabControl.getCurrentTab());
1604 break;
1605 }
1606 closeCurrentTab();
1607 break;
1608
1609 case R.id.homepage_menu_id:
1610 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07001611 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07001612 break;
1613
1614 case R.id.preferences_menu_id:
1615 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1616 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1617 getCurrentTopWebView().getUrl());
1618 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1619 break;
1620
1621 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001622 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001623 break;
1624
John Reck2bc80422011-06-30 15:11:49 -07001625 case R.id.save_snapshot_menu_id:
1626 final Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07001627 if (source == null) break;
John Reckd8c74522011-06-14 08:45:00 -07001628 final ContentResolver cr = mActivity.getContentResolver();
1629 final ContentValues values = source.createSnapshotValues();
John Reck2bc80422011-06-30 15:11:49 -07001630 if (values != null) {
1631 new AsyncTask<Tab, Void, Long>() {
John Reckd8c74522011-06-14 08:45:00 -07001632
John Reck2bc80422011-06-30 15:11:49 -07001633 @Override
1634 protected Long doInBackground(Tab... params) {
1635 Uri result = cr.insert(Snapshots.CONTENT_URI, values);
John Reck93384ff2011-11-10 11:29:18 -08001636 if (result == null) {
1637 return null;
1638 }
John Reck2bc80422011-06-30 15:11:49 -07001639 long id = ContentUris.parseId(result);
1640 return id;
John Reckd8c74522011-06-14 08:45:00 -07001641 }
John Reckf33b1632011-06-04 20:00:23 -07001642
John Reck2bc80422011-06-30 15:11:49 -07001643 @Override
1644 protected void onPostExecute(Long id) {
John Reck93384ff2011-11-10 11:29:18 -08001645 if (id == null) {
1646 Toast.makeText(mActivity, R.string.snapshot_failed,
1647 Toast.LENGTH_SHORT).show();
1648 return;
1649 }
John Reck2bc80422011-06-30 15:11:49 -07001650 Bundle b = new Bundle();
1651 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
1652 mUi.showComboView(ComboViews.Snapshots, b);
1653 };
1654 }.execute(source);
1655 } else {
1656 Toast.makeText(mActivity, R.string.snapshot_failed,
Leon Scrogginsac993842011-02-02 12:54:07 -05001657 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001658 }
Leon Scrogginsac993842011-02-02 12:54:07 -05001659 break;
1660
Michael Kolb8233fac2010-10-26 16:08:53 -07001661 case R.id.page_info_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001662 showPageInfo();
Michael Kolb8233fac2010-10-26 16:08:53 -07001663 break;
1664
John Recke1a03a32011-09-14 17:04:16 -07001665 case R.id.snapshot_go_live:
1666 goLive();
1667 return true;
1668
Michael Kolb8233fac2010-10-26 16:08:53 -07001669 case R.id.share_page_menu_id:
1670 Tab currentTab = mTabControl.getCurrentTab();
1671 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001672 return false;
1673 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001674 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001675 break;
1676
1677 case R.id.dump_nav_menu_id:
1678 getCurrentTopWebView().debugDump();
1679 break;
1680
Michael Kolb8233fac2010-10-26 16:08:53 -07001681 case R.id.zoom_in_menu_id:
1682 getCurrentTopWebView().zoomIn();
1683 break;
1684
1685 case R.id.zoom_out_menu_id:
1686 getCurrentTopWebView().zoomOut();
1687 break;
1688
1689 case R.id.view_downloads_menu_id:
1690 viewDownloads();
1691 break;
1692
John Reck42229bc2011-08-19 13:26:43 -07001693 case R.id.ua_desktop_menu_id:
1694 WebView web = getCurrentWebView();
1695 mSettings.toggleDesktopUseragent(web);
1696 web.loadUrl(web.getOriginalUrl());
1697 break;
1698
Michael Kolb8233fac2010-10-26 16:08:53 -07001699 case R.id.window_one_menu_id:
1700 case R.id.window_two_menu_id:
1701 case R.id.window_three_menu_id:
1702 case R.id.window_four_menu_id:
1703 case R.id.window_five_menu_id:
1704 case R.id.window_six_menu_id:
1705 case R.id.window_seven_menu_id:
1706 case R.id.window_eight_menu_id:
1707 {
1708 int menuid = item.getItemId();
1709 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1710 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1711 Tab desiredTab = mTabControl.getTab(id);
1712 if (desiredTab != null &&
1713 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001714 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001715 }
1716 break;
1717 }
1718 }
1719 }
1720 break;
1721
1722 default:
1723 return false;
1724 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001725 return true;
1726 }
1727
John Recke1a03a32011-09-14 17:04:16 -07001728 private void goLive() {
1729 Tab t = getCurrentTab();
1730 t.loadUrl(t.getUrl(), null);
1731 }
1732
Michael Kolb315d5022011-10-13 12:47:11 -07001733 @Override
1734 public void showPageInfo() {
1735 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
1736 }
1737
Michael Kolb8233fac2010-10-26 16:08:53 -07001738 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001739 // Let the History and Bookmark fragments handle menus they created.
1740 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1741 return false;
1742 }
1743
Michael Kolb8233fac2010-10-26 16:08:53 -07001744 int id = item.getItemId();
1745 boolean result = true;
1746 switch (id) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001747 // -- Browser context menu
1748 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001749 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001750 case R.id.copy_link_context_menu_id:
1751 final WebView webView = getCurrentTopWebView();
1752 if (null == webView) {
1753 result = false;
1754 break;
1755 }
1756 final HashMap<String, WebView> hrefMap =
1757 new HashMap<String, WebView>();
1758 hrefMap.put("webview", webView);
1759 final Message msg = mHandler.obtainMessage(
1760 FOCUS_NODE_HREF, id, 0, hrefMap);
1761 webView.requestFocusNodeHref(msg);
1762 break;
1763
1764 default:
1765 // For other context menus
1766 result = onOptionsItemSelected(item);
1767 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001768 return result;
1769 }
1770
1771 /**
1772 * support programmatically opening the context menu
1773 */
1774 public void openContextMenu(View view) {
1775 mActivity.openContextMenu(view);
1776 }
1777
1778 /**
1779 * programmatically open the options menu
1780 */
1781 public void openOptionsMenu() {
1782 mActivity.openOptionsMenu();
1783 }
1784
1785 public boolean onMenuOpened(int featureId, Menu menu) {
1786 if (mOptionsMenuOpen) {
1787 if (mConfigChanged) {
1788 // We do not need to make any changes to the state of the
1789 // title bar, since the only thing that happened was a
1790 // change in orientation
1791 mConfigChanged = false;
1792 } else {
1793 if (!mExtendedMenuOpen) {
1794 mExtendedMenuOpen = true;
1795 mUi.onExtendedMenuOpened();
1796 } else {
1797 // Switching the menu back to icon view, so show the
1798 // title bar once again.
1799 mExtendedMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001800 mUi.onExtendedMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001801 }
1802 }
1803 } else {
1804 // The options menu is closed, so open it, and show the title
1805 mOptionsMenuOpen = true;
1806 mConfigChanged = false;
1807 mExtendedMenuOpen = false;
1808 mUi.onOptionsMenuOpened();
1809 }
1810 return true;
1811 }
1812
1813 public void onOptionsMenuClosed(Menu menu) {
1814 mOptionsMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001815 mUi.onOptionsMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001816 }
1817
1818 public void onContextMenuClosed(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001819 mUi.onContextMenuClosed(menu, isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001820 }
1821
1822 // Helper method for getting the top window.
1823 @Override
1824 public WebView getCurrentTopWebView() {
1825 return mTabControl.getCurrentTopWebView();
1826 }
1827
1828 @Override
1829 public WebView getCurrentWebView() {
1830 return mTabControl.getCurrentWebView();
1831 }
1832
1833 /*
1834 * This method is called as a result of the user selecting the options
1835 * menu to see the download window. It shows the download window on top of
1836 * the current window.
1837 */
1838 void viewDownloads() {
1839 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1840 mActivity.startActivity(intent);
1841 }
1842
John Reck30b065e2011-07-19 10:58:05 -07001843 int getActionModeHeight() {
1844 TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
1845 new int[] { android.R.attr.actionBarSize });
1846 int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
1847 actionBarSizeTypedArray.recycle();
1848 return size;
1849 }
1850
Michael Kolb8233fac2010-10-26 16:08:53 -07001851 // action mode
1852
1853 void onActionModeStarted(ActionMode mode) {
1854 mUi.onActionModeStarted(mode);
1855 mActionMode = mode;
1856 }
1857
1858 /*
1859 * True if a custom ActionMode (i.e. find or select) is in use.
1860 */
1861 @Override
1862 public boolean isInCustomActionMode() {
1863 return mActionMode != null;
1864 }
1865
1866 /*
1867 * End the current ActionMode.
1868 */
1869 @Override
1870 public void endActionMode() {
1871 if (mActionMode != null) {
1872 mActionMode.finish();
1873 }
1874 }
1875
1876 /*
1877 * Called by find and select when they are finished. Replace title bars
1878 * as necessary.
1879 */
1880 public void onActionModeFinished(ActionMode mode) {
1881 if (!isInCustomActionMode()) return;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001882 mUi.onActionModeFinished(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07001883 mActionMode = null;
1884 }
1885
1886 boolean isInLoad() {
Michael Kolbc5b0b2d2011-11-29 16:13:35 -08001887 final Tab tab = getCurrentTab();
1888 return (tab != null) && tab.inPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07001889 }
1890
1891 // bookmark handling
1892
1893 /**
1894 * add the current page as a bookmark to the given folder id
1895 * @param folderId use -1 for the default folder
John Reckd3e4d5b2011-07-13 15:48:43 -07001896 * @param editExisting If true, check to see whether the site is already
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001897 * bookmarked, and if it is, edit that bookmark. If false, and
1898 * the site is already bookmarked, do not attempt to edit the
1899 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001900 */
1901 @Override
John Reckd3e4d5b2011-07-13 15:48:43 -07001902 public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
John Recka60fffa2011-09-06 16:30:29 -07001903 WebView w = getCurrentTopWebView();
1904 if (w == null) {
1905 return null;
1906 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001907 Intent i = new Intent(mActivity,
1908 AddBookmarkPage.class);
Michael Kolb8233fac2010-10-26 16:08:53 -07001909 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1910 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1911 String touchIconUrl = w.getTouchIconUrl();
1912 if (touchIconUrl != null) {
1913 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1914 WebSettings settings = w.getSettings();
1915 if (settings != null) {
1916 i.putExtra(AddBookmarkPage.USER_AGENT,
1917 settings.getUserAgentString());
1918 }
1919 }
1920 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1921 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1922 getDesiredThumbnailHeight(mActivity)));
1923 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07001924 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001925 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1926 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001927 // Put the dialog at the upper right of the screen, covering the
1928 // star on the title bar.
1929 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07001930 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07001931 }
1932
1933 // file chooser
1934 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1935 mUploadHandler = new UploadHandler(this);
1936 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1937 }
1938
1939 // thumbnails
1940
1941 /**
1942 * Return the desired width for thumbnail screenshots, which are stored in
1943 * the database, and used on the bookmarks screen.
1944 * @param context Context for finding out the density of the screen.
1945 * @return desired width for thumbnail screenshot.
1946 */
1947 static int getDesiredThumbnailWidth(Context context) {
1948 return context.getResources().getDimensionPixelOffset(
1949 R.dimen.bookmarkThumbnailWidth);
1950 }
1951
1952 /**
1953 * Return the desired height for thumbnail screenshots, which are stored in
1954 * the database, and used on the bookmarks screen.
1955 * @param context Context for finding out the density of the screen.
1956 * @return desired height for thumbnail screenshot.
1957 */
1958 static int getDesiredThumbnailHeight(Context context) {
1959 return context.getResources().getDimensionPixelOffset(
1960 R.dimen.bookmarkThumbnailHeight);
1961 }
1962
John Reck8cc92352011-07-06 17:41:52 -07001963 static Bitmap createScreenshot(WebView view, int width, int height) {
John Reckd7dd9b22011-08-30 09:18:29 -07001964 if (view == null || view.getContentHeight() == 0
1965 || view.getContentWidth() == 0) {
1966 return null;
1967 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001968 // We render to a bitmap 2x the desired size so that we can then
1969 // re-scale it with filtering since canvas.scale doesn't filter
1970 // This helps reduce aliasing at the cost of being slightly blurry
1971 final int filter_scale = 2;
John Reckd7dd9b22011-08-30 09:18:29 -07001972 int scaledWidth = width * filter_scale;
1973 int scaledHeight = height * filter_scale;
1974 if (sThumbnailBitmap == null || sThumbnailBitmap.getWidth() != scaledWidth
1975 || sThumbnailBitmap.getHeight() != scaledHeight) {
1976 if (sThumbnailBitmap != null) {
1977 sThumbnailBitmap.recycle();
1978 sThumbnailBitmap = null;
1979 }
1980 sThumbnailBitmap =
1981 Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.RGB_565);
Michael Kolb8233fac2010-10-26 16:08:53 -07001982 }
John Reckd7dd9b22011-08-30 09:18:29 -07001983 Canvas canvas = new Canvas(sThumbnailBitmap);
1984 int contentWidth = view.getContentWidth();
1985 float overviewScale = scaledWidth / (view.getScale() * contentWidth);
1986 if (view instanceof BrowserWebView) {
1987 int dy = -((BrowserWebView)view).getTitleHeight();
1988 canvas.translate(0, dy * overviewScale);
1989 }
1990
1991 canvas.scale(overviewScale, overviewScale);
1992
1993 if (view instanceof BrowserWebView) {
1994 ((BrowserWebView)view).drawContent(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07001995 } else {
John Reckd7dd9b22011-08-30 09:18:29 -07001996 view.draw(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07001997 }
John Reckd7dd9b22011-08-30 09:18:29 -07001998 Bitmap ret = Bitmap.createScaledBitmap(sThumbnailBitmap,
1999 width, height, true);
Dianne Hackborn43cfe8a2011-08-02 16:59:35 -07002000 canvas.setBitmap(null);
John Reck5c6ac2f2011-01-05 10:18:03 -08002001 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07002002 }
2003
John Reck34ef2672011-02-10 11:30:55 -08002004 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002005 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07002006 // FIXME: Would like to make sure there is actually something to
2007 // draw, but the API for that (WebViewCore.pictureReady()) is not
2008 // currently accessible here.
2009
John Reck34ef2672011-02-10 11:30:55 -08002010 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08002011 if (view == null) {
2012 // Tab was destroyed
2013 return;
2014 }
John Reck34ef2672011-02-10 11:30:55 -08002015 final String url = tab.getUrl();
2016 final String originalUrl = view.getOriginalUrl();
John Reck34ef2672011-02-10 11:30:55 -08002017 if (TextUtils.isEmpty(url)) {
2018 return;
2019 }
2020
2021 // Only update thumbnails for web urls (http(s)://), not for
2022 // about:, javascript:, data:, etc...
2023 // Unless it is a bookmarked site, then always update
2024 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2025 return;
2026 }
2027
Michael Kolb8233fac2010-10-26 16:08:53 -07002028 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2029 getDesiredThumbnailHeight(mActivity));
2030 if (bm == null) {
2031 return;
2032 }
2033
2034 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002035 new AsyncTask<Void, Void, Void>() {
2036 @Override
2037 protected Void doInBackground(Void... unused) {
2038 Cursor cursor = null;
2039 try {
2040 // TODO: Clean this up
2041 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2042 if (cursor != null && cursor.moveToFirst()) {
2043 final ByteArrayOutputStream os =
2044 new ByteArrayOutputStream();
2045 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002046
John Reck34ef2672011-02-10 11:30:55 -08002047 ContentValues values = new ContentValues();
2048 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002049
John Reck34ef2672011-02-10 11:30:55 -08002050 do {
John Reck617fd832011-02-16 14:35:59 -08002051 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002052 cr.update(Images.CONTENT_URI, values, null, null);
2053 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002054 }
John Reck34ef2672011-02-10 11:30:55 -08002055 } catch (IllegalStateException e) {
2056 // Ignore
2057 } finally {
2058 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002059 }
John Reck34ef2672011-02-10 11:30:55 -08002060 return null;
2061 }
2062 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002063 }
2064
2065 private class Copy implements OnMenuItemClickListener {
2066 private CharSequence mText;
2067
2068 public boolean onMenuItemClick(MenuItem item) {
2069 copy(mText);
2070 return true;
2071 }
2072
2073 public Copy(CharSequence toCopy) {
2074 mText = toCopy;
2075 }
2076 }
2077
Leon Scroggins63c02662010-11-18 15:16:27 -05002078 private static class Download implements OnMenuItemClickListener {
2079 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002080 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002081 private boolean mPrivateBrowsing;
George Mount387d45d2011-10-07 15:57:53 -07002082 private static final String FALLBACK_EXTENSION = "dat";
2083 private static final String IMAGE_BASE_FORMAT = "yyyy-MM-dd-HH-mm-ss-";
Michael Kolb8233fac2010-10-26 16:08:53 -07002084
2085 public boolean onMenuItemClick(MenuItem item) {
George Mount387d45d2011-10-07 15:57:53 -07002086 if (DataUri.isDataUri(mText)) {
2087 saveDataUri();
2088 } else {
2089 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
2090 null, null, mPrivateBrowsing);
2091 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002092 return true;
2093 }
2094
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002095 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002096 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002097 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002098 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002099 }
George Mount387d45d2011-10-07 15:57:53 -07002100
2101 /**
2102 * Treats mText as a data URI and writes its contents to a file
2103 * based on the current time.
2104 */
2105 private void saveDataUri() {
2106 FileOutputStream outputStream = null;
2107 try {
2108 DataUri uri = new DataUri(mText);
2109 File target = getTarget(uri);
2110 outputStream = new FileOutputStream(target);
2111 outputStream.write(uri.getData());
2112 final DownloadManager manager =
2113 (DownloadManager) mActivity.getSystemService(Context.DOWNLOAD_SERVICE);
2114 manager.addCompletedDownload(target.getName(),
2115 mActivity.getTitle().toString(), false,
2116 uri.getMimeType(), target.getAbsolutePath(),
George Mount7501bf42011-11-17 11:17:03 -08002117 (long)uri.getData().length, true);
George Mount387d45d2011-10-07 15:57:53 -07002118 } catch (IOException e) {
2119 Log.e(LOGTAG, "Could not save data URL");
2120 } finally {
2121 if (outputStream != null) {
2122 try {
2123 outputStream.close();
2124 } catch (IOException e) {
2125 // ignore close errors
2126 }
2127 }
2128 }
2129 }
2130
2131 /**
2132 * Creates a File based on the current time stamp and uses
2133 * the mime type of the DataUri to get the extension.
2134 */
2135 private File getTarget(DataUri uri) throws IOException {
2136 File dir = mActivity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
2137 DateFormat format = new SimpleDateFormat(IMAGE_BASE_FORMAT);
2138 String nameBase = format.format(new Date());
2139 String mimeType = uri.getMimeType();
2140 MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
2141 String extension = mimeTypeMap.getExtensionFromMimeType(mimeType);
2142 if (extension == null) {
2143 Log.w(LOGTAG, "Unknown mime type in data URI" + mimeType);
2144 extension = FALLBACK_EXTENSION;
2145 }
2146 extension = "." + extension; // createTempFile needs the '.'
2147 File targetFile = File.createTempFile(nameBase, extension, dir);
2148 return targetFile;
2149 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002150 }
2151
Cary Clark8974d282010-11-22 10:46:05 -05002152 private static class SelectText implements OnMenuItemClickListener {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002153 private WebViewClassic mWebView;
Cary Clark8974d282010-11-22 10:46:05 -05002154
2155 public boolean onMenuItemClick(MenuItem item) {
2156 if (mWebView != null) {
2157 return mWebView.selectText();
2158 }
2159 return false;
2160 }
2161
2162 public SelectText(WebView webView) {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002163 mWebView = WebViewClassic.fromWebView(webView);
Cary Clark8974d282010-11-22 10:46:05 -05002164 }
2165
2166 }
2167
Michael Kolb8233fac2010-10-26 16:08:53 -07002168 /********************** TODO: UI stuff *****************************/
2169
2170 // these methods have been copied, they still need to be cleaned up
2171
2172 /****************** tabs ***************************************************/
2173
2174 // basic tab interactions:
2175
2176 // it is assumed that tabcontrol already knows about the tab
2177 protected void addTab(Tab tab) {
2178 mUi.addTab(tab);
2179 }
2180
2181 protected void removeTab(Tab tab) {
2182 mUi.removeTab(tab);
2183 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002184 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002185 }
2186
Michael Kolbf2055602011-04-09 17:20:03 -07002187 @Override
2188 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002189 // monkey protection against delayed start
2190 if (tab != null) {
2191 mTabControl.setCurrentTab(tab);
2192 // the tab is guaranteed to have a webview after setCurrentTab
2193 mUi.setActiveTab(tab);
2194 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002195 }
2196
John Reck8bcafc12011-08-29 16:43:02 -07002197 protected void closeEmptyTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002198 Tab current = mTabControl.getCurrentTab();
2199 if (current != null
2200 && current.getWebView().copyBackForwardList().getSize() == 0) {
John Reck8bcafc12011-08-29 16:43:02 -07002201 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002202 }
2203 }
2204
John Reck26b18322011-06-21 13:08:58 -07002205 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002206 // Dismiss the subwindow if applicable.
2207 dismissSubWindow(appTab);
2208 // Since we might kill the WebView, remove it from the
2209 // content view first.
2210 mUi.detachTab(appTab);
2211 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002212 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002213 // TODO: analyze why the remove and add are necessary
2214 mUi.attachTab(appTab);
2215 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002216 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002217 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002218 } else {
2219 // If the tab was the current tab, we have to attach
2220 // it to the view system again.
2221 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002222 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002223 }
2224 }
2225
2226 // Remove the sub window if it exists. Also called by TabControl when the
2227 // user clicks the 'X' to dismiss a sub window.
2228 public void dismissSubWindow(Tab tab) {
2229 removeSubWindow(tab);
2230 // dismiss the subwindow. This will destroy the WebView.
2231 tab.dismissSubWindow();
Michael Kolbe8c97572011-11-21 14:03:56 -08002232 WebView wv = getCurrentTopWebView();
2233 if (wv != null) {
2234 wv.requestFocus();
2235 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002236 }
2237
2238 @Override
2239 public void removeSubWindow(Tab t) {
2240 if (t.getSubWebView() != null) {
2241 mUi.removeSubWindow(t.getSubViewContainer());
2242 }
2243 }
2244
2245 @Override
2246 public void attachSubWindow(Tab tab) {
2247 if (tab.getSubWebView() != null) {
2248 mUi.attachSubWindow(tab.getSubViewContainer());
2249 getCurrentTopWebView().requestFocus();
2250 }
2251 }
2252
Mathew Inwood29721c22011-06-29 17:55:24 +01002253 private Tab showPreloadedTab(final UrlData urlData) {
2254 if (!urlData.isPreloaded()) {
2255 return null;
2256 }
2257 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2258 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2259 if (sbQuery != null) {
Mathew Inwood9ad1eac2011-09-15 11:29:50 +01002260 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002261 // Could not submit query. Fallback to regular tab creation
2262 tabControl.destroy();
2263 return null;
2264 }
2265 }
Michael Kolbff6a7482011-07-26 16:37:15 -07002266 // check tab count and make room for new tab
2267 if (!mTabControl.canCreateNewTab()) {
2268 Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
2269 if (leastUsed != null) {
2270 closeTab(leastUsed);
2271 }
2272 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002273 Tab t = tabControl.getTab();
Mathew Inwoode09305e2011-09-02 12:03:26 +01002274 t.refreshIdAfterPreload();
Mathew Inwood29721c22011-06-29 17:55:24 +01002275 mTabControl.addPreloadedTab(t);
2276 addTab(t);
2277 setActiveTab(t);
2278 return t;
2279 }
2280
Michael Kolb7bcafde2011-05-09 13:55:59 -07002281 // open a non inconito tab with the given url data
2282 // and set as active tab
2283 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002284 Tab tab = showPreloadedTab(urlData);
2285 if (tab == null) {
2286 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002287 if ((tab != null) && !urlData.isEmpty()) {
2288 loadUrlDataIn(tab, urlData);
2289 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002290 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002291 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002292 }
2293
Michael Kolb843510f2010-12-09 10:51:49 -08002294 @Override
2295 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002296 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002297 }
2298
Michael Kolb8233fac2010-10-26 16:08:53 -07002299 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002300 public Tab openIncognitoTab() {
2301 return openTab(INCOGNITO_URI, true, true, false);
2302 }
2303
2304 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002305 public Tab openTab(String url, boolean incognito, boolean setActive,
2306 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002307 return openTab(url, incognito, setActive, useCurrent, null);
2308 }
2309
2310 @Override
2311 public Tab openTab(String url, Tab parent, boolean setActive,
2312 boolean useCurrent) {
2313 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2314 setActive, useCurrent, parent);
2315 }
2316
2317 public Tab openTab(String url, boolean incognito, boolean setActive,
2318 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002319 Tab tab = createNewTab(incognito, setActive, useCurrent);
2320 if (tab != null) {
John Reck5949c662011-05-27 09:52:29 -07002321 if (parent != null && parent != tab) {
2322 parent.addChildTab(tab);
2323 }
Michael Kolb519d2282011-05-09 17:03:19 -07002324 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002325 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002326 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002327 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002328 return tab;
2329 }
2330
2331 // this method will attempt to create a new tab
2332 // incognito: private browsing tab
2333 // setActive: ste tab as current tab
2334 // useCurrent: if no new tab can be created, return current tab
2335 private Tab createNewTab(boolean incognito, boolean setActive,
2336 boolean useCurrent) {
2337 Tab tab = null;
2338 if (mTabControl.canCreateNewTab()) {
2339 tab = mTabControl.createNewTab(incognito);
2340 addTab(tab);
2341 if (setActive) {
2342 setActiveTab(tab);
2343 }
2344 } else {
2345 if (useCurrent) {
2346 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002347 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002348 } else {
2349 mUi.showMaxTabsWarning();
2350 }
2351 }
2352 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002353 }
2354
John Reck2bc80422011-06-30 15:11:49 -07002355 @Override
2356 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2357 SnapshotTab tab = null;
2358 if (mTabControl.canCreateNewTab()) {
2359 tab = mTabControl.createSnapshotTab(snapshotId);
2360 addTab(tab);
2361 if (setActive) {
2362 setActiveTab(tab);
2363 }
2364 } else {
2365 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07002366 }
2367 return tab;
2368 }
2369
Michael Kolb8233fac2010-10-26 16:08:53 -07002370 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002371 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002372 * @return boolean True if we successfully switched to a different tab. If
2373 * the indexth tab is null, or if that tab is the same as
2374 * the current one, return false.
2375 */
2376 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002377 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002378 Tab currentTab = mTabControl.getCurrentTab();
2379 if (tab == null || tab == currentTab) {
2380 return false;
2381 }
2382 setActiveTab(tab);
2383 return true;
2384 }
2385
2386 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002387 public void closeCurrentTab() {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002388 closeCurrentTab(false);
2389 }
2390
2391 protected void closeCurrentTab(boolean andQuit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002392 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07002393 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07002394 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08002395 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002396 return;
2397 }
Michael Kolbc831b632011-05-11 09:30:34 -07002398 final Tab current = mTabControl.getCurrentTab();
2399 final int pos = mTabControl.getCurrentPosition();
2400 Tab newTab = current.getParent();
2401 if (newTab == null) {
2402 newTab = mTabControl.getTab(pos + 1);
2403 if (newTab == null) {
2404 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002405 }
2406 }
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002407 if (andQuit) {
2408 mTabControl.setCurrentTab(newTab);
2409 closeTab(current);
2410 } else if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002411 // Close window
2412 closeTab(current);
2413 }
2414 }
2415
2416 /**
2417 * Close the tab, remove its associated title bar, and adjust mTabControl's
2418 * current tab to a valid value.
2419 */
2420 @Override
2421 public void closeTab(Tab tab) {
John Reck28263772011-10-11 17:13:42 -07002422 if (tab == mTabControl.getCurrentTab()) {
2423 closeCurrentTab();
2424 } else {
2425 removeTab(tab);
2426 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002427 }
2428
Michael Kolb8233fac2010-10-26 16:08:53 -07002429 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07002430 protected void loadUrlFromContext(String url) {
2431 Tab tab = getCurrentTab();
2432 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002433 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07002434 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002435 url = UrlUtils.smartUrlFilter(url);
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002436 if (!WebViewClassic.fromWebView(view).getWebViewClient().
2437 shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07002438 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07002439 }
2440 }
2441 }
2442
2443 /**
2444 * Load the URL into the given WebView and update the title bar
2445 * to reflect the new load. Call this instead of WebView.loadUrl
2446 * directly.
2447 * @param view The WebView used to load url.
2448 * @param url The URL to load.
2449 */
John Reck71e51422011-07-01 16:49:28 -07002450 @Override
2451 public void loadUrl(Tab tab, String url) {
John Reck26b18322011-06-21 13:08:58 -07002452 loadUrl(tab, url, null);
2453 }
2454
2455 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
2456 if (tab != null) {
2457 dismissSubWindow(tab);
2458 tab.loadUrl(url, headers);
Michael Kolba53c9892011-10-05 13:31:40 -07002459 mUi.onProgressChanged(tab);
John Reck26b18322011-06-21 13:08:58 -07002460 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002461 }
2462
2463 /**
2464 * Load UrlData into a Tab and update the title bar to reflect the new
2465 * load. Call this instead of UrlData.loadIn directly.
2466 * @param t The Tab used to load.
2467 * @param data The UrlData being loaded.
2468 */
2469 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07002470 if (data != null) {
2471 if (data.mVoiceIntent != null) {
2472 t.activateVoiceSearchMode(data.mVoiceIntent);
Michael Kolb14612442011-06-24 13:06:29 -07002473 } else if (data.isPreloaded()) {
2474 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07002475 } else {
2476 loadUrl(t, data.mUrl, data.mHeaders);
2477 }
2478 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002479 }
2480
John Reck30c714c2010-12-16 17:30:34 -08002481 @Override
2482 public void onUserCanceledSsl(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08002483 // TODO: Figure out the "right" behavior
John Reckef654f12011-07-12 16:42:08 -07002484 if (tab.canGoBack()) {
2485 tab.goBack();
John Reck30c714c2010-12-16 17:30:34 -08002486 } else {
John Reckef654f12011-07-12 16:42:08 -07002487 tab.loadUrl(mSettings.getHomePage(), null);
John Reck30c714c2010-12-16 17:30:34 -08002488 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002489 }
2490
2491 void goBackOnePageOrQuit() {
2492 Tab current = mTabControl.getCurrentTab();
2493 if (current == null) {
2494 /*
2495 * Instead of finishing the activity, simply push this to the back
2496 * of the stack and let ActivityManager to choose the foreground
2497 * activity. As BrowserActivity is singleTask, it will be always the
2498 * root of the task. So we can use either true or false for
2499 * moveTaskToBack().
2500 */
2501 mActivity.moveTaskToBack(true);
2502 return;
2503 }
John Reckef654f12011-07-12 16:42:08 -07002504 if (current.canGoBack()) {
2505 current.goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07002506 } else {
2507 // Check to see if we are closing a window that was created by
2508 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002509 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002510 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002511 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002512 // Now we close the other tab
2513 closeTab(current);
2514 } else {
Michael Kolbe28b3472011-08-04 16:54:31 -07002515 if ((current.getAppId() != null) || current.closeOnBack()) {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002516 closeCurrentTab(true);
Michael Kolbe28b3472011-08-04 16:54:31 -07002517 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002518 /*
2519 * Instead of finishing the activity, simply push this to the back
2520 * of the stack and let ActivityManager to choose the foreground
2521 * activity. As BrowserActivity is singleTask, it will be always the
2522 * root of the task. So we can use either true or false for
2523 * moveTaskToBack().
2524 */
2525 mActivity.moveTaskToBack(true);
2526 }
2527 }
2528 }
2529
2530 /**
2531 * Feed the previously stored results strings to the BrowserProvider so that
2532 * the SearchDialog will show them instead of the standard searches.
2533 * @param result String to show on the editable line of the SearchDialog.
2534 */
2535 @Override
2536 public void showVoiceSearchResults(String result) {
2537 ContentProviderClient client = mActivity.getContentResolver()
2538 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2539 ContentProvider prov = client.getLocalContentProvider();
2540 BrowserProvider bp = (BrowserProvider) prov;
2541 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2542 client.release();
2543
2544 Bundle bundle = createGoogleSearchSourceBundle(
2545 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2546 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2547 startSearch(result, false, bundle, false);
2548 }
2549
2550 private void startSearch(String initialQuery, boolean selectInitialQuery,
2551 Bundle appSearchData, boolean globalSearch) {
2552 if (appSearchData == null) {
2553 appSearchData = createGoogleSearchSourceBundle(
2554 GOOGLE_SEARCH_SOURCE_TYPE);
2555 }
2556
2557 SearchEngine searchEngine = mSettings.getSearchEngine();
2558 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2559 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2560 }
2561 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2562 globalSearch);
2563 }
2564
2565 private Bundle createGoogleSearchSourceBundle(String source) {
2566 Bundle bundle = new Bundle();
2567 bundle.putString(Search.SOURCE, source);
2568 return bundle;
2569 }
2570
2571 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002572 * helper method for key handler
2573 * returns the current tab if it can't advance
2574 */
Michael Kolbc831b632011-05-11 09:30:34 -07002575 private Tab getNextTab() {
Michael Kolbf5261da2011-12-15 15:07:35 -08002576 int pos = mTabControl.getCurrentPosition() + 1;
2577 if (pos >= mTabControl.getTabCount()) {
2578 pos = 0;
2579 }
2580 return mTabControl.getTab(pos);
Michael Kolb0035fad2011-03-14 13:25:28 -07002581 }
2582
2583 /**
2584 * helper method for key handler
2585 * returns the current tab if it can't advance
2586 */
Michael Kolbc831b632011-05-11 09:30:34 -07002587 private Tab getPrevTab() {
Michael Kolbf5261da2011-12-15 15:07:35 -08002588 int pos = mTabControl.getCurrentPosition() - 1;
2589 if ( pos < 0) {
2590 pos = mTabControl.getTabCount() - 1;
2591 }
2592 return mTabControl.getTab(pos);
Michael Kolb0035fad2011-03-14 13:25:28 -07002593 }
2594
John Reckbcef87f2012-02-03 14:58:34 -08002595 boolean isMenuOrCtrlKey(int keyCode) {
2596 return (KeyEvent.KEYCODE_MENU == keyCode)
2597 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2598 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode);
2599 }
2600
Michael Kolb0035fad2011-03-14 13:25:28 -07002601 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002602 * handle key events in browser
2603 *
2604 * @param keyCode
2605 * @param event
2606 * @return true if handled, false to pass to super
2607 */
2608 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002609 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002610 // Even if MENU is already held down, we need to call to super to open
2611 // the IME on long press.
John Reckbcef87f2012-02-03 14:58:34 -08002612 if (!noModifiers && isMenuOrCtrlKey(keyCode)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002613 mMenuIsDown = true;
2614 return false;
2615 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002616
Cary Clark8ff8c662010-12-29 15:03:05 -05002617 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07002618 Tab tab = getCurrentTab();
2619 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05002620
Cary Clark160bbb92011-01-10 11:17:07 -05002621 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2622 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002623
Michael Kolb8233fac2010-10-26 16:08:53 -07002624 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002625 case KeyEvent.KEYCODE_TAB:
2626 if (event.isCtrlPressed()) {
2627 if (event.isShiftPressed()) {
2628 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002629 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002630 } else {
2631 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002632 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002633 }
2634 return true;
2635 }
2636 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002637 case KeyEvent.KEYCODE_SPACE:
2638 // WebView/WebTextView handle the keys in the KeyDown. As
2639 // the Activity's shortcut keys are only handled when WebView
2640 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002641 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002642 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002643 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002644 pageDown();
2645 }
2646 return true;
2647 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002648 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002649 event.startTracking();
2650 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07002651 case KeyEvent.KEYCODE_FORWARD:
2652 if (!noModifiers) break;
2653 tab.goForward();
2654 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002655 case KeyEvent.KEYCODE_DPAD_LEFT:
2656 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002657 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05002658 return true;
2659 }
2660 break;
2661 case KeyEvent.KEYCODE_DPAD_RIGHT:
2662 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002663 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05002664 return true;
2665 }
2666 break;
2667 case KeyEvent.KEYCODE_A:
2668 if (ctrl) {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002669 WebViewClassic.fromWebView(webView).selectAll();
Cary Clark8ff8c662010-12-29 15:03:05 -05002670 return true;
2671 }
2672 break;
Michael Kolba4183062011-01-16 10:43:21 -08002673// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002674 case KeyEvent.KEYCODE_C:
2675 if (ctrl) {
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00002676 WebViewClassic.fromWebView(webView).copySelection();
Cary Clark8ff8c662010-12-29 15:03:05 -05002677 return true;
2678 }
2679 break;
Michael Kolba4183062011-01-16 10:43:21 -08002680// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002681// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002682// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002683// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002684// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002685// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002686// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002687// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002688// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002689// case KeyEvent.KEYCODE_M: // unused
2690// case KeyEvent.KEYCODE_N: // in Chrome: new window
2691// case KeyEvent.KEYCODE_O: // in Chrome: open file
2692// case KeyEvent.KEYCODE_P: // in Chrome: print page
2693// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002694// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002695// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2696 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002697 // we can't use the ctrl/shift flags, they check for
2698 // exclusive use of a modifier
2699 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002700 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002701 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002702 } else {
2703 openTabToHomePage();
2704 }
2705 return true;
2706 }
2707 break;
2708// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2709// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb5ae15bd2011-08-16 17:09:27 -07002710// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002711// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2712// case KeyEvent.KEYCODE_Y: // unused
2713// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002714 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002715 // it is a regular key and webview is not null
2716 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002717 }
2718
John Recke6bf4ab2011-02-24 15:48:05 -08002719 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2720 switch(keyCode) {
2721 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07002722 if (mUi.isWebShowing()) {
Michael Kolb315d5022011-10-13 12:47:11 -07002723 bookmarksOrHistoryPicker(ComboViews.History);
John Recke6bf4ab2011-02-24 15:48:05 -08002724 return true;
2725 }
2726 break;
2727 }
2728 return false;
2729 }
2730
Michael Kolb8233fac2010-10-26 16:08:53 -07002731 boolean onKeyUp(int keyCode, KeyEvent event) {
John Reckbcef87f2012-02-03 14:58:34 -08002732 if (isMenuOrCtrlKey(keyCode)) {
Michael Kolb2814a362011-05-19 15:49:41 -07002733 mMenuIsDown = false;
John Reckbcef87f2012-02-03 14:58:34 -08002734 if (KeyEvent.KEYCODE_MENU == keyCode
2735 && event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002736 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002737 }
2738 }
Cary Clark160bbb92011-01-10 11:17:07 -05002739 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002740 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002741 case KeyEvent.KEYCODE_BACK:
2742 if (event.isTracking() && !event.isCanceled()) {
2743 onBackKey();
2744 return true;
2745 }
2746 break;
2747 }
2748 return false;
2749 }
2750
2751 public boolean isMenuDown() {
2752 return mMenuIsDown;
2753 }
2754
Ben Murdoch8029a772010-11-16 11:58:21 +00002755 public void setupAutoFill(Message message) {
2756 // Open the settings activity at the AutoFill profile fragment so that
2757 // the user can create a new profile. When they return, we will dispatch
2758 // the message so that we can autofill the form using their new profile.
2759 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2760 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2761 AutoFillSettingsFragment.class.getName());
2762 mAutoFillSetupMessage = message;
2763 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2764 }
John Reckb3417f02011-01-14 11:01:05 -08002765
Michael Kolbfbc579a2011-07-07 15:59:33 -07002766 public boolean onSearchRequested() {
2767 mUi.editUrl(false);
2768 return true;
2769 }
2770
John Reck1cf4b792011-07-26 10:22:22 -07002771 @Override
2772 public boolean shouldCaptureThumbnails() {
2773 return mUi.shouldCaptureThumbnails();
2774 }
2775
Michael Kolbc3af0672011-08-09 10:24:41 -07002776 @Override
2777 public void setBlockEvents(boolean block) {
2778 mBlockEvents = block;
2779 }
2780
2781 public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002782 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002783 }
2784
2785 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002786 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002787 }
2788
2789 public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002790 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002791 }
2792
2793 public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002794 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002795 }
2796
2797 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002798 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002799 }
2800
Michael Kolb8233fac2010-10-26 16:08:53 -07002801}