blob: e72570d21f35a57c23de44dd54ea6436e5c77f3c [file] [log] [blame]
Michael Kolb8233fac2010-10-26 16:08:53 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
Michael Kolb8233fac2010-10-26 16:08:53 -070019import android.app.Activity;
20import android.app.DownloadManager;
21import android.app.SearchManager;
22import android.content.ClipboardManager;
23import android.content.ContentProvider;
24import android.content.ContentProviderClient;
25import android.content.ContentResolver;
John Reckd8c74522011-06-14 08:45:00 -070026import android.content.ContentUris;
Michael Kolb8233fac2010-10-26 16:08:53 -070027import android.content.ContentValues;
28import android.content.Context;
29import android.content.Intent;
30import android.content.pm.PackageManager;
31import android.content.pm.ResolveInfo;
32import android.content.res.Configuration;
John Reck30b065e2011-07-19 10:58:05 -070033import android.content.res.TypedArray;
Leon Scroggins1961ed22010-12-07 15:22:21 -050034import android.database.ContentObserver;
Michael Kolb8233fac2010-10-26 16:08:53 -070035import android.database.Cursor;
36import android.database.sqlite.SQLiteDatabase;
Michael Kolb8233fac2010-10-26 16:08:53 -070037import android.graphics.Bitmap;
38import android.graphics.Canvas;
Michael Kolb8233fac2010-10-26 16:08:53 -070039import android.net.Uri;
40import android.net.http.SslError;
41import android.os.AsyncTask;
42import android.os.Bundle;
George Mount387d45d2011-10-07 15:57:53 -070043import android.os.Environment;
Michael Kolb8233fac2010-10-26 16:08:53 -070044import android.os.Handler;
45import android.os.Message;
46import android.os.PowerManager;
47import android.os.PowerManager.WakeLock;
Ben Murdoch8029a772010-11-16 11:58:21 +000048import android.preference.PreferenceActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -070049import android.provider.Browser;
50import android.provider.BrowserContract;
Michael Kolb8233fac2010-10-26 16:08:53 -070051import android.provider.BrowserContract.Images;
52import android.provider.ContactsContract;
53import android.provider.ContactsContract.Intents.Insert;
Michael Kolbcfa3af52010-12-14 10:36:11 -080054import android.speech.RecognizerIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070055import android.text.TextUtils;
56import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080057import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070058import android.view.ActionMode;
59import android.view.ContextMenu;
60import android.view.ContextMenu.ContextMenuInfo;
61import android.view.Gravity;
62import android.view.KeyEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070063import android.view.Menu;
64import android.view.MenuInflater;
65import android.view.MenuItem;
66import android.view.MenuItem.OnMenuItemClickListener;
Michael Kolbc3af0672011-08-09 10:24:41 -070067import android.view.MotionEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070068import android.view.View;
69import android.webkit.CookieManager;
70import android.webkit.CookieSyncManager;
71import android.webkit.HttpAuthHandler;
George Mount387d45d2011-10-07 15:57:53 -070072import android.webkit.MimeTypeMap;
Michael Kolb8233fac2010-10-26 16:08:53 -070073import android.webkit.SslErrorHandler;
74import android.webkit.ValueCallback;
75import android.webkit.WebChromeClient;
76import android.webkit.WebIconDatabase;
77import android.webkit.WebSettings;
78import android.webkit.WebView;
Leon Scrogginsac993842011-02-02 12:54:07 -050079import android.widget.Toast;
Michael Kolb8233fac2010-10-26 16:08:53 -070080
Michael Kolb4bd767d2011-05-27 11:33:55 -070081import com.android.browser.IntentHandler.UrlData;
John Reck2bc80422011-06-30 15:11:49 -070082import com.android.browser.UI.ComboViews;
Michael Kolb4bd767d2011-05-27 11:33:55 -070083import com.android.browser.provider.BrowserProvider;
John Reck1cf4b792011-07-26 10:22:22 -070084import com.android.browser.provider.BrowserProvider2.Thumbnails;
John Reck8cc92352011-07-06 17:41:52 -070085import com.android.browser.provider.SnapshotProvider.Snapshots;
Michael Kolb4bd767d2011-05-27 11:33:55 -070086import com.android.browser.search.SearchEngine;
87import com.android.common.Search;
88
Michael Kolb8233fac2010-10-26 16:08:53 -070089import java.io.ByteArrayOutputStream;
George Mount387d45d2011-10-07 15:57:53 -070090import java.io.File;
91import java.io.FileOutputStream;
92import java.io.IOException;
Michael Kolb8233fac2010-10-26 16:08:53 -070093import java.net.URLEncoder;
George Mount387d45d2011-10-07 15:57:53 -070094import java.text.DateFormat;
95import java.text.SimpleDateFormat;
John Reck1cf4b792011-07-26 10:22:22 -070096import java.util.ArrayList;
Michael Kolb8233fac2010-10-26 16:08:53 -070097import java.util.Calendar;
George Mount387d45d2011-10-07 15:57:53 -070098import java.util.Date;
Michael Kolb8233fac2010-10-26 16:08:53 -070099import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -0800100import java.util.List;
John Reck26b18322011-06-21 13:08:58 -0700101import java.util.Map;
Michael Kolb8233fac2010-10-26 16:08:53 -0700102
103/**
104 * Controller for browser
105 */
106public class Controller
107 implements WebViewController, UiController {
108
109 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800110 private static final String SEND_APP_ID_EXTRA =
111 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
Michael Kolba4261fd2011-05-05 11:27:37 -0700112 private static final String INCOGNITO_URI = "browser:incognito";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800113
Michael Kolb8233fac2010-10-26 16:08:53 -0700114
115 // public message ids
116 public final static int LOAD_URL = 1001;
117 public final static int STOP_LOAD = 1002;
118
119 // Message Ids
120 private static final int FOCUS_NODE_HREF = 102;
121 private static final int RELEASE_WAKELOCK = 107;
122
123 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
124
125 private static final int OPEN_BOOKMARKS = 201;
126
127 private static final int EMPTY_MENU = -1;
128
Michael Kolb8233fac2010-10-26 16:08:53 -0700129 // activity requestCode
John Reckd3e4d5b2011-07-13 15:48:43 -0700130 final static int COMBO_VIEW = 1;
Michael Kolb8233fac2010-10-26 16:08:53 -0700131 final static int PREFERENCES_PAGE = 3;
132 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000133 final static int AUTOFILL_SETUP = 5;
134
Michael Kolb8233fac2010-10-26 16:08:53 -0700135 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
136
137 // As the ids are dynamically created, we can't guarantee that they will
138 // be in sequence, so this static array maps ids to a window number.
139 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
140 { R.id.window_one_menu_id, R.id.window_two_menu_id,
141 R.id.window_three_menu_id, R.id.window_four_menu_id,
142 R.id.window_five_menu_id, R.id.window_six_menu_id,
143 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
144
145 // "source" parameter for Google search through search key
146 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
147 // "source" parameter for Google search through simplily type
148 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
149
George Mount387d45d2011-10-07 15:57:53 -0700150 // "no-crash-recovery" parameter in intent to suppress crash recovery
Guang Zhu9e78f512011-05-04 11:45:11 -0700151 final static String NO_CRASH_RECOVERY = "no-crash-recovery";
152
John Reckd7dd9b22011-08-30 09:18:29 -0700153 // A bitmap that is re-used in createScreenshot as scratch space
154 private static Bitmap sThumbnailBitmap;
155
Michael Kolb8233fac2010-10-26 16:08:53 -0700156 private Activity mActivity;
157 private UI mUi;
158 private TabControl mTabControl;
159 private BrowserSettings mSettings;
160 private WebViewFactory mFactory;
161
162 private WakeLock mWakeLock;
163
164 private UrlHandler mUrlHandler;
165 private UploadHandler mUploadHandler;
166 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700167 private PageDialogsHandler mPageDialogsHandler;
168 private NetworkStateHandler mNetworkHandler;
169
Ben Murdoch8029a772010-11-16 11:58:21 +0000170 private Message mAutoFillSetupMessage;
171
Michael Kolb8233fac2010-10-26 16:08:53 -0700172 private boolean mShouldShowErrorConsole;
173
174 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
175
176 // FIXME, temp address onPrepareMenu performance problem.
177 // When we move everything out of view, we should rewrite this.
178 private int mCurrentMenuState = 0;
179 private int mMenuState = R.id.MAIN_MENU;
180 private int mOldMenuState = EMPTY_MENU;
181 private Menu mCachedMenu;
182
Michael Kolb8233fac2010-10-26 16:08:53 -0700183 private boolean mMenuIsDown;
184
185 // For select and find, we keep track of the ActionMode so that
186 // finish() can be called as desired.
187 private ActionMode mActionMode;
188
189 /**
190 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
191 * of whether the configuration has changed. The first onMenuOpened call
192 * after a configuration change is simply a reopening of the same menu
193 * (i.e. mIconView did not change).
194 */
195 private boolean mConfigChanged;
196
197 /**
198 * Keeps track of whether the options menu is open. This is important in
199 * determining whether to show or hide the title bar overlay
200 */
201 private boolean mOptionsMenuOpen;
202
203 /**
204 * Whether or not the options menu is in its bigger, popup menu form. When
205 * true, we want the title bar overlay to be gone. When false, we do not.
206 * Only meaningful if mOptionsMenuOpen is true.
207 */
208 private boolean mExtendedMenuOpen;
209
210 private boolean mInLoad;
211
212 private boolean mActivityPaused = true;
213 private boolean mLoadStopped;
214
215 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500216 // Checks to see when the bookmarks database has changed, and updates the
217 // Tabs' notion of whether they represent bookmarked sites.
218 private ContentObserver mBookmarksObserver;
John Reck847b5322011-04-14 17:02:18 -0700219 private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700220
Michael Kolbc3af0672011-08-09 10:24:41 -0700221 private boolean mBlockEvents;
222
George Mount3636d0a2011-11-21 09:08:21 -0800223 public Controller(Activity browser) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700224 mActivity = browser;
225 mSettings = BrowserSettings.getInstance();
226 mTabControl = new TabControl(this);
227 mSettings.setController(this);
John Reck378a4102011-06-09 16:23:01 -0700228 mCrashRecoveryHandler = CrashRecoveryHandler.initialize(this);
George Mount3636d0a2011-11-21 09:08:21 -0800229 mCrashRecoveryHandler.preloadCrashState();
Michael Kolb14612442011-06-24 13:06:29 -0700230 mFactory = new BrowserWebViewFactory(browser);
Michael Kolb8233fac2010-10-26 16:08:53 -0700231
232 mUrlHandler = new UrlHandler(this);
233 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700234 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
235
Michael Kolb8233fac2010-10-26 16:08:53 -0700236 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500237 mBookmarksObserver = new ContentObserver(mHandler) {
238 @Override
239 public void onChange(boolean selfChange) {
240 int size = mTabControl.getTabCount();
241 for (int i = 0; i < size; i++) {
242 mTabControl.getTab(i).updateBookmarkedStatus();
243 }
244 }
245
246 };
247 browser.getContentResolver().registerContentObserver(
248 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700249
250 mNetworkHandler = new NetworkStateHandler(mActivity, this);
251 // Start watching the default geolocation permissions
252 mSystemAllowGeolocationOrigins =
253 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
254 mSystemAllowGeolocationOrigins.start();
255
John Reckaf262e72011-07-25 13:55:44 -0700256 openIconDatabase();
Michael Kolb8233fac2010-10-26 16:08:53 -0700257 }
258
George Mount3636d0a2011-11-21 09:08:21 -0800259 void start(final Intent intent) {
260 // mCrashRecoverHandler has any previously saved state.
261 mCrashRecoveryHandler.startRecovery(intent);
John Reck847b5322011-04-14 17:02:18 -0700262 }
263
George Mount3636d0a2011-11-21 09:08:21 -0800264 void doStart(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700265 // Unless the last browser usage was within 24 hours, destroy any
266 // remaining incognito tabs.
267
268 Calendar lastActiveDate = icicle != null ?
269 (Calendar) icicle.getSerializable("lastActiveDate") : null;
270 Calendar today = Calendar.getInstance();
271 Calendar yesterday = Calendar.getInstance();
272 yesterday.add(Calendar.DATE, -1);
273
Patrick Scott7d50a932011-02-04 09:27:26 -0500274 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700275 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800276 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700277
Patrick Scott7d50a932011-02-04 09:27:26 -0500278 // Find out if we will restore any state and remember the tab.
Michael Kolbc831b632011-05-11 09:30:34 -0700279 final long currentTabId =
Patrick Scott7d50a932011-02-04 09:27:26 -0500280 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000281
Michael Kolbc831b632011-05-11 09:30:34 -0700282 if (currentTabId == -1) {
Patrick Scott7d50a932011-02-04 09:27:26 -0500283 // Not able to restore so we go ahead and clear session cookies. We
284 // must do this before trying to login the user as we don't want to
285 // clear any session cookies set during login.
286 CookieManager.getInstance().removeSessionCookie();
287 }
288
Patrick Scottd43e75a2011-03-14 14:47:23 -0400289 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500290 new Runnable() {
291 @Override public void run() {
George Mount3636d0a2011-11-21 09:08:21 -0800292 onPreloginFinished(icicle, intent, currentTabId,
293 restoreIncognitoTabs);
Patrick Scott7d50a932011-02-04 09:27:26 -0500294 }
295 });
296 }
297
Michael Kolbc831b632011-05-11 09:30:34 -0700298 private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId,
George Mount3636d0a2011-11-21 09:08:21 -0800299 boolean restoreIncognitoTabs) {
Michael Kolbc831b632011-05-11 09:30:34 -0700300 if (currentTabId == -1) {
John Reck1cf4b792011-07-26 10:22:22 -0700301 BackgroundHandler.execute(new PruneThumbnails(mActivity, null));
George Mount3636d0a2011-11-21 09:08:21 -0800302 if (intent == null) {
303 // This won't happen under common scenarios. The icicle is
304 // not null, but there aren't any tabs to restore.
305 openTabToHomePage();
Michael Kolb7bcafde2011-05-09 13:55:59 -0700306 } else {
George Mount3636d0a2011-11-21 09:08:21 -0800307 final Bundle extra = intent.getExtras();
308 // Create an initial tab.
309 // If the intent is ACTION_VIEW and data is not null, the Browser is
310 // invoked to view the content by another application. In this case,
311 // the tab will be close when exit.
312 UrlData urlData = IntentHandler.getUrlDataFromIntent(intent);
313 Tab t = null;
314 if (urlData.isEmpty()) {
315 t = openTabToHomePage();
316 } else {
317 t = openTab(urlData);
318 }
319 if (t != null) {
320 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
321 }
322 WebView webView = t.getWebView();
323 if (extra != null) {
324 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
325 if (scale > 0 && scale <= 1000) {
326 webView.setInitialScale(scale);
327 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700328 }
329 }
John Reckd8c74522011-06-14 08:45:00 -0700330 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700331 } else {
Michael Kolbc831b632011-05-11 09:30:34 -0700332 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
Patrick Scott7d50a932011-02-04 09:27:26 -0500333 mUi.needsRestoreAllTabs());
John Reck1cf4b792011-07-26 10:22:22 -0700334 List<Tab> tabs = mTabControl.getTabs();
335 ArrayList<Long> restoredTabs = new ArrayList<Long>(tabs.size());
336 for (Tab t : tabs) {
337 restoredTabs.add(t.getId());
338 }
339 BackgroundHandler.execute(new PruneThumbnails(mActivity, restoredTabs));
John Reck52be4782011-08-26 15:37:29 -0700340 if (tabs.size() == 0) {
341 openTabToHomePage();
342 }
John Reck1cf4b792011-07-26 10:22:22 -0700343 mUi.updateTabs(tabs);
Michael Kolb8233fac2010-10-26 16:08:53 -0700344 // TabControl.restoreState() will create a new tab even if
345 // restoring the state fails.
346 setActiveTab(mTabControl.getCurrentTab());
George Mount3636d0a2011-11-21 09:08:21 -0800347 // Intent is non-null when framework thinks the browser should be
348 // launching with a new intent (icicle is null).
349 if (intent != null) {
John Reck9dd4a412011-10-05 14:55:30 -0700350 mIntentHandler.onNewIntent(intent);
351 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700352 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700353 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700354 String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb8233fac2010-10-26 16:08:53 -0700355 if (jsFlags.trim().length() != 0) {
356 getCurrentWebView().setJsFlags(jsFlags);
357 }
George Mount3636d0a2011-11-21 09:08:21 -0800358 if (intent != null
359 && BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
Michael Kolb315d5022011-10-13 12:47:11 -0700360 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
John Reck439c9a52010-12-14 10:04:39 -0800361 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700362 }
363
John Reck1cf4b792011-07-26 10:22:22 -0700364 private static class PruneThumbnails implements Runnable {
365 private Context mContext;
366 private List<Long> mIds;
367
368 PruneThumbnails(Context context, List<Long> preserveIds) {
369 mContext = context.getApplicationContext();
370 mIds = preserveIds;
371 }
372
373 @Override
374 public void run() {
375 ContentResolver cr = mContext.getContentResolver();
376 if (mIds == null || mIds.size() == 0) {
377 cr.delete(Thumbnails.CONTENT_URI, null, null);
378 } else {
379 int length = mIds.size();
380 StringBuilder where = new StringBuilder();
381 where.append(Thumbnails._ID);
382 where.append(" not in (");
383 for (int i = 0; i < length; i++) {
384 where.append(mIds.get(i));
385 if (i < (length - 1)) {
386 where.append(",");
387 }
388 }
389 where.append(")");
390 cr.delete(Thumbnails.CONTENT_URI, where.toString(), null);
391 }
392 }
393
394 }
395
Michael Kolb1514bb72010-11-22 09:11:48 -0800396 @Override
397 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700398 return mFactory;
399 }
400
401 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800402 public void onSetWebView(Tab tab, WebView view) {
403 mUi.onSetWebView(tab, view);
404 }
405
406 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800407 public void createSubWindow(Tab tab) {
408 endActionMode();
409 WebView mainView = tab.getWebView();
410 WebView subView = mFactory.createWebView((mainView == null)
411 ? false
412 : mainView.isPrivateBrowsingEnabled());
413 mUi.createSubWindow(tab, subView);
414 }
415
416 @Override
Michael Kolb14612442011-06-24 13:06:29 -0700417 public Context getContext() {
418 return mActivity;
419 }
420
421 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700422 public Activity getActivity() {
423 return mActivity;
424 }
425
426 void setUi(UI ui) {
427 mUi = ui;
428 }
429
430 BrowserSettings getSettings() {
431 return mSettings;
432 }
433
434 IntentHandler getIntentHandler() {
435 return mIntentHandler;
436 }
437
438 @Override
439 public UI getUi() {
440 return mUi;
441 }
442
443 int getMaxTabs() {
444 return mActivity.getResources().getInteger(R.integer.max_tabs);
445 }
446
447 @Override
448 public TabControl getTabControl() {
449 return mTabControl;
450 }
451
Michael Kolb1bf23132010-11-19 12:55:12 -0800452 @Override
453 public List<Tab> getTabs() {
454 return mTabControl.getTabs();
455 }
456
John Reckaf262e72011-07-25 13:55:44 -0700457 // Open the icon database.
458 private void openIconDatabase() {
459 // We have to call getInstance on the UI thread
460 final WebIconDatabase instance = WebIconDatabase.getInstance();
461 BackgroundHandler.execute(new Runnable() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000462
John Reckaf262e72011-07-25 13:55:44 -0700463 @Override
464 public void run() {
465 instance.open(mActivity.getDir("icons", 0).getPath());
Michael Kolb8233fac2010-10-26 16:08:53 -0700466 }
John Reckaf262e72011-07-25 13:55:44 -0700467 });
Michael Kolb8233fac2010-10-26 16:08:53 -0700468 }
469
470 private void startHandler() {
471 mHandler = new Handler() {
472
473 @Override
474 public void handleMessage(Message msg) {
475 switch (msg.what) {
476 case OPEN_BOOKMARKS:
Michael Kolb315d5022011-10-13 12:47:11 -0700477 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
Michael Kolb8233fac2010-10-26 16:08:53 -0700478 break;
479 case FOCUS_NODE_HREF:
480 {
481 String url = (String) msg.getData().get("url");
482 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500483 String src = (String) msg.getData().get("src");
484 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700485 if (TextUtils.isEmpty(url)) {
486 break;
487 }
488 HashMap focusNodeMap = (HashMap) msg.obj;
489 WebView view = (WebView) focusNodeMap.get("webview");
490 // Only apply the action if the top window did not change.
491 if (getCurrentTopWebView() != view) {
492 break;
493 }
494 switch (msg.arg1) {
495 case R.id.open_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700496 loadUrlFromContext(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700497 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500498 case R.id.view_image_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700499 loadUrlFromContext(src);
Cary Clark043c2d62010-12-15 11:19:39 -0500500 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500501 case R.id.open_newtab_context_menu_id:
502 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -0700503 openTab(url, parent,
504 !mSettings.openInBackground(), true);
Leon Scroggins026f2542010-11-22 13:26:12 -0500505 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700506 case R.id.copy_link_context_menu_id:
507 copy(url);
508 break;
509 case R.id.save_link_context_menu_id:
510 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500511 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000512 mActivity, url, null, null, null,
513 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700514 break;
515 }
516 break;
517 }
518
519 case LOAD_URL:
John Reck26b18322011-06-21 13:08:58 -0700520 loadUrlFromContext((String) msg.obj);
Michael Kolb8233fac2010-10-26 16:08:53 -0700521 break;
522
523 case STOP_LOAD:
524 stopLoading();
525 break;
526
527 case RELEASE_WAKELOCK:
John Reckf57c0292011-07-21 18:15:39 -0700528 if (mWakeLock != null && mWakeLock.isHeld()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700529 mWakeLock.release();
530 // if we reach here, Browser should be still in the
531 // background loading after WAKELOCK_TIMEOUT (5-min).
532 // To avoid burning the battery, stop loading.
533 mTabControl.stopAllLoading();
534 }
535 break;
536
537 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800538 Tab tab = (Tab) msg.obj;
539 if (tab != null) {
540 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700541 }
542 break;
543 }
544 }
545 };
546
547 }
548
John Reckef654f12011-07-12 16:42:08 -0700549 @Override
Martijn Coenenb2f93552011-06-14 10:48:35 +0200550 public Tab getCurrentTab() {
551 return mTabControl.getCurrentTab();
552 }
553
Michael Kolbba99c5d2010-11-29 14:57:41 -0800554 @Override
555 public void shareCurrentPage() {
556 shareCurrentPage(mTabControl.getCurrentTab());
557 }
558
559 private void shareCurrentPage(Tab tab) {
560 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800561 sharePage(mActivity, tab.getTitle(),
562 tab.getUrl(), tab.getFavicon(),
563 createScreenshot(tab.getWebView(),
564 getDesiredThumbnailWidth(mActivity),
565 getDesiredThumbnailHeight(mActivity)));
566 }
567 }
568
Michael Kolb8233fac2010-10-26 16:08:53 -0700569 /**
570 * Share a page, providing the title, url, favicon, and a screenshot. Uses
571 * an {@link Intent} to launch the Activity chooser.
572 * @param c Context used to launch a new Activity.
573 * @param title Title of the page. Stored in the Intent with
574 * {@link Intent#EXTRA_SUBJECT}
575 * @param url URL of the page. Stored in the Intent with
576 * {@link Intent#EXTRA_TEXT}
577 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
578 * with {@link Browser#EXTRA_SHARE_FAVICON}
579 * @param screenshot Bitmap of a screenshot of the page. Stored in the
580 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
581 */
582 static final void sharePage(Context c, String title, String url,
583 Bitmap favicon, Bitmap screenshot) {
584 Intent send = new Intent(Intent.ACTION_SEND);
585 send.setType("text/plain");
586 send.putExtra(Intent.EXTRA_TEXT, url);
587 send.putExtra(Intent.EXTRA_SUBJECT, title);
588 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
589 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
590 try {
591 c.startActivity(Intent.createChooser(send, c.getString(
592 R.string.choosertitle_sharevia)));
593 } catch(android.content.ActivityNotFoundException ex) {
594 // if no app handles it, do nothing
595 }
596 }
597
598 private void copy(CharSequence text) {
599 ClipboardManager cm = (ClipboardManager) mActivity
600 .getSystemService(Context.CLIPBOARD_SERVICE);
601 cm.setText(text);
602 }
603
604 // lifecycle
605
606 protected void onConfgurationChanged(Configuration config) {
607 mConfigChanged = true;
608 if (mPageDialogsHandler != null) {
609 mPageDialogsHandler.onConfigurationChanged(config);
610 }
611 mUi.onConfigurationChanged(config);
612 }
613
614 @Override
615 public void handleNewIntent(Intent intent) {
Michael Kolb59e232c2011-08-18 17:19:53 -0700616 if (!mUi.isWebShowing()) {
617 mUi.showWeb(false);
618 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700619 mIntentHandler.onNewIntent(intent);
620 }
621
622 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800623 if (mUi.isCustomViewShowing()) {
624 hideCustomView();
625 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700626 if (mActivityPaused) {
627 Log.e(LOGTAG, "BrowserActivity is already paused.");
628 return;
629 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700630 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800631 Tab tab = mTabControl.getCurrentTab();
632 if (tab != null) {
633 tab.pause();
634 if (!pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700635 if (mWakeLock == null) {
636 PowerManager pm = (PowerManager) mActivity
637 .getSystemService(Context.POWER_SERVICE);
638 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
639 }
Michael Kolb70976932010-11-30 11:34:01 -0800640 mWakeLock.acquire();
641 mHandler.sendMessageDelayed(mHandler
642 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
643 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700644 }
645 mUi.onPause();
646 mNetworkHandler.onPause();
647
648 WebView.disablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100649 NfcHandler.unregister(mActivity);
John Reckd7dd9b22011-08-30 09:18:29 -0700650 if (sThumbnailBitmap != null) {
651 sThumbnailBitmap.recycle();
652 sThumbnailBitmap = null;
653 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700654 }
655
John Reck1cf4b792011-07-26 10:22:22 -0700656 void onSaveInstanceState(Bundle outState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700657 // Save all the tabs
George Mount3636d0a2011-11-21 09:08:21 -0800658 Bundle saveState = createSaveState();
659
660 // crash recovery manages all save & restore state
661 mCrashRecoveryHandler.writeState(saveState);
662 mSettings.setLastRunPaused(true);
663 }
664
665 /**
666 * Save the current state to outState. Does not write the state to
667 * disk.
668 * @return Bundle containing the current state of all tabs.
669 */
670 /* package */ Bundle createSaveState() {
671 Bundle saveState = new Bundle();
672 mTabControl.saveState(saveState);
673 if (!saveState.isEmpty()) {
John Reck24f18262011-06-17 14:47:20 -0700674 // Save time so that we know how old incognito tabs (if any) are.
George Mount3636d0a2011-11-21 09:08:21 -0800675 saveState.putSerializable("lastActiveDate", Calendar.getInstance());
John Reck24f18262011-06-17 14:47:20 -0700676 }
George Mount3636d0a2011-11-21 09:08:21 -0800677 return saveState;
Michael Kolb8233fac2010-10-26 16:08:53 -0700678 }
679
680 void onResume() {
681 if (!mActivityPaused) {
682 Log.e(LOGTAG, "BrowserActivity is already resumed.");
683 return;
684 }
George Mount3636d0a2011-11-21 09:08:21 -0800685 mSettings.setLastRunPaused(false);
Michael Kolb8233fac2010-10-26 16:08:53 -0700686 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800687 Tab current = mTabControl.getCurrentTab();
688 if (current != null) {
689 current.resume();
690 resumeWebViewTimers(current);
691 }
John Reckf57c0292011-07-21 18:15:39 -0700692 releaseWakeLock();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200693
Michael Kolb8233fac2010-10-26 16:08:53 -0700694 mUi.onResume();
695 mNetworkHandler.onResume();
696 WebView.enablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100697 NfcHandler.register(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700698 }
699
John Reckf57c0292011-07-21 18:15:39 -0700700 private void releaseWakeLock() {
701 if (mWakeLock != null && mWakeLock.isHeld()) {
702 mHandler.removeMessages(RELEASE_WAKELOCK);
703 mWakeLock.release();
704 }
705 }
706
Michael Kolb70976932010-11-30 11:34:01 -0800707 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800708 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800709 * @param tab guaranteed non-null
710 */
711 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700712 boolean inLoad = tab.inPageLoad();
713 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
714 CookieSyncManager.getInstance().startSync();
715 WebView w = tab.getWebView();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100716 WebViewTimersControl.getInstance().onBrowserActivityResume(w);
Michael Kolb8233fac2010-10-26 16:08:53 -0700717 }
718 }
719
Michael Kolb70976932010-11-30 11:34:01 -0800720 /**
721 * Pause all WebView timers using the WebView of the given tab
722 * @param tab
723 * @return true if the timers are paused or tab is null
724 */
725 private boolean pauseWebViewTimers(Tab tab) {
726 if (tab == null) {
727 return true;
728 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700729 CookieSyncManager.getInstance().stopSync();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100730 WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView());
Michael Kolb8233fac2010-10-26 16:08:53 -0700731 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700732 }
Michael Kolb70976932010-11-30 11:34:01 -0800733 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700734 }
735
736 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800737 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700738 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
739 mUploadHandler = null;
740 }
741 if (mTabControl == null) return;
742 mUi.onDestroy();
743 // Remove the current tab and sub window
744 Tab t = mTabControl.getCurrentTab();
745 if (t != null) {
746 dismissSubWindow(t);
747 removeTab(t);
748 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500749 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700750 // Destroy all the tabs
751 mTabControl.destroy();
752 WebIconDatabase.getInstance().close();
753 // Stop watching the default geolocation permissions
754 mSystemAllowGeolocationOrigins.stop();
755 mSystemAllowGeolocationOrigins = null;
756 }
757
758 protected boolean isActivityPaused() {
759 return mActivityPaused;
760 }
761
762 protected void onLowMemory() {
763 mTabControl.freeMemory();
764 }
765
766 @Override
767 public boolean shouldShowErrorConsole() {
768 return mShouldShowErrorConsole;
769 }
770
771 protected void setShouldShowErrorConsole(boolean show) {
772 if (show == mShouldShowErrorConsole) {
773 // Nothing to do.
774 return;
775 }
776 mShouldShowErrorConsole = show;
777 Tab t = mTabControl.getCurrentTab();
778 if (t == null) {
779 // There is no current tab so we cannot toggle the error console
780 return;
781 }
782 mUi.setShouldShowErrorConsole(t, show);
783 }
784
785 @Override
786 public void stopLoading() {
787 mLoadStopped = true;
788 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700789 WebView w = getCurrentTopWebView();
790 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700791 mUi.onPageStopped(tab);
792 }
793
794 boolean didUserStopLoading() {
795 return mLoadStopped;
796 }
797
798 // WebViewController
799
800 @Override
John Reck324d4402011-01-11 16:56:42 -0800801 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700802
803 // We've started to load a new page. If there was a pending message
804 // to save a screenshot then we will now take the new page and save
805 // an incorrect screenshot. Therefore, remove any pending thumbnail
806 // messages from the queue.
807 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800808 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700809
810 // reset sync timer to avoid sync starts during loading a page
811 CookieSyncManager.getInstance().resetSync();
812
813 if (!mNetworkHandler.isNetworkUp()) {
814 view.setNetworkAvailable(false);
815 }
816
817 // when BrowserActivity just starts, onPageStarted may be called before
818 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
819 // to start the timer. As we won't switch tabs while an activity is in
820 // pause state, we can ensure calling resume and pause in pair.
821 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800822 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700823 }
824 mLoadStopped = false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700825 endActionMode();
826
John Reck30c714c2010-12-16 17:30:34 -0800827 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700828
John Reck324d4402011-01-11 16:56:42 -0800829 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700830 // update the bookmark database for favicon
831 maybeUpdateFavicon(tab, null, url, favicon);
832
833 Performance.tracePageStart(url);
834
835 // Performance probe
836 if (false) {
837 Performance.onPageStarted();
838 }
839
840 }
841
842 @Override
John Reck324d4402011-01-11 16:56:42 -0800843 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800844 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800845 if (!tab.isPrivateBrowsingEnabled()
John Reckd8c74522011-06-14 08:45:00 -0700846 && !TextUtils.isEmpty(tab.getUrl())
847 && !tab.isSnapshot()) {
John Recka1696282011-07-08 14:10:37 -0700848 // Only update the bookmark screenshot if the user did not
849 // cancel the load early and there is not already
850 // a pending update for the tab.
Michael Kolb8233fac2010-10-26 16:08:53 -0700851 if (tab.inForeground() && !didUserStopLoading()
852 || !tab.inForeground()) {
John Recka1696282011-07-08 14:10:37 -0700853 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
854 mHandler.sendMessageDelayed(mHandler.obtainMessage(
855 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
856 500);
857 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700858 }
859 }
860 // pause the WebView timer and release the wake lock if it is finished
861 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800862 if (mActivityPaused && pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700863 releaseWakeLock();
Michael Kolb8233fac2010-10-26 16:08:53 -0700864 }
Martijn Coenenb2f93552011-06-14 10:48:35 +0200865
Michael Kolb8233fac2010-10-26 16:08:53 -0700866 // Performance probe
867 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800868 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700869 }
870
871 Performance.tracePageFinished();
872 }
873
874 @Override
John Reck30c714c2010-12-16 17:30:34 -0800875 public void onProgressChanged(Tab tab) {
John Reck6c2e2f32011-08-22 13:41:23 -0700876 mCrashRecoveryHandler.backupState();
John Reck30c714c2010-12-16 17:30:34 -0800877 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700878
879 if (newProgress == 100) {
880 CookieSyncManager.getInstance().sync();
881 // onProgressChanged() may continue to be called after the main
882 // frame has finished loading, as any remaining sub frames continue
883 // to load. We'll only get called once though with newProgress as
884 // 100 when everything is loaded. (onPageFinished is called once
885 // when the main frame completes loading regardless of the state of
886 // any sub frames so calls to onProgressChanges may continue after
887 // onPageFinished has executed)
888 if (mInLoad) {
889 mInLoad = false;
890 updateInLoadMenuItems(mCachedMenu);
891 }
892 } else {
893 if (!mInLoad) {
894 // onPageFinished may have already been called but a subframe is
895 // still loading and updating the progress. Reset mInLoad and
896 // update the menu items.
897 mInLoad = true;
898 updateInLoadMenuItems(mCachedMenu);
899 }
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();
1299 menu.setGroupVisible(R.id.PHONE_MENU,
1300 type == WebView.HitTestResult.PHONE_TYPE);
1301 menu.setGroupVisible(R.id.EMAIL_MENU,
1302 type == WebView.HitTestResult.EMAIL_TYPE);
1303 menu.setGroupVisible(R.id.GEO_MENU,
1304 type == WebView.HitTestResult.GEO_TYPE);
1305 menu.setGroupVisible(R.id.IMAGE_MENU,
1306 type == WebView.HitTestResult.IMAGE_TYPE
1307 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1308 menu.setGroupVisible(R.id.ANCHOR_MENU,
1309 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1310 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001311 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1312 || type == WebView.HitTestResult.PHONE_TYPE
1313 || type == WebView.HitTestResult.EMAIL_TYPE
1314 || type == WebView.HitTestResult.GEO_TYPE;
1315 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1316 if (hitText) {
1317 menu.findItem(R.id.select_text_menu_id)
1318 .setOnMenuItemClickListener(new SelectText(webview));
1319 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001320 // Setup custom handling depending on the type
1321 switch (type) {
1322 case WebView.HitTestResult.PHONE_TYPE:
1323 menu.setHeaderTitle(Uri.decode(extra));
1324 menu.findItem(R.id.dial_context_menu_id).setIntent(
1325 new Intent(Intent.ACTION_VIEW, Uri
1326 .parse(WebView.SCHEME_TEL + extra)));
1327 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1328 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1329 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1330 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1331 addIntent);
1332 menu.findItem(R.id.copy_phone_context_menu_id)
1333 .setOnMenuItemClickListener(
1334 new Copy(extra));
1335 break;
1336
1337 case WebView.HitTestResult.EMAIL_TYPE:
1338 menu.setHeaderTitle(extra);
1339 menu.findItem(R.id.email_context_menu_id).setIntent(
1340 new Intent(Intent.ACTION_VIEW, Uri
1341 .parse(WebView.SCHEME_MAILTO + extra)));
1342 menu.findItem(R.id.copy_mail_context_menu_id)
1343 .setOnMenuItemClickListener(
1344 new Copy(extra));
1345 break;
1346
1347 case WebView.HitTestResult.GEO_TYPE:
1348 menu.setHeaderTitle(extra);
1349 menu.findItem(R.id.map_context_menu_id).setIntent(
1350 new Intent(Intent.ACTION_VIEW, Uri
1351 .parse(WebView.SCHEME_GEO
1352 + URLEncoder.encode(extra))));
1353 menu.findItem(R.id.copy_geo_context_menu_id)
1354 .setOnMenuItemClickListener(
1355 new Copy(extra));
1356 break;
1357
1358 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1359 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001360 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001361 // decide whether to show the open link in new tab option
1362 boolean showNewTab = mTabControl.canCreateNewTab();
1363 MenuItem newTabItem
1364 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001365 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001366 ? R.string.contextmenu_openlink_newwindow_background
1367 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001368 newTabItem.setVisible(showNewTab);
1369 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001370 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1371 newTabItem.setOnMenuItemClickListener(
1372 new MenuItem.OnMenuItemClickListener() {
1373 @Override
1374 public boolean onMenuItemClick(MenuItem item) {
1375 final HashMap<String, WebView> hrefMap =
1376 new HashMap<String, WebView>();
1377 hrefMap.put("webview", webview);
1378 final Message msg = mHandler.obtainMessage(
1379 FOCUS_NODE_HREF,
1380 R.id.open_newtab_context_menu_id,
1381 0, hrefMap);
1382 webview.requestFocusNodeHref(msg);
1383 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001384 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001385 });
1386 } else {
1387 newTabItem.setOnMenuItemClickListener(
1388 new MenuItem.OnMenuItemClickListener() {
1389 @Override
1390 public boolean onMenuItemClick(MenuItem item) {
1391 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001392 openTab(extra, parent,
1393 !mSettings.openInBackground(),
1394 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001395 return true;
1396 }
1397 });
1398 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001399 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001400 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1401 break;
1402 }
1403 // otherwise fall through to handle image part
1404 case WebView.HitTestResult.IMAGE_TYPE:
1405 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1406 menu.setHeaderTitle(extra);
1407 }
Michael Kolb3639c4c2011-09-28 15:36:40 -07001408 menu.findItem(R.id.view_image_context_menu_id)
1409 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1410 @Override
1411 public boolean onMenuItemClick(MenuItem item) {
1412 openTab(extra, mTabControl.getCurrentTab(), true, true);
1413 return false;
1414 }
1415 });
Michael Kolb8233fac2010-10-26 16:08:53 -07001416 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001417 setOnMenuItemClickListener(
1418 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001419 menu.findItem(R.id.set_wallpaper_context_menu_id).
1420 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1421 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001422 break;
1423
1424 default:
1425 Log.w(LOGTAG, "We should not get here.");
1426 break;
1427 }
1428 //update the ui
1429 mUi.onContextMenuCreated(menu);
1430 }
1431
1432 /**
1433 * As the menu can be open when loading state changes
1434 * we must manually update the state of the stop/reload menu
1435 * item
1436 */
1437 private void updateInLoadMenuItems(Menu menu) {
1438 if (menu == null) {
1439 return;
1440 }
1441 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1442 MenuItem src = mInLoad ?
1443 menu.findItem(R.id.stop_menu_id):
1444 menu.findItem(R.id.reload_menu_id);
1445 if (src != null) {
1446 dest.setIcon(src.getIcon());
1447 dest.setTitle(src.getTitle());
1448 }
1449 }
1450
John Reckb3417f02011-01-14 11:01:05 -08001451 boolean onPrepareOptionsMenu(Menu menu) {
John Recke1a03a32011-09-14 17:04:16 -07001452 updateInLoadMenuItems(menu);
1453 // hold on to the menu reference here; it is used by the page callbacks
1454 // to update the menu based on loading state
1455 mCachedMenu = menu;
Michael Kolb8233fac2010-10-26 16:08:53 -07001456 // Note: setVisible will decide whether an item is visible; while
1457 // setEnabled() will decide whether an item is enabled, which also means
1458 // whether the matching shortcut key will function.
1459 switch (mMenuState) {
1460 case EMPTY_MENU:
1461 if (mCurrentMenuState != mMenuState) {
1462 menu.setGroupVisible(R.id.MAIN_MENU, false);
1463 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1464 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1465 }
1466 break;
1467 default:
1468 if (mCurrentMenuState != mMenuState) {
1469 menu.setGroupVisible(R.id.MAIN_MENU, true);
1470 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1471 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1472 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001473 updateMenuState(getCurrentTab(), menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001474 break;
1475 }
1476 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001477 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001478 }
1479
Michael Kolb4bf79712011-07-14 14:18:12 -07001480 @Override
1481 public void updateMenuState(Tab tab, Menu menu) {
1482 boolean canGoBack = false;
1483 boolean canGoForward = false;
1484 boolean isHome = false;
John Reck42229bc2011-08-19 13:26:43 -07001485 boolean isDesktopUa = false;
John Recke1a03a32011-09-14 17:04:16 -07001486 boolean isLive = false;
Michael Kolb4bf79712011-07-14 14:18:12 -07001487 if (tab != null) {
1488 canGoBack = tab.canGoBack();
1489 canGoForward = tab.canGoForward();
1490 isHome = mSettings.getHomePage().equals(tab.getUrl());
John Reck42229bc2011-08-19 13:26:43 -07001491 isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
John Recke1a03a32011-09-14 17:04:16 -07001492 isLive = !tab.isSnapshot();
Michael Kolb4bf79712011-07-14 14:18:12 -07001493 }
1494 final MenuItem back = menu.findItem(R.id.back_menu_id);
1495 back.setEnabled(canGoBack);
1496
1497 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1498 home.setEnabled(!isHome);
1499
1500 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1501 forward.setEnabled(canGoForward);
1502
1503 final MenuItem source = menu.findItem(mInLoad ? R.id.stop_menu_id : R.id.reload_menu_id);
1504 final MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolb7ab75ee2011-07-14 16:36:38 -07001505 if (source != null && dest != null) {
1506 dest.setTitle(source.getTitle());
1507 dest.setIcon(source.getIcon());
1508 }
John Recke1a03a32011-09-14 17:04:16 -07001509 menu.setGroupVisible(R.id.NAV_MENU, isLive);
Michael Kolb4bf79712011-07-14 14:18:12 -07001510
1511 // decide whether to show the share link option
1512 PackageManager pm = mActivity.getPackageManager();
1513 Intent send = new Intent(Intent.ACTION_SEND);
1514 send.setType("text/plain");
1515 ResolveInfo ri = pm.resolveActivity(send,
1516 PackageManager.MATCH_DEFAULT_ONLY);
1517 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1518
1519 boolean isNavDump = mSettings.enableNavDump();
1520 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1521 nav.setVisible(isNavDump);
1522 nav.setEnabled(isNavDump);
1523
1524 boolean showDebugSettings = mSettings.isDebugEnabled();
John Reck42229bc2011-08-19 13:26:43 -07001525 final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
1526 uaSwitcher.setChecked(isDesktopUa);
John Recke1a03a32011-09-14 17:04:16 -07001527 menu.setGroupVisible(R.id.LIVE_MENU, isLive);
1528 menu.setGroupVisible(R.id.SNAPSHOT_MENU, !isLive);
Michael Kolb315d5022011-10-13 12:47:11 -07001529 menu.setGroupVisible(R.id.COMBO_MENU, false);
Michael Kolb4bf79712011-07-14 14:18:12 -07001530
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001531 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001532 }
1533
Michael Kolb8233fac2010-10-26 16:08:53 -07001534 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001535 if (null == getCurrentTopWebView()) {
1536 return false;
1537 }
1538 if (mMenuIsDown) {
1539 // The shortcut action consumes the MENU. Even if it is still down,
1540 // it won't trigger the next shortcut action. In the case of the
1541 // shortcut action triggering a new activity, like Bookmarks, we
1542 // won't get onKeyUp for MENU. So it is important to reset it here.
1543 mMenuIsDown = false;
1544 }
Michael Kolb3ca12752011-07-20 13:52:25 -07001545 if (mUi.onOptionsItemSelected(item)) {
1546 // ui callback handled it
1547 return true;
1548 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001549 switch (item.getItemId()) {
1550 // -- Main menu
1551 case R.id.new_tab_menu_id:
1552 openTabToHomePage();
1553 break;
1554
1555 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001556 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001557 break;
1558
1559 case R.id.goto_menu_id:
1560 editUrl();
1561 break;
1562
1563 case R.id.bookmarks_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001564 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
1565 break;
1566
1567 case R.id.history_menu_id:
1568 bookmarksOrHistoryPicker(ComboViews.History);
1569 break;
1570
1571 case R.id.snapshots_menu_id:
1572 bookmarksOrHistoryPicker(ComboViews.Snapshots);
Michael Kolb8233fac2010-10-26 16:08:53 -07001573 break;
1574
Michael Kolb8233fac2010-10-26 16:08:53 -07001575 case R.id.add_bookmark_menu_id:
John Recka60fffa2011-09-06 16:30:29 -07001576 Intent bookmarkIntent = createBookmarkCurrentPageIntent(false);
1577 if (bookmarkIntent != null) {
1578 mActivity.startActivity(bookmarkIntent);
1579 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001580 break;
1581
1582 case R.id.stop_reload_menu_id:
1583 if (mInLoad) {
1584 stopLoading();
1585 } else {
1586 getCurrentTopWebView().reload();
1587 }
1588 break;
1589
1590 case R.id.back_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001591 getCurrentTab().goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07001592 break;
1593
1594 case R.id.forward_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001595 getCurrentTab().goForward();
Michael Kolb8233fac2010-10-26 16:08:53 -07001596 break;
1597
1598 case R.id.close_menu_id:
1599 // Close the subwindow if it exists.
1600 if (mTabControl.getCurrentSubWindow() != null) {
1601 dismissSubWindow(mTabControl.getCurrentTab());
1602 break;
1603 }
1604 closeCurrentTab();
1605 break;
1606
1607 case R.id.homepage_menu_id:
1608 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07001609 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07001610 break;
1611
1612 case R.id.preferences_menu_id:
1613 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1614 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1615 getCurrentTopWebView().getUrl());
1616 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1617 break;
1618
1619 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001620 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001621 break;
1622
John Reck2bc80422011-06-30 15:11:49 -07001623 case R.id.save_snapshot_menu_id:
1624 final Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07001625 if (source == null) break;
John Reckd8c74522011-06-14 08:45:00 -07001626 final ContentResolver cr = mActivity.getContentResolver();
1627 final ContentValues values = source.createSnapshotValues();
John Reck2bc80422011-06-30 15:11:49 -07001628 if (values != null) {
1629 new AsyncTask<Tab, Void, Long>() {
John Reckd8c74522011-06-14 08:45:00 -07001630
John Reck2bc80422011-06-30 15:11:49 -07001631 @Override
1632 protected Long doInBackground(Tab... params) {
1633 Uri result = cr.insert(Snapshots.CONTENT_URI, values);
John Reck93384ff2011-11-10 11:29:18 -08001634 if (result == null) {
1635 return null;
1636 }
John Reck2bc80422011-06-30 15:11:49 -07001637 long id = ContentUris.parseId(result);
1638 return id;
John Reckd8c74522011-06-14 08:45:00 -07001639 }
John Reckf33b1632011-06-04 20:00:23 -07001640
John Reck2bc80422011-06-30 15:11:49 -07001641 @Override
1642 protected void onPostExecute(Long id) {
John Reck93384ff2011-11-10 11:29:18 -08001643 if (id == null) {
1644 Toast.makeText(mActivity, R.string.snapshot_failed,
1645 Toast.LENGTH_SHORT).show();
1646 return;
1647 }
John Reck2bc80422011-06-30 15:11:49 -07001648 Bundle b = new Bundle();
1649 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
1650 mUi.showComboView(ComboViews.Snapshots, b);
1651 };
1652 }.execute(source);
1653 } else {
1654 Toast.makeText(mActivity, R.string.snapshot_failed,
Leon Scrogginsac993842011-02-02 12:54:07 -05001655 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001656 }
Leon Scrogginsac993842011-02-02 12:54:07 -05001657 break;
1658
Michael Kolb8233fac2010-10-26 16:08:53 -07001659 case R.id.page_info_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001660 showPageInfo();
Michael Kolb8233fac2010-10-26 16:08:53 -07001661 break;
1662
John Recke1a03a32011-09-14 17:04:16 -07001663 case R.id.snapshot_go_live:
1664 goLive();
1665 return true;
1666
Michael Kolb8233fac2010-10-26 16:08:53 -07001667 case R.id.share_page_menu_id:
1668 Tab currentTab = mTabControl.getCurrentTab();
1669 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001670 return false;
1671 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001672 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001673 break;
1674
1675 case R.id.dump_nav_menu_id:
1676 getCurrentTopWebView().debugDump();
1677 break;
1678
Michael Kolb8233fac2010-10-26 16:08:53 -07001679 case R.id.zoom_in_menu_id:
1680 getCurrentTopWebView().zoomIn();
1681 break;
1682
1683 case R.id.zoom_out_menu_id:
1684 getCurrentTopWebView().zoomOut();
1685 break;
1686
1687 case R.id.view_downloads_menu_id:
1688 viewDownloads();
1689 break;
1690
John Reck42229bc2011-08-19 13:26:43 -07001691 case R.id.ua_desktop_menu_id:
1692 WebView web = getCurrentWebView();
1693 mSettings.toggleDesktopUseragent(web);
1694 web.loadUrl(web.getOriginalUrl());
1695 break;
1696
Michael Kolb8233fac2010-10-26 16:08:53 -07001697 case R.id.window_one_menu_id:
1698 case R.id.window_two_menu_id:
1699 case R.id.window_three_menu_id:
1700 case R.id.window_four_menu_id:
1701 case R.id.window_five_menu_id:
1702 case R.id.window_six_menu_id:
1703 case R.id.window_seven_menu_id:
1704 case R.id.window_eight_menu_id:
1705 {
1706 int menuid = item.getItemId();
1707 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1708 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1709 Tab desiredTab = mTabControl.getTab(id);
1710 if (desiredTab != null &&
1711 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001712 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001713 }
1714 break;
1715 }
1716 }
1717 }
1718 break;
1719
1720 default:
1721 return false;
1722 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001723 return true;
1724 }
1725
John Recke1a03a32011-09-14 17:04:16 -07001726 private void goLive() {
1727 Tab t = getCurrentTab();
1728 t.loadUrl(t.getUrl(), null);
1729 }
1730
Michael Kolb315d5022011-10-13 12:47:11 -07001731 @Override
1732 public void showPageInfo() {
1733 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
1734 }
1735
Michael Kolb8233fac2010-10-26 16:08:53 -07001736 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001737 // Let the History and Bookmark fragments handle menus they created.
1738 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1739 return false;
1740 }
1741
Michael Kolb8233fac2010-10-26 16:08:53 -07001742 int id = item.getItemId();
1743 boolean result = true;
1744 switch (id) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001745 // -- Browser context menu
1746 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001747 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001748 case R.id.copy_link_context_menu_id:
1749 final WebView webView = getCurrentTopWebView();
1750 if (null == webView) {
1751 result = false;
1752 break;
1753 }
1754 final HashMap<String, WebView> hrefMap =
1755 new HashMap<String, WebView>();
1756 hrefMap.put("webview", webView);
1757 final Message msg = mHandler.obtainMessage(
1758 FOCUS_NODE_HREF, id, 0, hrefMap);
1759 webView.requestFocusNodeHref(msg);
1760 break;
1761
1762 default:
1763 // For other context menus
1764 result = onOptionsItemSelected(item);
1765 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001766 return result;
1767 }
1768
1769 /**
1770 * support programmatically opening the context menu
1771 */
1772 public void openContextMenu(View view) {
1773 mActivity.openContextMenu(view);
1774 }
1775
1776 /**
1777 * programmatically open the options menu
1778 */
1779 public void openOptionsMenu() {
1780 mActivity.openOptionsMenu();
1781 }
1782
1783 public boolean onMenuOpened(int featureId, Menu menu) {
1784 if (mOptionsMenuOpen) {
1785 if (mConfigChanged) {
1786 // We do not need to make any changes to the state of the
1787 // title bar, since the only thing that happened was a
1788 // change in orientation
1789 mConfigChanged = false;
1790 } else {
1791 if (!mExtendedMenuOpen) {
1792 mExtendedMenuOpen = true;
1793 mUi.onExtendedMenuOpened();
1794 } else {
1795 // Switching the menu back to icon view, so show the
1796 // title bar once again.
1797 mExtendedMenuOpen = false;
1798 mUi.onExtendedMenuClosed(mInLoad);
Michael Kolb8233fac2010-10-26 16:08:53 -07001799 }
1800 }
1801 } else {
1802 // The options menu is closed, so open it, and show the title
1803 mOptionsMenuOpen = true;
1804 mConfigChanged = false;
1805 mExtendedMenuOpen = false;
1806 mUi.onOptionsMenuOpened();
1807 }
1808 return true;
1809 }
1810
1811 public void onOptionsMenuClosed(Menu menu) {
1812 mOptionsMenuOpen = false;
1813 mUi.onOptionsMenuClosed(mInLoad);
1814 }
1815
1816 public void onContextMenuClosed(Menu menu) {
1817 mUi.onContextMenuClosed(menu, mInLoad);
1818 }
1819
1820 // Helper method for getting the top window.
1821 @Override
1822 public WebView getCurrentTopWebView() {
1823 return mTabControl.getCurrentTopWebView();
1824 }
1825
1826 @Override
1827 public WebView getCurrentWebView() {
1828 return mTabControl.getCurrentWebView();
1829 }
1830
1831 /*
1832 * This method is called as a result of the user selecting the options
1833 * menu to see the download window. It shows the download window on top of
1834 * the current window.
1835 */
1836 void viewDownloads() {
1837 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1838 mActivity.startActivity(intent);
1839 }
1840
John Reck30b065e2011-07-19 10:58:05 -07001841 int getActionModeHeight() {
1842 TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
1843 new int[] { android.R.attr.actionBarSize });
1844 int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
1845 actionBarSizeTypedArray.recycle();
1846 return size;
1847 }
1848
Michael Kolb8233fac2010-10-26 16:08:53 -07001849 // action mode
1850
1851 void onActionModeStarted(ActionMode mode) {
1852 mUi.onActionModeStarted(mode);
1853 mActionMode = mode;
1854 }
1855
1856 /*
1857 * True if a custom ActionMode (i.e. find or select) is in use.
1858 */
1859 @Override
1860 public boolean isInCustomActionMode() {
1861 return mActionMode != null;
1862 }
1863
1864 /*
1865 * End the current ActionMode.
1866 */
1867 @Override
1868 public void endActionMode() {
1869 if (mActionMode != null) {
1870 mActionMode.finish();
1871 }
1872 }
1873
1874 /*
1875 * Called by find and select when they are finished. Replace title bars
1876 * as necessary.
1877 */
1878 public void onActionModeFinished(ActionMode mode) {
1879 if (!isInCustomActionMode()) return;
1880 mUi.onActionModeFinished(mInLoad);
1881 mActionMode = null;
1882 }
1883
1884 boolean isInLoad() {
1885 return mInLoad;
1886 }
1887
1888 // bookmark handling
1889
1890 /**
1891 * add the current page as a bookmark to the given folder id
1892 * @param folderId use -1 for the default folder
John Reckd3e4d5b2011-07-13 15:48:43 -07001893 * @param editExisting If true, check to see whether the site is already
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001894 * bookmarked, and if it is, edit that bookmark. If false, and
1895 * the site is already bookmarked, do not attempt to edit the
1896 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001897 */
1898 @Override
John Reckd3e4d5b2011-07-13 15:48:43 -07001899 public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
John Recka60fffa2011-09-06 16:30:29 -07001900 WebView w = getCurrentTopWebView();
1901 if (w == null) {
1902 return null;
1903 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001904 Intent i = new Intent(mActivity,
1905 AddBookmarkPage.class);
Michael Kolb8233fac2010-10-26 16:08:53 -07001906 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1907 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1908 String touchIconUrl = w.getTouchIconUrl();
1909 if (touchIconUrl != null) {
1910 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1911 WebSettings settings = w.getSettings();
1912 if (settings != null) {
1913 i.putExtra(AddBookmarkPage.USER_AGENT,
1914 settings.getUserAgentString());
1915 }
1916 }
1917 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1918 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1919 getDesiredThumbnailHeight(mActivity)));
1920 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07001921 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001922 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1923 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001924 // Put the dialog at the upper right of the screen, covering the
1925 // star on the title bar.
1926 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07001927 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07001928 }
1929
1930 // file chooser
1931 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1932 mUploadHandler = new UploadHandler(this);
1933 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1934 }
1935
1936 // thumbnails
1937
1938 /**
1939 * Return the desired width for thumbnail screenshots, which are stored in
1940 * the database, and used on the bookmarks screen.
1941 * @param context Context for finding out the density of the screen.
1942 * @return desired width for thumbnail screenshot.
1943 */
1944 static int getDesiredThumbnailWidth(Context context) {
1945 return context.getResources().getDimensionPixelOffset(
1946 R.dimen.bookmarkThumbnailWidth);
1947 }
1948
1949 /**
1950 * Return the desired height for thumbnail screenshots, which are stored in
1951 * the database, and used on the bookmarks screen.
1952 * @param context Context for finding out the density of the screen.
1953 * @return desired height for thumbnail screenshot.
1954 */
1955 static int getDesiredThumbnailHeight(Context context) {
1956 return context.getResources().getDimensionPixelOffset(
1957 R.dimen.bookmarkThumbnailHeight);
1958 }
1959
John Reck8cc92352011-07-06 17:41:52 -07001960 static Bitmap createScreenshot(WebView view, int width, int height) {
John Reckd7dd9b22011-08-30 09:18:29 -07001961 if (view == null || view.getContentHeight() == 0
1962 || view.getContentWidth() == 0) {
1963 return null;
1964 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001965 // We render to a bitmap 2x the desired size so that we can then
1966 // re-scale it with filtering since canvas.scale doesn't filter
1967 // This helps reduce aliasing at the cost of being slightly blurry
1968 final int filter_scale = 2;
John Reckd7dd9b22011-08-30 09:18:29 -07001969 int scaledWidth = width * filter_scale;
1970 int scaledHeight = height * filter_scale;
1971 if (sThumbnailBitmap == null || sThumbnailBitmap.getWidth() != scaledWidth
1972 || sThumbnailBitmap.getHeight() != scaledHeight) {
1973 if (sThumbnailBitmap != null) {
1974 sThumbnailBitmap.recycle();
1975 sThumbnailBitmap = null;
1976 }
1977 sThumbnailBitmap =
1978 Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.RGB_565);
Michael Kolb8233fac2010-10-26 16:08:53 -07001979 }
John Reckd7dd9b22011-08-30 09:18:29 -07001980 Canvas canvas = new Canvas(sThumbnailBitmap);
1981 int contentWidth = view.getContentWidth();
1982 float overviewScale = scaledWidth / (view.getScale() * contentWidth);
1983 if (view instanceof BrowserWebView) {
1984 int dy = -((BrowserWebView)view).getTitleHeight();
1985 canvas.translate(0, dy * overviewScale);
1986 }
1987
1988 canvas.scale(overviewScale, overviewScale);
1989
1990 if (view instanceof BrowserWebView) {
1991 ((BrowserWebView)view).drawContent(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07001992 } else {
John Reckd7dd9b22011-08-30 09:18:29 -07001993 view.draw(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07001994 }
John Reckd7dd9b22011-08-30 09:18:29 -07001995 Bitmap ret = Bitmap.createScaledBitmap(sThumbnailBitmap,
1996 width, height, true);
Dianne Hackborn43cfe8a2011-08-02 16:59:35 -07001997 canvas.setBitmap(null);
John Reck5c6ac2f2011-01-05 10:18:03 -08001998 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001999 }
2000
John Reck34ef2672011-02-10 11:30:55 -08002001 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002002 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07002003 // FIXME: Would like to make sure there is actually something to
2004 // draw, but the API for that (WebViewCore.pictureReady()) is not
2005 // currently accessible here.
2006
John Reck34ef2672011-02-10 11:30:55 -08002007 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08002008 if (view == null) {
2009 // Tab was destroyed
2010 return;
2011 }
John Reck34ef2672011-02-10 11:30:55 -08002012 final String url = tab.getUrl();
2013 final String originalUrl = view.getOriginalUrl();
2014
2015 if (TextUtils.isEmpty(url)) {
2016 return;
2017 }
2018
2019 // Only update thumbnails for web urls (http(s)://), not for
2020 // about:, javascript:, data:, etc...
2021 // Unless it is a bookmarked site, then always update
2022 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2023 return;
2024 }
2025
Michael Kolb8233fac2010-10-26 16:08:53 -07002026 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2027 getDesiredThumbnailHeight(mActivity));
2028 if (bm == null) {
2029 return;
2030 }
2031
2032 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002033 new AsyncTask<Void, Void, Void>() {
2034 @Override
2035 protected Void doInBackground(Void... unused) {
2036 Cursor cursor = null;
2037 try {
2038 // TODO: Clean this up
2039 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2040 if (cursor != null && cursor.moveToFirst()) {
2041 final ByteArrayOutputStream os =
2042 new ByteArrayOutputStream();
2043 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002044
John Reck34ef2672011-02-10 11:30:55 -08002045 ContentValues values = new ContentValues();
2046 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002047
John Reck34ef2672011-02-10 11:30:55 -08002048 do {
John Reck617fd832011-02-16 14:35:59 -08002049 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002050 cr.update(Images.CONTENT_URI, values, null, null);
2051 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002052 }
John Reck34ef2672011-02-10 11:30:55 -08002053 } catch (IllegalStateException e) {
2054 // Ignore
2055 } finally {
2056 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002057 }
John Reck34ef2672011-02-10 11:30:55 -08002058 return null;
2059 }
2060 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002061 }
2062
2063 private class Copy implements OnMenuItemClickListener {
2064 private CharSequence mText;
2065
2066 public boolean onMenuItemClick(MenuItem item) {
2067 copy(mText);
2068 return true;
2069 }
2070
2071 public Copy(CharSequence toCopy) {
2072 mText = toCopy;
2073 }
2074 }
2075
Leon Scroggins63c02662010-11-18 15:16:27 -05002076 private static class Download implements OnMenuItemClickListener {
2077 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002078 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002079 private boolean mPrivateBrowsing;
George Mount387d45d2011-10-07 15:57:53 -07002080 private static final String FALLBACK_EXTENSION = "dat";
2081 private static final String IMAGE_BASE_FORMAT = "yyyy-MM-dd-HH-mm-ss-";
Michael Kolb8233fac2010-10-26 16:08:53 -07002082
2083 public boolean onMenuItemClick(MenuItem item) {
George Mount387d45d2011-10-07 15:57:53 -07002084 if (DataUri.isDataUri(mText)) {
2085 saveDataUri();
2086 } else {
2087 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
2088 null, null, mPrivateBrowsing);
2089 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002090 return true;
2091 }
2092
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002093 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002094 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002095 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002096 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002097 }
George Mount387d45d2011-10-07 15:57:53 -07002098
2099 /**
2100 * Treats mText as a data URI and writes its contents to a file
2101 * based on the current time.
2102 */
2103 private void saveDataUri() {
2104 FileOutputStream outputStream = null;
2105 try {
2106 DataUri uri = new DataUri(mText);
2107 File target = getTarget(uri);
2108 outputStream = new FileOutputStream(target);
2109 outputStream.write(uri.getData());
2110 final DownloadManager manager =
2111 (DownloadManager) mActivity.getSystemService(Context.DOWNLOAD_SERVICE);
2112 manager.addCompletedDownload(target.getName(),
2113 mActivity.getTitle().toString(), false,
2114 uri.getMimeType(), target.getAbsolutePath(),
George Mount7501bf42011-11-17 11:17:03 -08002115 (long)uri.getData().length, true);
George Mount387d45d2011-10-07 15:57:53 -07002116 } catch (IOException e) {
2117 Log.e(LOGTAG, "Could not save data URL");
2118 } finally {
2119 if (outputStream != null) {
2120 try {
2121 outputStream.close();
2122 } catch (IOException e) {
2123 // ignore close errors
2124 }
2125 }
2126 }
2127 }
2128
2129 /**
2130 * Creates a File based on the current time stamp and uses
2131 * the mime type of the DataUri to get the extension.
2132 */
2133 private File getTarget(DataUri uri) throws IOException {
2134 File dir = mActivity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
2135 DateFormat format = new SimpleDateFormat(IMAGE_BASE_FORMAT);
2136 String nameBase = format.format(new Date());
2137 String mimeType = uri.getMimeType();
2138 MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
2139 String extension = mimeTypeMap.getExtensionFromMimeType(mimeType);
2140 if (extension == null) {
2141 Log.w(LOGTAG, "Unknown mime type in data URI" + mimeType);
2142 extension = FALLBACK_EXTENSION;
2143 }
2144 extension = "." + extension; // createTempFile needs the '.'
2145 File targetFile = File.createTempFile(nameBase, extension, dir);
2146 return targetFile;
2147 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002148 }
2149
Cary Clark8974d282010-11-22 10:46:05 -05002150 private static class SelectText implements OnMenuItemClickListener {
2151 private WebView mWebView;
2152
2153 public boolean onMenuItemClick(MenuItem item) {
2154 if (mWebView != null) {
2155 return mWebView.selectText();
2156 }
2157 return false;
2158 }
2159
2160 public SelectText(WebView webView) {
2161 mWebView = webView;
2162 }
2163
2164 }
2165
Michael Kolb8233fac2010-10-26 16:08:53 -07002166 /********************** TODO: UI stuff *****************************/
2167
2168 // these methods have been copied, they still need to be cleaned up
2169
2170 /****************** tabs ***************************************************/
2171
2172 // basic tab interactions:
2173
2174 // it is assumed that tabcontrol already knows about the tab
2175 protected void addTab(Tab tab) {
2176 mUi.addTab(tab);
2177 }
2178
2179 protected void removeTab(Tab tab) {
2180 mUi.removeTab(tab);
2181 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002182 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002183 }
2184
Michael Kolbf2055602011-04-09 17:20:03 -07002185 @Override
2186 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002187 // monkey protection against delayed start
2188 if (tab != null) {
2189 mTabControl.setCurrentTab(tab);
2190 // the tab is guaranteed to have a webview after setCurrentTab
2191 mUi.setActiveTab(tab);
2192 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002193 }
2194
John Reck8bcafc12011-08-29 16:43:02 -07002195 protected void closeEmptyTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002196 Tab current = mTabControl.getCurrentTab();
2197 if (current != null
2198 && current.getWebView().copyBackForwardList().getSize() == 0) {
John Reck8bcafc12011-08-29 16:43:02 -07002199 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002200 }
2201 }
2202
John Reck26b18322011-06-21 13:08:58 -07002203 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002204 // Dismiss the subwindow if applicable.
2205 dismissSubWindow(appTab);
2206 // Since we might kill the WebView, remove it from the
2207 // content view first.
2208 mUi.detachTab(appTab);
2209 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002210 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002211 // TODO: analyze why the remove and add are necessary
2212 mUi.attachTab(appTab);
2213 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002214 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002215 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002216 } else {
2217 // If the tab was the current tab, we have to attach
2218 // it to the view system again.
2219 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002220 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002221 }
2222 }
2223
2224 // Remove the sub window if it exists. Also called by TabControl when the
2225 // user clicks the 'X' to dismiss a sub window.
2226 public void dismissSubWindow(Tab tab) {
2227 removeSubWindow(tab);
2228 // dismiss the subwindow. This will destroy the WebView.
2229 tab.dismissSubWindow();
2230 getCurrentTopWebView().requestFocus();
2231 }
2232
2233 @Override
2234 public void removeSubWindow(Tab t) {
2235 if (t.getSubWebView() != null) {
2236 mUi.removeSubWindow(t.getSubViewContainer());
2237 }
2238 }
2239
2240 @Override
2241 public void attachSubWindow(Tab tab) {
2242 if (tab.getSubWebView() != null) {
2243 mUi.attachSubWindow(tab.getSubViewContainer());
2244 getCurrentTopWebView().requestFocus();
2245 }
2246 }
2247
Mathew Inwood29721c22011-06-29 17:55:24 +01002248 private Tab showPreloadedTab(final UrlData urlData) {
2249 if (!urlData.isPreloaded()) {
2250 return null;
2251 }
2252 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2253 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2254 if (sbQuery != null) {
Mathew Inwood9ad1eac2011-09-15 11:29:50 +01002255 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002256 // Could not submit query. Fallback to regular tab creation
2257 tabControl.destroy();
2258 return null;
2259 }
2260 }
Michael Kolbff6a7482011-07-26 16:37:15 -07002261 // check tab count and make room for new tab
2262 if (!mTabControl.canCreateNewTab()) {
2263 Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
2264 if (leastUsed != null) {
2265 closeTab(leastUsed);
2266 }
2267 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002268 Tab t = tabControl.getTab();
Mathew Inwoode09305e2011-09-02 12:03:26 +01002269 t.refreshIdAfterPreload();
Mathew Inwood29721c22011-06-29 17:55:24 +01002270 mTabControl.addPreloadedTab(t);
2271 addTab(t);
2272 setActiveTab(t);
2273 return t;
2274 }
2275
Michael Kolb7bcafde2011-05-09 13:55:59 -07002276 // open a non inconito tab with the given url data
2277 // and set as active tab
2278 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002279 Tab tab = showPreloadedTab(urlData);
2280 if (tab == null) {
2281 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002282 if ((tab != null) && !urlData.isEmpty()) {
2283 loadUrlDataIn(tab, urlData);
2284 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002285 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002286 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002287 }
2288
Michael Kolb843510f2010-12-09 10:51:49 -08002289 @Override
2290 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002291 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002292 }
2293
Michael Kolb8233fac2010-10-26 16:08:53 -07002294 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002295 public Tab openIncognitoTab() {
2296 return openTab(INCOGNITO_URI, true, true, false);
2297 }
2298
2299 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002300 public Tab openTab(String url, boolean incognito, boolean setActive,
2301 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002302 return openTab(url, incognito, setActive, useCurrent, null);
2303 }
2304
2305 @Override
2306 public Tab openTab(String url, Tab parent, boolean setActive,
2307 boolean useCurrent) {
2308 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2309 setActive, useCurrent, parent);
2310 }
2311
2312 public Tab openTab(String url, boolean incognito, boolean setActive,
2313 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002314 Tab tab = createNewTab(incognito, setActive, useCurrent);
2315 if (tab != null) {
John Reck5949c662011-05-27 09:52:29 -07002316 if (parent != null && parent != tab) {
2317 parent.addChildTab(tab);
2318 }
Michael Kolb519d2282011-05-09 17:03:19 -07002319 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002320 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002321 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002322 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002323 return tab;
2324 }
2325
2326 // this method will attempt to create a new tab
2327 // incognito: private browsing tab
2328 // setActive: ste tab as current tab
2329 // useCurrent: if no new tab can be created, return current tab
2330 private Tab createNewTab(boolean incognito, boolean setActive,
2331 boolean useCurrent) {
2332 Tab tab = null;
2333 if (mTabControl.canCreateNewTab()) {
2334 tab = mTabControl.createNewTab(incognito);
2335 addTab(tab);
2336 if (setActive) {
2337 setActiveTab(tab);
2338 }
2339 } else {
2340 if (useCurrent) {
2341 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002342 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002343 } else {
2344 mUi.showMaxTabsWarning();
2345 }
2346 }
2347 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002348 }
2349
John Reck2bc80422011-06-30 15:11:49 -07002350 @Override
2351 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2352 SnapshotTab tab = null;
2353 if (mTabControl.canCreateNewTab()) {
2354 tab = mTabControl.createSnapshotTab(snapshotId);
2355 addTab(tab);
2356 if (setActive) {
2357 setActiveTab(tab);
2358 }
2359 } else {
2360 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07002361 }
2362 return tab;
2363 }
2364
Michael Kolb8233fac2010-10-26 16:08:53 -07002365 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002366 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002367 * @return boolean True if we successfully switched to a different tab. If
2368 * the indexth tab is null, or if that tab is the same as
2369 * the current one, return false.
2370 */
2371 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002372 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002373 Tab currentTab = mTabControl.getCurrentTab();
2374 if (tab == null || tab == currentTab) {
2375 return false;
2376 }
2377 setActiveTab(tab);
2378 return true;
2379 }
2380
2381 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002382 public void closeCurrentTab() {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002383 closeCurrentTab(false);
2384 }
2385
2386 protected void closeCurrentTab(boolean andQuit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002387 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07002388 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07002389 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08002390 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002391 return;
2392 }
Michael Kolbc831b632011-05-11 09:30:34 -07002393 final Tab current = mTabControl.getCurrentTab();
2394 final int pos = mTabControl.getCurrentPosition();
2395 Tab newTab = current.getParent();
2396 if (newTab == null) {
2397 newTab = mTabControl.getTab(pos + 1);
2398 if (newTab == null) {
2399 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002400 }
2401 }
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002402 if (andQuit) {
2403 mTabControl.setCurrentTab(newTab);
2404 closeTab(current);
2405 } else if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002406 // Close window
2407 closeTab(current);
2408 }
2409 }
2410
2411 /**
2412 * Close the tab, remove its associated title bar, and adjust mTabControl's
2413 * current tab to a valid value.
2414 */
2415 @Override
2416 public void closeTab(Tab tab) {
John Reck28263772011-10-11 17:13:42 -07002417 if (tab == mTabControl.getCurrentTab()) {
2418 closeCurrentTab();
2419 } else {
2420 removeTab(tab);
2421 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002422 }
2423
Michael Kolb8233fac2010-10-26 16:08:53 -07002424 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07002425 protected void loadUrlFromContext(String url) {
2426 Tab tab = getCurrentTab();
2427 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002428 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07002429 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002430 url = UrlUtils.smartUrlFilter(url);
2431 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07002432 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07002433 }
2434 }
2435 }
2436
2437 /**
2438 * Load the URL into the given WebView and update the title bar
2439 * to reflect the new load. Call this instead of WebView.loadUrl
2440 * directly.
2441 * @param view The WebView used to load url.
2442 * @param url The URL to load.
2443 */
John Reck71e51422011-07-01 16:49:28 -07002444 @Override
2445 public void loadUrl(Tab tab, String url) {
John Reck26b18322011-06-21 13:08:58 -07002446 loadUrl(tab, url, null);
2447 }
2448
2449 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
2450 if (tab != null) {
2451 dismissSubWindow(tab);
2452 tab.loadUrl(url, headers);
Michael Kolba53c9892011-10-05 13:31:40 -07002453 mUi.onProgressChanged(tab);
John Reck26b18322011-06-21 13:08:58 -07002454 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002455 }
2456
2457 /**
2458 * Load UrlData into a Tab and update the title bar to reflect the new
2459 * load. Call this instead of UrlData.loadIn directly.
2460 * @param t The Tab used to load.
2461 * @param data The UrlData being loaded.
2462 */
2463 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07002464 if (data != null) {
2465 if (data.mVoiceIntent != null) {
2466 t.activateVoiceSearchMode(data.mVoiceIntent);
Michael Kolb14612442011-06-24 13:06:29 -07002467 } else if (data.isPreloaded()) {
2468 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07002469 } else {
2470 loadUrl(t, data.mUrl, data.mHeaders);
2471 }
2472 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002473 }
2474
John Reck30c714c2010-12-16 17:30:34 -08002475 @Override
2476 public void onUserCanceledSsl(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08002477 // TODO: Figure out the "right" behavior
John Reckef654f12011-07-12 16:42:08 -07002478 if (tab.canGoBack()) {
2479 tab.goBack();
John Reck30c714c2010-12-16 17:30:34 -08002480 } else {
John Reckef654f12011-07-12 16:42:08 -07002481 tab.loadUrl(mSettings.getHomePage(), null);
John Reck30c714c2010-12-16 17:30:34 -08002482 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002483 }
2484
2485 void goBackOnePageOrQuit() {
2486 Tab current = mTabControl.getCurrentTab();
2487 if (current == null) {
2488 /*
2489 * Instead of finishing the activity, simply push this to the back
2490 * of the stack and let ActivityManager to choose the foreground
2491 * activity. As BrowserActivity is singleTask, it will be always the
2492 * root of the task. So we can use either true or false for
2493 * moveTaskToBack().
2494 */
2495 mActivity.moveTaskToBack(true);
2496 return;
2497 }
John Reckef654f12011-07-12 16:42:08 -07002498 if (current.canGoBack()) {
2499 current.goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07002500 } else {
2501 // Check to see if we are closing a window that was created by
2502 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002503 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002504 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002505 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002506 // Now we close the other tab
2507 closeTab(current);
2508 } else {
Michael Kolbe28b3472011-08-04 16:54:31 -07002509 if ((current.getAppId() != null) || current.closeOnBack()) {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002510 closeCurrentTab(true);
Michael Kolbe28b3472011-08-04 16:54:31 -07002511 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002512 /*
2513 * Instead of finishing the activity, simply push this to the back
2514 * of the stack and let ActivityManager to choose the foreground
2515 * activity. As BrowserActivity is singleTask, it will be always the
2516 * root of the task. So we can use either true or false for
2517 * moveTaskToBack().
2518 */
2519 mActivity.moveTaskToBack(true);
2520 }
2521 }
2522 }
2523
2524 /**
2525 * Feed the previously stored results strings to the BrowserProvider so that
2526 * the SearchDialog will show them instead of the standard searches.
2527 * @param result String to show on the editable line of the SearchDialog.
2528 */
2529 @Override
2530 public void showVoiceSearchResults(String result) {
2531 ContentProviderClient client = mActivity.getContentResolver()
2532 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2533 ContentProvider prov = client.getLocalContentProvider();
2534 BrowserProvider bp = (BrowserProvider) prov;
2535 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2536 client.release();
2537
2538 Bundle bundle = createGoogleSearchSourceBundle(
2539 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2540 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2541 startSearch(result, false, bundle, false);
2542 }
2543
2544 private void startSearch(String initialQuery, boolean selectInitialQuery,
2545 Bundle appSearchData, boolean globalSearch) {
2546 if (appSearchData == null) {
2547 appSearchData = createGoogleSearchSourceBundle(
2548 GOOGLE_SEARCH_SOURCE_TYPE);
2549 }
2550
2551 SearchEngine searchEngine = mSettings.getSearchEngine();
2552 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2553 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2554 }
2555 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2556 globalSearch);
2557 }
2558
2559 private Bundle createGoogleSearchSourceBundle(String source) {
2560 Bundle bundle = new Bundle();
2561 bundle.putString(Search.SOURCE, source);
2562 return bundle;
2563 }
2564
2565 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002566 * helper method for key handler
2567 * returns the current tab if it can't advance
2568 */
Michael Kolbc831b632011-05-11 09:30:34 -07002569 private Tab getNextTab() {
2570 return mTabControl.getTab(Math.min(mTabControl.getTabCount() - 1,
2571 mTabControl.getCurrentPosition() + 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002572 }
2573
2574 /**
2575 * helper method for key handler
2576 * returns the current tab if it can't advance
2577 */
Michael Kolbc831b632011-05-11 09:30:34 -07002578 private Tab getPrevTab() {
2579 return mTabControl.getTab(Math.max(0,
2580 mTabControl.getCurrentPosition() - 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002581 }
2582
2583 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002584 * handle key events in browser
2585 *
2586 * @param keyCode
2587 * @param event
2588 * @return true if handled, false to pass to super
2589 */
2590 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002591 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002592 // Even if MENU is already held down, we need to call to super to open
2593 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002594 if (!noModifiers
2595 && ((KeyEvent.KEYCODE_MENU == keyCode)
2596 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2597 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002598 mMenuIsDown = true;
2599 return false;
2600 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002601
Cary Clark8ff8c662010-12-29 15:03:05 -05002602 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07002603 Tab tab = getCurrentTab();
2604 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05002605
Cary Clark160bbb92011-01-10 11:17:07 -05002606 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2607 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002608
Michael Kolb8233fac2010-10-26 16:08:53 -07002609 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002610 case KeyEvent.KEYCODE_TAB:
2611 if (event.isCtrlPressed()) {
2612 if (event.isShiftPressed()) {
2613 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002614 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002615 } else {
2616 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002617 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002618 }
2619 return true;
2620 }
2621 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002622 case KeyEvent.KEYCODE_SPACE:
2623 // WebView/WebTextView handle the keys in the KeyDown. As
2624 // the Activity's shortcut keys are only handled when WebView
2625 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002626 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002627 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002628 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002629 pageDown();
2630 }
2631 return true;
2632 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002633 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002634 event.startTracking();
2635 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07002636 case KeyEvent.KEYCODE_FORWARD:
2637 if (!noModifiers) break;
2638 tab.goForward();
2639 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002640 case KeyEvent.KEYCODE_DPAD_LEFT:
2641 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002642 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05002643 return true;
2644 }
2645 break;
2646 case KeyEvent.KEYCODE_DPAD_RIGHT:
2647 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002648 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05002649 return true;
2650 }
2651 break;
2652 case KeyEvent.KEYCODE_A:
2653 if (ctrl) {
2654 webView.selectAll();
2655 return true;
2656 }
2657 break;
Michael Kolba4183062011-01-16 10:43:21 -08002658// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002659 case KeyEvent.KEYCODE_C:
2660 if (ctrl) {
2661 webView.copySelection();
2662 return true;
2663 }
2664 break;
Michael Kolba4183062011-01-16 10:43:21 -08002665// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002666// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002667// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002668// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002669// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002670// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002671// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002672// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002673// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002674// case KeyEvent.KEYCODE_M: // unused
2675// case KeyEvent.KEYCODE_N: // in Chrome: new window
2676// case KeyEvent.KEYCODE_O: // in Chrome: open file
2677// case KeyEvent.KEYCODE_P: // in Chrome: print page
2678// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002679// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002680// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2681 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002682 // we can't use the ctrl/shift flags, they check for
2683 // exclusive use of a modifier
2684 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002685 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002686 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002687 } else {
2688 openTabToHomePage();
2689 }
2690 return true;
2691 }
2692 break;
2693// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2694// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb5ae15bd2011-08-16 17:09:27 -07002695// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002696// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2697// case KeyEvent.KEYCODE_Y: // unused
2698// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002699 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002700 // it is a regular key and webview is not null
2701 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002702 }
2703
John Recke6bf4ab2011-02-24 15:48:05 -08002704 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2705 switch(keyCode) {
2706 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07002707 if (mUi.isWebShowing()) {
Michael Kolb315d5022011-10-13 12:47:11 -07002708 bookmarksOrHistoryPicker(ComboViews.History);
John Recke6bf4ab2011-02-24 15:48:05 -08002709 return true;
2710 }
2711 break;
2712 }
2713 return false;
2714 }
2715
Michael Kolb8233fac2010-10-26 16:08:53 -07002716 boolean onKeyUp(int keyCode, KeyEvent event) {
Michael Kolb2814a362011-05-19 15:49:41 -07002717 if (KeyEvent.KEYCODE_MENU == keyCode) {
2718 mMenuIsDown = false;
2719 if (event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002720 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002721 }
2722 }
Cary Clark160bbb92011-01-10 11:17:07 -05002723 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002724 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002725 case KeyEvent.KEYCODE_BACK:
2726 if (event.isTracking() && !event.isCanceled()) {
2727 onBackKey();
2728 return true;
2729 }
2730 break;
2731 }
2732 return false;
2733 }
2734
2735 public boolean isMenuDown() {
2736 return mMenuIsDown;
2737 }
2738
Ben Murdoch8029a772010-11-16 11:58:21 +00002739 public void setupAutoFill(Message message) {
2740 // Open the settings activity at the AutoFill profile fragment so that
2741 // the user can create a new profile. When they return, we will dispatch
2742 // the message so that we can autofill the form using their new profile.
2743 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2744 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2745 AutoFillSettingsFragment.class.getName());
2746 mAutoFillSetupMessage = message;
2747 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2748 }
John Reckb3417f02011-01-14 11:01:05 -08002749
Michael Kolbfbc579a2011-07-07 15:59:33 -07002750 public boolean onSearchRequested() {
2751 mUi.editUrl(false);
2752 return true;
2753 }
2754
John Reck1cf4b792011-07-26 10:22:22 -07002755 @Override
2756 public boolean shouldCaptureThumbnails() {
2757 return mUi.shouldCaptureThumbnails();
2758 }
2759
Michael Kolbc3af0672011-08-09 10:24:41 -07002760 @Override
2761 public void setBlockEvents(boolean block) {
2762 mBlockEvents = block;
2763 }
2764
2765 public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002766 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002767 }
2768
2769 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002770 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002771 }
2772
2773 public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002774 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002775 }
2776
2777 public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002778 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002779 }
2780
2781 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002782 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002783 }
2784
Michael Kolb8233fac2010-10-26 16:08:53 -07002785}