blob: 600554711a1ab00cb52da986bb7e07b5e66f2e87 [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.UI.DropdownChangeListener;
84import com.android.browser.provider.BrowserProvider;
John Reck1cf4b792011-07-26 10:22:22 -070085import com.android.browser.provider.BrowserProvider2.Thumbnails;
John Reck8cc92352011-07-06 17:41:52 -070086import com.android.browser.provider.SnapshotProvider.Snapshots;
Michael Kolb4bd767d2011-05-27 11:33:55 -070087import com.android.browser.search.SearchEngine;
88import com.android.common.Search;
89
Michael Kolb8233fac2010-10-26 16:08:53 -070090import java.io.ByteArrayOutputStream;
George Mount387d45d2011-10-07 15:57:53 -070091import java.io.File;
92import java.io.FileOutputStream;
93import java.io.IOException;
Michael Kolb8233fac2010-10-26 16:08:53 -070094import java.net.URLEncoder;
George Mount387d45d2011-10-07 15:57:53 -070095import java.text.DateFormat;
96import java.text.SimpleDateFormat;
John Reck1cf4b792011-07-26 10:22:22 -070097import java.util.ArrayList;
Michael Kolb8233fac2010-10-26 16:08:53 -070098import java.util.Calendar;
George Mount387d45d2011-10-07 15:57:53 -070099import java.util.Date;
Michael Kolb8233fac2010-10-26 16:08:53 -0700100import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -0800101import java.util.List;
John Reck26b18322011-06-21 13:08:58 -0700102import java.util.Map;
Michael Kolb8233fac2010-10-26 16:08:53 -0700103
104/**
105 * Controller for browser
106 */
107public class Controller
108 implements WebViewController, UiController {
109
110 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800111 private static final String SEND_APP_ID_EXTRA =
112 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
Michael Kolba4261fd2011-05-05 11:27:37 -0700113 private static final String INCOGNITO_URI = "browser:incognito";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800114
Michael Kolb8233fac2010-10-26 16:08:53 -0700115
116 // public message ids
117 public final static int LOAD_URL = 1001;
118 public final static int STOP_LOAD = 1002;
119
120 // Message Ids
121 private static final int FOCUS_NODE_HREF = 102;
122 private static final int RELEASE_WAKELOCK = 107;
123
124 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
125
126 private static final int OPEN_BOOKMARKS = 201;
127
128 private static final int EMPTY_MENU = -1;
129
Michael Kolb8233fac2010-10-26 16:08:53 -0700130 // activity requestCode
John Reckd3e4d5b2011-07-13 15:48:43 -0700131 final static int COMBO_VIEW = 1;
Michael Kolb8233fac2010-10-26 16:08:53 -0700132 final static int PREFERENCES_PAGE = 3;
133 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000134 final static int AUTOFILL_SETUP = 5;
135
Michael Kolb8233fac2010-10-26 16:08:53 -0700136 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
137
138 // As the ids are dynamically created, we can't guarantee that they will
139 // be in sequence, so this static array maps ids to a window number.
140 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
141 { R.id.window_one_menu_id, R.id.window_two_menu_id,
142 R.id.window_three_menu_id, R.id.window_four_menu_id,
143 R.id.window_five_menu_id, R.id.window_six_menu_id,
144 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
145
146 // "source" parameter for Google search through search key
147 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
148 // "source" parameter for Google search through simplily type
149 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
150
George Mount387d45d2011-10-07 15:57:53 -0700151 // "no-crash-recovery" parameter in intent to suppress crash recovery
Guang Zhu9e78f512011-05-04 11:45:11 -0700152 final static String NO_CRASH_RECOVERY = "no-crash-recovery";
153
John Reckd7dd9b22011-08-30 09:18:29 -0700154 // A bitmap that is re-used in createScreenshot as scratch space
155 private static Bitmap sThumbnailBitmap;
156
Michael Kolb8233fac2010-10-26 16:08:53 -0700157 private Activity mActivity;
158 private UI mUi;
159 private TabControl mTabControl;
160 private BrowserSettings mSettings;
161 private WebViewFactory mFactory;
162
163 private WakeLock mWakeLock;
164
165 private UrlHandler mUrlHandler;
166 private UploadHandler mUploadHandler;
167 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700168 private PageDialogsHandler mPageDialogsHandler;
169 private NetworkStateHandler mNetworkHandler;
170
Ben Murdoch8029a772010-11-16 11:58:21 +0000171 private Message mAutoFillSetupMessage;
172
Michael Kolb8233fac2010-10-26 16:08:53 -0700173 private boolean mShouldShowErrorConsole;
174
175 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
176
177 // FIXME, temp address onPrepareMenu performance problem.
178 // When we move everything out of view, we should rewrite this.
179 private int mCurrentMenuState = 0;
180 private int mMenuState = R.id.MAIN_MENU;
181 private int mOldMenuState = EMPTY_MENU;
182 private Menu mCachedMenu;
183
Michael Kolb8233fac2010-10-26 16:08:53 -0700184 private boolean mMenuIsDown;
185
186 // For select and find, we keep track of the ActionMode so that
187 // finish() can be called as desired.
188 private ActionMode mActionMode;
189
190 /**
191 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
192 * of whether the configuration has changed. The first onMenuOpened call
193 * after a configuration change is simply a reopening of the same menu
194 * (i.e. mIconView did not change).
195 */
196 private boolean mConfigChanged;
197
198 /**
199 * Keeps track of whether the options menu is open. This is important in
200 * determining whether to show or hide the title bar overlay
201 */
202 private boolean mOptionsMenuOpen;
203
204 /**
205 * Whether or not the options menu is in its bigger, popup menu form. When
206 * true, we want the title bar overlay to be gone. When false, we do not.
207 * Only meaningful if mOptionsMenuOpen is true.
208 */
209 private boolean mExtendedMenuOpen;
210
211 private boolean mInLoad;
212
213 private boolean mActivityPaused = true;
214 private boolean mLoadStopped;
215
216 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500217 // Checks to see when the bookmarks database has changed, and updates the
218 // Tabs' notion of whether they represent bookmarked sites.
219 private ContentObserver mBookmarksObserver;
John Reck847b5322011-04-14 17:02:18 -0700220 private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700221
Michael Kolbc3af0672011-08-09 10:24:41 -0700222 private boolean mBlockEvents;
223
John Reckbc490d22011-07-22 15:04:59 -0700224 public Controller(Activity browser, boolean preloadCrashState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700225 mActivity = browser;
226 mSettings = BrowserSettings.getInstance();
227 mTabControl = new TabControl(this);
228 mSettings.setController(this);
John Reck378a4102011-06-09 16:23:01 -0700229 mCrashRecoveryHandler = CrashRecoveryHandler.initialize(this);
John Reckbc490d22011-07-22 15:04:59 -0700230 if (preloadCrashState) {
231 mCrashRecoveryHandler.preloadCrashState();
232 }
Michael Kolb14612442011-06-24 13:06:29 -0700233 mFactory = new BrowserWebViewFactory(browser);
Michael Kolb8233fac2010-10-26 16:08:53 -0700234
235 mUrlHandler = new UrlHandler(this);
236 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700237 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
238
Michael Kolb8233fac2010-10-26 16:08:53 -0700239 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500240 mBookmarksObserver = new ContentObserver(mHandler) {
241 @Override
242 public void onChange(boolean selfChange) {
243 int size = mTabControl.getTabCount();
244 for (int i = 0; i < size; i++) {
245 mTabControl.getTab(i).updateBookmarkedStatus();
246 }
247 }
248
249 };
250 browser.getContentResolver().registerContentObserver(
251 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700252
253 mNetworkHandler = new NetworkStateHandler(mActivity, this);
254 // Start watching the default geolocation permissions
255 mSystemAllowGeolocationOrigins =
256 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
257 mSystemAllowGeolocationOrigins.start();
258
John Reckaf262e72011-07-25 13:55:44 -0700259 openIconDatabase();
Michael Kolb8233fac2010-10-26 16:08:53 -0700260 }
261
Patrick Scott7d50a932011-02-04 09:27:26 -0500262 void start(final Bundle icicle, final Intent intent) {
Guang Zhu9e78f512011-05-04 11:45:11 -0700263 boolean noCrashRecovery = intent.getBooleanExtra(NO_CRASH_RECOVERY, false);
264 if (icicle != null || noCrashRecovery) {
Michael Kolb938db802011-10-11 10:49:05 -0700265 doStart(icicle, intent, false);
John Reck847b5322011-04-14 17:02:18 -0700266 } else {
267 mCrashRecoveryHandler.startRecovery(intent);
268 }
269 }
270
Michael Kolb938db802011-10-11 10:49:05 -0700271 void doStart(final Bundle icicle, final Intent intent, final boolean fromCrash) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700272 // Unless the last browser usage was within 24 hours, destroy any
273 // remaining incognito tabs.
274
275 Calendar lastActiveDate = icicle != null ?
276 (Calendar) icicle.getSerializable("lastActiveDate") : null;
277 Calendar today = Calendar.getInstance();
278 Calendar yesterday = Calendar.getInstance();
279 yesterday.add(Calendar.DATE, -1);
280
Patrick Scott7d50a932011-02-04 09:27:26 -0500281 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700282 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800283 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700284
Patrick Scott7d50a932011-02-04 09:27:26 -0500285 // Find out if we will restore any state and remember the tab.
Michael Kolbc831b632011-05-11 09:30:34 -0700286 final long currentTabId =
Patrick Scott7d50a932011-02-04 09:27:26 -0500287 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000288
Michael Kolbc831b632011-05-11 09:30:34 -0700289 if (currentTabId == -1) {
Patrick Scott7d50a932011-02-04 09:27:26 -0500290 // Not able to restore so we go ahead and clear session cookies. We
291 // must do this before trying to login the user as we don't want to
292 // clear any session cookies set during login.
293 CookieManager.getInstance().removeSessionCookie();
294 }
295
Patrick Scottd43e75a2011-03-14 14:47:23 -0400296 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500297 new Runnable() {
298 @Override public void run() {
Michael Kolb938db802011-10-11 10:49:05 -0700299 onPreloginFinished(icicle, intent, currentTabId, restoreIncognitoTabs,
300 fromCrash);
Patrick Scott7d50a932011-02-04 09:27:26 -0500301 }
302 });
303 }
304
Michael Kolbc831b632011-05-11 09:30:34 -0700305 private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId,
Michael Kolb938db802011-10-11 10:49:05 -0700306 boolean restoreIncognitoTabs, boolean fromCrash) {
Michael Kolbc831b632011-05-11 09:30:34 -0700307 if (currentTabId == -1) {
John Reck1cf4b792011-07-26 10:22:22 -0700308 BackgroundHandler.execute(new PruneThumbnails(mActivity, null));
Michael Kolb8233fac2010-10-26 16:08:53 -0700309 final Bundle extra = intent.getExtras();
310 // Create an initial tab.
311 // If the intent is ACTION_VIEW and data is not null, the Browser is
312 // invoked to view the content by another application. In this case,
313 // the tab will be close when exit.
Michael Kolb14612442011-06-24 13:06:29 -0700314 UrlData urlData = IntentHandler.getUrlDataFromIntent(intent);
Michael Kolb7bcafde2011-05-09 13:55:59 -0700315 Tab t = null;
316 if (urlData.isEmpty()) {
317 t = openTabToHomePage();
318 } else {
319 t = openTab(urlData);
320 }
321 if (t != null) {
322 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
323 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700324 WebView webView = t.getWebView();
325 if (extra != null) {
326 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
327 if (scale > 0 && scale <= 1000) {
328 webView.setInitialScale(scale);
329 }
330 }
John Reckd8c74522011-06-14 08:45:00 -0700331 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700332 } else {
Michael Kolbc831b632011-05-11 09:30:34 -0700333 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
Patrick Scott7d50a932011-02-04 09:27:26 -0500334 mUi.needsRestoreAllTabs());
John Reck1cf4b792011-07-26 10:22:22 -0700335 List<Tab> tabs = mTabControl.getTabs();
336 ArrayList<Long> restoredTabs = new ArrayList<Long>(tabs.size());
337 for (Tab t : tabs) {
338 restoredTabs.add(t.getId());
339 }
340 BackgroundHandler.execute(new PruneThumbnails(mActivity, restoredTabs));
John Reck52be4782011-08-26 15:37:29 -0700341 if (tabs.size() == 0) {
342 openTabToHomePage();
343 }
John Reck1cf4b792011-07-26 10:22:22 -0700344 mUi.updateTabs(tabs);
Michael Kolb8233fac2010-10-26 16:08:53 -0700345 // TabControl.restoreState() will create a new tab even if
346 // restoring the state fails.
347 setActiveTab(mTabControl.getCurrentTab());
John Reck9dd4a412011-10-05 14:55:30 -0700348 // Handle the intent if needed. If icicle != null, we are restoring
349 // and the intent will be stale - ignore it.
Michael Kolb938db802011-10-11 10:49:05 -0700350 if (icicle == null || fromCrash) {
John Reck9dd4a412011-10-05 14:55:30 -0700351 mIntentHandler.onNewIntent(intent);
352 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700353 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700354 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700355 String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb8233fac2010-10-26 16:08:53 -0700356 if (jsFlags.trim().length() != 0) {
357 getCurrentWebView().setJsFlags(jsFlags);
358 }
John Reck439c9a52010-12-14 10:04:39 -0800359 if (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 // the default implementation requires each view to have an id. As the
658 // browser handles the state itself and it doesn't use id for the views,
659 // don't call the default implementation. Otherwise it will trigger the
660 // warning like this, "couldn't save which view has focus because the
661 // focused view XXX has no id".
662
663 // Save all the tabs
John Reck1cf4b792011-07-26 10:22:22 -0700664 mTabControl.saveState(outState);
John Reck24f18262011-06-17 14:47:20 -0700665 if (!outState.isEmpty()) {
666 // Save time so that we know how old incognito tabs (if any) are.
667 outState.putSerializable("lastActiveDate", Calendar.getInstance());
668 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700669 }
670
671 void onResume() {
672 if (!mActivityPaused) {
673 Log.e(LOGTAG, "BrowserActivity is already resumed.");
674 return;
675 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700676 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800677 Tab current = mTabControl.getCurrentTab();
678 if (current != null) {
679 current.resume();
680 resumeWebViewTimers(current);
681 }
John Reckf57c0292011-07-21 18:15:39 -0700682 releaseWakeLock();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200683
Michael Kolb8233fac2010-10-26 16:08:53 -0700684 mUi.onResume();
685 mNetworkHandler.onResume();
686 WebView.enablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100687 NfcHandler.register(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700688 }
689
John Reckf57c0292011-07-21 18:15:39 -0700690 private void releaseWakeLock() {
691 if (mWakeLock != null && mWakeLock.isHeld()) {
692 mHandler.removeMessages(RELEASE_WAKELOCK);
693 mWakeLock.release();
694 }
695 }
696
Michael Kolb70976932010-11-30 11:34:01 -0800697 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800698 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800699 * @param tab guaranteed non-null
700 */
701 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700702 boolean inLoad = tab.inPageLoad();
703 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
704 CookieSyncManager.getInstance().startSync();
705 WebView w = tab.getWebView();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100706 WebViewTimersControl.getInstance().onBrowserActivityResume(w);
Michael Kolb8233fac2010-10-26 16:08:53 -0700707 }
708 }
709
Michael Kolb70976932010-11-30 11:34:01 -0800710 /**
711 * Pause all WebView timers using the WebView of the given tab
712 * @param tab
713 * @return true if the timers are paused or tab is null
714 */
715 private boolean pauseWebViewTimers(Tab tab) {
716 if (tab == null) {
717 return true;
718 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700719 CookieSyncManager.getInstance().stopSync();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100720 WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView());
Michael Kolb8233fac2010-10-26 16:08:53 -0700721 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700722 }
Michael Kolb70976932010-11-30 11:34:01 -0800723 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700724 }
725
726 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800727 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700728 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
729 mUploadHandler = null;
730 }
731 if (mTabControl == null) return;
732 mUi.onDestroy();
733 // Remove the current tab and sub window
734 Tab t = mTabControl.getCurrentTab();
735 if (t != null) {
736 dismissSubWindow(t);
737 removeTab(t);
738 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500739 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700740 // Destroy all the tabs
741 mTabControl.destroy();
742 WebIconDatabase.getInstance().close();
743 // Stop watching the default geolocation permissions
744 mSystemAllowGeolocationOrigins.stop();
745 mSystemAllowGeolocationOrigins = null;
746 }
747
748 protected boolean isActivityPaused() {
749 return mActivityPaused;
750 }
751
752 protected void onLowMemory() {
753 mTabControl.freeMemory();
754 }
755
756 @Override
757 public boolean shouldShowErrorConsole() {
758 return mShouldShowErrorConsole;
759 }
760
761 protected void setShouldShowErrorConsole(boolean show) {
762 if (show == mShouldShowErrorConsole) {
763 // Nothing to do.
764 return;
765 }
766 mShouldShowErrorConsole = show;
767 Tab t = mTabControl.getCurrentTab();
768 if (t == null) {
769 // There is no current tab so we cannot toggle the error console
770 return;
771 }
772 mUi.setShouldShowErrorConsole(t, show);
773 }
774
775 @Override
776 public void stopLoading() {
777 mLoadStopped = true;
778 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700779 WebView w = getCurrentTopWebView();
780 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700781 mUi.onPageStopped(tab);
782 }
783
784 boolean didUserStopLoading() {
785 return mLoadStopped;
786 }
787
788 // WebViewController
789
790 @Override
John Reck324d4402011-01-11 16:56:42 -0800791 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700792
793 // We've started to load a new page. If there was a pending message
794 // to save a screenshot then we will now take the new page and save
795 // an incorrect screenshot. Therefore, remove any pending thumbnail
796 // messages from the queue.
797 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800798 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700799
800 // reset sync timer to avoid sync starts during loading a page
801 CookieSyncManager.getInstance().resetSync();
802
803 if (!mNetworkHandler.isNetworkUp()) {
804 view.setNetworkAvailable(false);
805 }
806
807 // when BrowserActivity just starts, onPageStarted may be called before
808 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
809 // to start the timer. As we won't switch tabs while an activity is in
810 // pause state, we can ensure calling resume and pause in pair.
811 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800812 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700813 }
814 mLoadStopped = false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700815 endActionMode();
816
John Reck30c714c2010-12-16 17:30:34 -0800817 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700818
John Reck324d4402011-01-11 16:56:42 -0800819 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700820 // update the bookmark database for favicon
821 maybeUpdateFavicon(tab, null, url, favicon);
822
823 Performance.tracePageStart(url);
824
825 // Performance probe
826 if (false) {
827 Performance.onPageStarted();
828 }
829
830 }
831
832 @Override
John Reck324d4402011-01-11 16:56:42 -0800833 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800834 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800835 if (!tab.isPrivateBrowsingEnabled()
John Reckd8c74522011-06-14 08:45:00 -0700836 && !TextUtils.isEmpty(tab.getUrl())
837 && !tab.isSnapshot()) {
John Recka1696282011-07-08 14:10:37 -0700838 // Only update the bookmark screenshot if the user did not
839 // cancel the load early and there is not already
840 // a pending update for the tab.
Michael Kolb8233fac2010-10-26 16:08:53 -0700841 if (tab.inForeground() && !didUserStopLoading()
842 || !tab.inForeground()) {
John Recka1696282011-07-08 14:10:37 -0700843 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
844 mHandler.sendMessageDelayed(mHandler.obtainMessage(
845 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
846 500);
847 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700848 }
849 }
850 // pause the WebView timer and release the wake lock if it is finished
851 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800852 if (mActivityPaused && pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700853 releaseWakeLock();
Michael Kolb8233fac2010-10-26 16:08:53 -0700854 }
Martijn Coenenb2f93552011-06-14 10:48:35 +0200855
Michael Kolb8233fac2010-10-26 16:08:53 -0700856 // Performance probe
857 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800858 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700859 }
860
861 Performance.tracePageFinished();
862 }
863
864 @Override
John Reck30c714c2010-12-16 17:30:34 -0800865 public void onProgressChanged(Tab tab) {
John Reck6c2e2f32011-08-22 13:41:23 -0700866 mCrashRecoveryHandler.backupState();
John Reck30c714c2010-12-16 17:30:34 -0800867 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700868
869 if (newProgress == 100) {
870 CookieSyncManager.getInstance().sync();
871 // onProgressChanged() may continue to be called after the main
872 // frame has finished loading, as any remaining sub frames continue
873 // to load. We'll only get called once though with newProgress as
874 // 100 when everything is loaded. (onPageFinished is called once
875 // when the main frame completes loading regardless of the state of
876 // any sub frames so calls to onProgressChanges may continue after
877 // onPageFinished has executed)
878 if (mInLoad) {
879 mInLoad = false;
880 updateInLoadMenuItems(mCachedMenu);
881 }
882 } else {
883 if (!mInLoad) {
884 // onPageFinished may have already been called but a subframe is
885 // still loading and updating the progress. Reset mInLoad and
886 // update the menu items.
887 mInLoad = true;
888 updateInLoadMenuItems(mCachedMenu);
889 }
890 }
John Reck30c714c2010-12-16 17:30:34 -0800891 mUi.onProgressChanged(tab);
892 }
893
894 @Override
Steve Block2466eff2011-10-03 15:33:09 +0100895 public void onUpdatedSecurityState(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800896 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700897 }
898
899 @Override
900 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800901 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800902 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800903 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700904 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
905 return;
906 }
907 // Update the title in the history database if not in private browsing mode
908 if (!tab.isPrivateBrowsingEnabled()) {
John Reckf57c0292011-07-21 18:15:39 -0700909 DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700910 }
911 }
912
913 @Override
914 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800915 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700916 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
917 }
918
919 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800920 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
921 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700922 }
923
924 @Override
925 public boolean shouldOverrideKeyEvent(KeyEvent event) {
926 if (mMenuIsDown) {
927 // only check shortcut key when MENU is held
928 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
929 event);
930 } else {
931 return false;
932 }
933 }
934
935 @Override
936 public void onUnhandledKeyEvent(KeyEvent event) {
937 if (!isActivityPaused()) {
938 if (event.getAction() == KeyEvent.ACTION_DOWN) {
939 mActivity.onKeyDown(event.getKeyCode(), event);
940 } else {
941 mActivity.onKeyUp(event.getKeyCode(), event);
942 }
943 }
944 }
945
946 @Override
John Reck324d4402011-01-11 16:56:42 -0800947 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700948 // Don't save anything in private browsing mode
949 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800950 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700951
John Reck324d4402011-01-11 16:56:42 -0800952 if (TextUtils.isEmpty(url)
953 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700954 return;
955 }
John Reckf57c0292011-07-21 18:15:39 -0700956 DataController.getInstance(mActivity).updateVisitedHistory(url);
John Reck6c2e2f32011-08-22 13:41:23 -0700957 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -0700958 }
959
960 @Override
961 public void getVisitedHistory(final ValueCallback<String[]> callback) {
962 AsyncTask<Void, Void, String[]> task =
963 new AsyncTask<Void, Void, String[]>() {
964 @Override
965 public String[] doInBackground(Void... unused) {
966 return Browser.getVisitedHistory(mActivity.getContentResolver());
967 }
968 @Override
969 public void onPostExecute(String[] result) {
970 callback.onReceiveValue(result);
971 }
972 };
973 task.execute();
974 }
975
976 @Override
977 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
978 final HttpAuthHandler handler, final String host,
979 final String realm) {
980 String username = null;
981 String password = null;
982
983 boolean reuseHttpAuthUsernamePassword
984 = handler.useHttpAuthUsernamePassword();
985
986 if (reuseHttpAuthUsernamePassword && view != null) {
987 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
988 if (credentials != null && credentials.length == 2) {
989 username = credentials[0];
990 password = credentials[1];
991 }
992 }
993
994 if (username != null && password != null) {
995 handler.proceed(username, password);
996 } else {
Ben Murdochfdd37112011-08-05 15:48:14 +0100997 if (tab.inForeground() && !handler.suppressDialog()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700998 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
999 } else {
1000 handler.cancel();
1001 }
1002 }
1003 }
1004
1005 @Override
1006 public void onDownloadStart(Tab tab, String url, String userAgent,
1007 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001008 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -05001009 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001010 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
1011 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001012 // This Tab was opened for the sole purpose of downloading a
1013 // file. Remove it.
1014 if (tab == mTabControl.getCurrentTab()) {
1015 // In this case, the Tab is still on top.
1016 goBackOnePageOrQuit();
1017 } else {
1018 // In this case, it is not.
1019 closeTab(tab);
1020 }
1021 }
1022 }
1023
1024 @Override
1025 public Bitmap getDefaultVideoPoster() {
1026 return mUi.getDefaultVideoPoster();
1027 }
1028
1029 @Override
1030 public View getVideoLoadingProgressView() {
1031 return mUi.getVideoLoadingProgressView();
1032 }
1033
1034 @Override
1035 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1036 SslError error) {
1037 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1038 }
1039
Patrick Scott92066772011-03-10 08:46:27 -05001040 @Override
1041 public void showAutoLogin(Tab tab) {
1042 assert tab.inForeground();
1043 // Update the title bar to show the auto-login request.
1044 mUi.showAutoLogin(tab);
1045 }
1046
1047 @Override
1048 public void hideAutoLogin(Tab tab) {
1049 assert tab.inForeground();
1050 mUi.hideAutoLogin(tab);
1051 }
1052
Michael Kolb8233fac2010-10-26 16:08:53 -07001053 // helper method
1054
1055 /*
1056 * Update the favorites icon if the private browsing isn't enabled and the
1057 * icon is valid.
1058 */
1059 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1060 final String url, Bitmap favicon) {
1061 if (favicon == null) {
1062 return;
1063 }
1064 if (!tab.isPrivateBrowsingEnabled()) {
1065 Bookmarks.updateFavicon(mActivity
1066 .getContentResolver(), originalUrl, url, favicon);
1067 }
1068 }
1069
Leon Scroggins4cd97792010-12-03 15:31:56 -05001070 @Override
1071 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001072 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001073 mUi.bookmarkedStatusHasChanged(tab);
1074 }
1075
Michael Kolb8233fac2010-10-26 16:08:53 -07001076 // end WebViewController
1077
1078 protected void pageUp() {
1079 getCurrentTopWebView().pageUp(false);
1080 }
1081
1082 protected void pageDown() {
1083 getCurrentTopWebView().pageDown(false);
1084 }
1085
1086 // callback from phone title bar
1087 public void editUrl() {
1088 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001089 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001090 }
1091
Michael Kolbcfa3af52010-12-14 10:36:11 -08001092 public void startVoiceSearch() {
1093 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1094 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1095 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1096 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1097 mActivity.getComponentName().flattenToString());
1098 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001099 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001100 mActivity.startActivity(intent);
1101 }
1102
Michael Kolb11d19782011-03-20 10:17:40 -07001103 @Override
1104 public void activateVoiceSearchMode(String title, List<String> results) {
1105 mUi.showVoiceTitleBar(title, results);
Michael Kolb8233fac2010-10-26 16:08:53 -07001106 }
1107
1108 public void revertVoiceSearchMode(Tab tab) {
1109 mUi.revertVoiceTitleBar(tab);
1110 }
1111
Michael Kolb736990c2011-03-20 10:01:20 -07001112 public boolean supportsVoiceSearch() {
John Reck35e9dd62011-04-25 09:01:54 -07001113 SearchEngine searchEngine = getSettings().getSearchEngine();
Michael Kolb736990c2011-03-20 10:01:20 -07001114 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1115 }
1116
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001117 public void showCustomView(Tab tab, View view, int requestedOrientation,
Michael Kolb8233fac2010-10-26 16:08:53 -07001118 WebChromeClient.CustomViewCallback callback) {
1119 if (tab.inForeground()) {
1120 if (mUi.isCustomViewShowing()) {
1121 callback.onCustomViewHidden();
1122 return;
1123 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001124 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001125 // Save the menu state and set it to empty while the custom
1126 // view is showing.
1127 mOldMenuState = mMenuState;
1128 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001129 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001130 }
1131 }
1132
1133 @Override
1134 public void hideCustomView() {
1135 if (mUi.isCustomViewShowing()) {
1136 mUi.onHideCustomView();
1137 // Reset the old menu state.
1138 mMenuState = mOldMenuState;
1139 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001140 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001141 }
1142 }
1143
1144 protected void onActivityResult(int requestCode, int resultCode,
1145 Intent intent) {
1146 if (getCurrentTopWebView() == null) return;
1147 switch (requestCode) {
1148 case PREFERENCES_PAGE:
1149 if (resultCode == Activity.RESULT_OK && intent != null) {
1150 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001151 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001152 mTabControl.removeParentChildRelationShips();
1153 }
1154 }
1155 break;
1156 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001157 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001158 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001159 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001160 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001161 case AUTOFILL_SETUP:
1162 // Determine whether a profile was actually set up or not
1163 // and if so, send the message back to the WebTextView to
1164 // fill the form with the new profile.
1165 if (getSettings().getAutoFillProfile() != null) {
1166 mAutoFillSetupMessage.sendToTarget();
1167 mAutoFillSetupMessage = null;
1168 }
1169 break;
John Reckd3e4d5b2011-07-13 15:48:43 -07001170 case COMBO_VIEW:
1171 if (intent == null || resultCode != Activity.RESULT_OK) {
1172 break;
1173 }
John Reck3ba45532011-08-11 16:26:53 -07001174 mUi.showWeb(false);
John Reckd3e4d5b2011-07-13 15:48:43 -07001175 if (Intent.ACTION_VIEW.equals(intent.getAction())) {
1176 Tab t = getCurrentTab();
1177 Uri uri = intent.getData();
1178 loadUrl(t, uri.toString());
1179 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
1180 String[] urls = intent.getStringArrayExtra(
1181 ComboViewActivity.EXTRA_OPEN_ALL);
1182 Tab parent = getCurrentTab();
1183 for (String url : urls) {
1184 parent = openTab(url, parent,
1185 !mSettings.openInBackground(), true);
1186 }
1187 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
1188 long id = intent.getLongExtra(
1189 ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
1190 if (id >= 0) {
1191 createNewSnapshotTab(id, true);
1192 }
1193 }
1194 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001195 default:
1196 break;
1197 }
1198 getCurrentTopWebView().requestFocus();
1199 }
1200
1201 /**
1202 * Open the Go page.
1203 * @param startWithHistory If true, open starting on the history tab.
1204 * Otherwise, start with the bookmarks tab.
1205 */
1206 @Override
Michael Kolb315d5022011-10-13 12:47:11 -07001207 public void bookmarksOrHistoryPicker(ComboViews startView) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001208 if (mTabControl.getCurrentWebView() == null) {
1209 return;
1210 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001211 // clear action mode
1212 if (isInCustomActionMode()) {
1213 endActionMode();
1214 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001215 Bundle extras = new Bundle();
1216 // Disable opening in a new window if we have maxed out the windows
1217 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1218 !mTabControl.canCreateNewTab());
Michael Kolb315d5022011-10-13 12:47:11 -07001219 mUi.showComboView(startView, extras);
Michael Kolb8233fac2010-10-26 16:08:53 -07001220 }
1221
1222 // combo view callbacks
1223
Michael Kolb8233fac2010-10-26 16:08:53 -07001224 // key handling
1225 protected void onBackKey() {
1226 if (!mUi.onBackKey()) {
1227 WebView subwindow = mTabControl.getCurrentSubWindow();
1228 if (subwindow != null) {
1229 if (subwindow.canGoBack()) {
1230 subwindow.goBack();
1231 } else {
1232 dismissSubWindow(mTabControl.getCurrentTab());
1233 }
1234 } else {
1235 goBackOnePageOrQuit();
1236 }
1237 }
1238 }
1239
Michael Kolb4bd767d2011-05-27 11:33:55 -07001240 protected boolean onMenuKey() {
1241 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001242 }
1243
Michael Kolb8233fac2010-10-26 16:08:53 -07001244 // menu handling and state
1245 // TODO: maybe put into separate handler
1246
1247 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckd73c5a22010-12-22 10:22:50 -08001248 if (mMenuState == EMPTY_MENU) {
1249 return false;
1250 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001251 MenuInflater inflater = mActivity.getMenuInflater();
1252 inflater.inflate(R.menu.browser, menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001253 return true;
1254 }
1255
1256 protected void onCreateContextMenu(ContextMenu menu, View v,
1257 ContextMenuInfo menuInfo) {
John Reck0f602f32011-07-07 15:38:43 -07001258 if (v instanceof TitleBar) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001259 return;
1260 }
1261 if (!(v instanceof WebView)) {
1262 return;
1263 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001264 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001265 WebView.HitTestResult result = webview.getHitTestResult();
1266 if (result == null) {
1267 return;
1268 }
1269
1270 int type = result.getType();
1271 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1272 Log.w(LOGTAG,
1273 "We should not show context menu when nothing is touched");
1274 return;
1275 }
1276 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1277 // let TextView handles context menu
1278 return;
1279 }
1280
1281 // Note, http://b/issue?id=1106666 is requesting that
1282 // an inflated menu can be used again. This is not available
1283 // yet, so inflate each time (yuk!)
1284 MenuInflater inflater = mActivity.getMenuInflater();
1285 inflater.inflate(R.menu.browsercontext, menu);
1286
1287 // Show the correct menu group
1288 final String extra = result.getExtra();
1289 menu.setGroupVisible(R.id.PHONE_MENU,
1290 type == WebView.HitTestResult.PHONE_TYPE);
1291 menu.setGroupVisible(R.id.EMAIL_MENU,
1292 type == WebView.HitTestResult.EMAIL_TYPE);
1293 menu.setGroupVisible(R.id.GEO_MENU,
1294 type == WebView.HitTestResult.GEO_TYPE);
1295 menu.setGroupVisible(R.id.IMAGE_MENU,
1296 type == WebView.HitTestResult.IMAGE_TYPE
1297 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1298 menu.setGroupVisible(R.id.ANCHOR_MENU,
1299 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1300 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001301 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1302 || type == WebView.HitTestResult.PHONE_TYPE
1303 || type == WebView.HitTestResult.EMAIL_TYPE
1304 || type == WebView.HitTestResult.GEO_TYPE;
1305 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1306 if (hitText) {
1307 menu.findItem(R.id.select_text_menu_id)
1308 .setOnMenuItemClickListener(new SelectText(webview));
1309 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001310 // Setup custom handling depending on the type
1311 switch (type) {
1312 case WebView.HitTestResult.PHONE_TYPE:
1313 menu.setHeaderTitle(Uri.decode(extra));
1314 menu.findItem(R.id.dial_context_menu_id).setIntent(
1315 new Intent(Intent.ACTION_VIEW, Uri
1316 .parse(WebView.SCHEME_TEL + extra)));
1317 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1318 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1319 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1320 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1321 addIntent);
1322 menu.findItem(R.id.copy_phone_context_menu_id)
1323 .setOnMenuItemClickListener(
1324 new Copy(extra));
1325 break;
1326
1327 case WebView.HitTestResult.EMAIL_TYPE:
1328 menu.setHeaderTitle(extra);
1329 menu.findItem(R.id.email_context_menu_id).setIntent(
1330 new Intent(Intent.ACTION_VIEW, Uri
1331 .parse(WebView.SCHEME_MAILTO + extra)));
1332 menu.findItem(R.id.copy_mail_context_menu_id)
1333 .setOnMenuItemClickListener(
1334 new Copy(extra));
1335 break;
1336
1337 case WebView.HitTestResult.GEO_TYPE:
1338 menu.setHeaderTitle(extra);
1339 menu.findItem(R.id.map_context_menu_id).setIntent(
1340 new Intent(Intent.ACTION_VIEW, Uri
1341 .parse(WebView.SCHEME_GEO
1342 + URLEncoder.encode(extra))));
1343 menu.findItem(R.id.copy_geo_context_menu_id)
1344 .setOnMenuItemClickListener(
1345 new Copy(extra));
1346 break;
1347
1348 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1349 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001350 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001351 // decide whether to show the open link in new tab option
1352 boolean showNewTab = mTabControl.canCreateNewTab();
1353 MenuItem newTabItem
1354 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001355 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001356 ? R.string.contextmenu_openlink_newwindow_background
1357 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001358 newTabItem.setVisible(showNewTab);
1359 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001360 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1361 newTabItem.setOnMenuItemClickListener(
1362 new MenuItem.OnMenuItemClickListener() {
1363 @Override
1364 public boolean onMenuItemClick(MenuItem item) {
1365 final HashMap<String, WebView> hrefMap =
1366 new HashMap<String, WebView>();
1367 hrefMap.put("webview", webview);
1368 final Message msg = mHandler.obtainMessage(
1369 FOCUS_NODE_HREF,
1370 R.id.open_newtab_context_menu_id,
1371 0, hrefMap);
1372 webview.requestFocusNodeHref(msg);
1373 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001374 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001375 });
1376 } else {
1377 newTabItem.setOnMenuItemClickListener(
1378 new MenuItem.OnMenuItemClickListener() {
1379 @Override
1380 public boolean onMenuItemClick(MenuItem item) {
1381 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001382 openTab(extra, parent,
1383 !mSettings.openInBackground(),
1384 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001385 return true;
1386 }
1387 });
1388 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001389 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001390 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1391 break;
1392 }
1393 // otherwise fall through to handle image part
1394 case WebView.HitTestResult.IMAGE_TYPE:
1395 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1396 menu.setHeaderTitle(extra);
1397 }
Michael Kolb3639c4c2011-09-28 15:36:40 -07001398 menu.findItem(R.id.view_image_context_menu_id)
1399 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1400 @Override
1401 public boolean onMenuItemClick(MenuItem item) {
1402 openTab(extra, mTabControl.getCurrentTab(), true, true);
1403 return false;
1404 }
1405 });
Michael Kolb8233fac2010-10-26 16:08:53 -07001406 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001407 setOnMenuItemClickListener(
1408 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001409 menu.findItem(R.id.set_wallpaper_context_menu_id).
1410 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1411 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001412 break;
1413
1414 default:
1415 Log.w(LOGTAG, "We should not get here.");
1416 break;
1417 }
1418 //update the ui
1419 mUi.onContextMenuCreated(menu);
1420 }
1421
1422 /**
1423 * As the menu can be open when loading state changes
1424 * we must manually update the state of the stop/reload menu
1425 * item
1426 */
1427 private void updateInLoadMenuItems(Menu menu) {
1428 if (menu == null) {
1429 return;
1430 }
1431 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1432 MenuItem src = mInLoad ?
1433 menu.findItem(R.id.stop_menu_id):
1434 menu.findItem(R.id.reload_menu_id);
1435 if (src != null) {
1436 dest.setIcon(src.getIcon());
1437 dest.setTitle(src.getTitle());
1438 }
1439 }
1440
John Reckb3417f02011-01-14 11:01:05 -08001441 boolean onPrepareOptionsMenu(Menu menu) {
John Recke1a03a32011-09-14 17:04:16 -07001442 updateInLoadMenuItems(menu);
1443 // hold on to the menu reference here; it is used by the page callbacks
1444 // to update the menu based on loading state
1445 mCachedMenu = menu;
Michael Kolb8233fac2010-10-26 16:08:53 -07001446 // Note: setVisible will decide whether an item is visible; while
1447 // setEnabled() will decide whether an item is enabled, which also means
1448 // whether the matching shortcut key will function.
1449 switch (mMenuState) {
1450 case EMPTY_MENU:
1451 if (mCurrentMenuState != mMenuState) {
1452 menu.setGroupVisible(R.id.MAIN_MENU, false);
1453 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1454 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1455 }
1456 break;
1457 default:
1458 if (mCurrentMenuState != mMenuState) {
1459 menu.setGroupVisible(R.id.MAIN_MENU, true);
1460 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1461 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1462 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001463 updateMenuState(getCurrentTab(), menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001464 break;
1465 }
1466 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001467 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001468 }
1469
Michael Kolb4bf79712011-07-14 14:18:12 -07001470 @Override
1471 public void updateMenuState(Tab tab, Menu menu) {
1472 boolean canGoBack = false;
1473 boolean canGoForward = false;
1474 boolean isHome = false;
John Reck42229bc2011-08-19 13:26:43 -07001475 boolean isDesktopUa = false;
John Recke1a03a32011-09-14 17:04:16 -07001476 boolean isLive = false;
Michael Kolb4bf79712011-07-14 14:18:12 -07001477 if (tab != null) {
1478 canGoBack = tab.canGoBack();
1479 canGoForward = tab.canGoForward();
1480 isHome = mSettings.getHomePage().equals(tab.getUrl());
John Reck42229bc2011-08-19 13:26:43 -07001481 isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
John Recke1a03a32011-09-14 17:04:16 -07001482 isLive = !tab.isSnapshot();
Michael Kolb4bf79712011-07-14 14:18:12 -07001483 }
1484 final MenuItem back = menu.findItem(R.id.back_menu_id);
1485 back.setEnabled(canGoBack);
1486
1487 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1488 home.setEnabled(!isHome);
1489
1490 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1491 forward.setEnabled(canGoForward);
1492
1493 final MenuItem source = menu.findItem(mInLoad ? R.id.stop_menu_id : R.id.reload_menu_id);
1494 final MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolb7ab75ee2011-07-14 16:36:38 -07001495 if (source != null && dest != null) {
1496 dest.setTitle(source.getTitle());
1497 dest.setIcon(source.getIcon());
1498 }
John Recke1a03a32011-09-14 17:04:16 -07001499 menu.setGroupVisible(R.id.NAV_MENU, isLive);
Michael Kolb4bf79712011-07-14 14:18:12 -07001500
1501 // decide whether to show the share link option
1502 PackageManager pm = mActivity.getPackageManager();
1503 Intent send = new Intent(Intent.ACTION_SEND);
1504 send.setType("text/plain");
1505 ResolveInfo ri = pm.resolveActivity(send,
1506 PackageManager.MATCH_DEFAULT_ONLY);
1507 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1508
1509 boolean isNavDump = mSettings.enableNavDump();
1510 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1511 nav.setVisible(isNavDump);
1512 nav.setEnabled(isNavDump);
1513
1514 boolean showDebugSettings = mSettings.isDebugEnabled();
John Reck42229bc2011-08-19 13:26:43 -07001515 final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
1516 uaSwitcher.setChecked(isDesktopUa);
John Recke1a03a32011-09-14 17:04:16 -07001517 menu.setGroupVisible(R.id.LIVE_MENU, isLive);
1518 menu.setGroupVisible(R.id.SNAPSHOT_MENU, !isLive);
Michael Kolb315d5022011-10-13 12:47:11 -07001519 menu.setGroupVisible(R.id.COMBO_MENU, false);
Michael Kolb4bf79712011-07-14 14:18:12 -07001520
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001521 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001522 }
1523
Michael Kolb8233fac2010-10-26 16:08:53 -07001524 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001525 if (null == getCurrentTopWebView()) {
1526 return false;
1527 }
1528 if (mMenuIsDown) {
1529 // The shortcut action consumes the MENU. Even if it is still down,
1530 // it won't trigger the next shortcut action. In the case of the
1531 // shortcut action triggering a new activity, like Bookmarks, we
1532 // won't get onKeyUp for MENU. So it is important to reset it here.
1533 mMenuIsDown = false;
1534 }
Michael Kolb3ca12752011-07-20 13:52:25 -07001535 if (mUi.onOptionsItemSelected(item)) {
1536 // ui callback handled it
1537 return true;
1538 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001539 switch (item.getItemId()) {
1540 // -- Main menu
1541 case R.id.new_tab_menu_id:
1542 openTabToHomePage();
1543 break;
1544
1545 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001546 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001547 break;
1548
1549 case R.id.goto_menu_id:
1550 editUrl();
1551 break;
1552
1553 case R.id.bookmarks_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001554 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
1555 break;
1556
1557 case R.id.history_menu_id:
1558 bookmarksOrHistoryPicker(ComboViews.History);
1559 break;
1560
1561 case R.id.snapshots_menu_id:
1562 bookmarksOrHistoryPicker(ComboViews.Snapshots);
Michael Kolb8233fac2010-10-26 16:08:53 -07001563 break;
1564
Michael Kolb8233fac2010-10-26 16:08:53 -07001565 case R.id.add_bookmark_menu_id:
John Recka60fffa2011-09-06 16:30:29 -07001566 Intent bookmarkIntent = createBookmarkCurrentPageIntent(false);
1567 if (bookmarkIntent != null) {
1568 mActivity.startActivity(bookmarkIntent);
1569 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001570 break;
1571
1572 case R.id.stop_reload_menu_id:
1573 if (mInLoad) {
1574 stopLoading();
1575 } else {
1576 getCurrentTopWebView().reload();
1577 }
1578 break;
1579
1580 case R.id.back_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001581 getCurrentTab().goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07001582 break;
1583
1584 case R.id.forward_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001585 getCurrentTab().goForward();
Michael Kolb8233fac2010-10-26 16:08:53 -07001586 break;
1587
1588 case R.id.close_menu_id:
1589 // Close the subwindow if it exists.
1590 if (mTabControl.getCurrentSubWindow() != null) {
1591 dismissSubWindow(mTabControl.getCurrentTab());
1592 break;
1593 }
1594 closeCurrentTab();
1595 break;
1596
1597 case R.id.homepage_menu_id:
1598 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07001599 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07001600 break;
1601
1602 case R.id.preferences_menu_id:
1603 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1604 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1605 getCurrentTopWebView().getUrl());
1606 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1607 break;
1608
1609 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001610 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001611 break;
1612
John Reck2bc80422011-06-30 15:11:49 -07001613 case R.id.save_snapshot_menu_id:
1614 final Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07001615 if (source == null) break;
John Reckd8c74522011-06-14 08:45:00 -07001616 final ContentResolver cr = mActivity.getContentResolver();
1617 final ContentValues values = source.createSnapshotValues();
John Reck2bc80422011-06-30 15:11:49 -07001618 if (values != null) {
1619 new AsyncTask<Tab, Void, Long>() {
John Reckd8c74522011-06-14 08:45:00 -07001620
John Reck2bc80422011-06-30 15:11:49 -07001621 @Override
1622 protected Long doInBackground(Tab... params) {
1623 Uri result = cr.insert(Snapshots.CONTENT_URI, values);
John Reck93384ff2011-11-10 11:29:18 -08001624 if (result == null) {
1625 return null;
1626 }
John Reck2bc80422011-06-30 15:11:49 -07001627 long id = ContentUris.parseId(result);
1628 return id;
John Reckd8c74522011-06-14 08:45:00 -07001629 }
John Reckf33b1632011-06-04 20:00:23 -07001630
John Reck2bc80422011-06-30 15:11:49 -07001631 @Override
1632 protected void onPostExecute(Long id) {
John Reck93384ff2011-11-10 11:29:18 -08001633 if (id == null) {
1634 Toast.makeText(mActivity, R.string.snapshot_failed,
1635 Toast.LENGTH_SHORT).show();
1636 return;
1637 }
John Reck2bc80422011-06-30 15:11:49 -07001638 Bundle b = new Bundle();
1639 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
1640 mUi.showComboView(ComboViews.Snapshots, b);
1641 };
1642 }.execute(source);
1643 } else {
1644 Toast.makeText(mActivity, R.string.snapshot_failed,
Leon Scrogginsac993842011-02-02 12:54:07 -05001645 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001646 }
Leon Scrogginsac993842011-02-02 12:54:07 -05001647 break;
1648
Michael Kolb8233fac2010-10-26 16:08:53 -07001649 case R.id.page_info_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001650 showPageInfo();
Michael Kolb8233fac2010-10-26 16:08:53 -07001651 break;
1652
John Recke1a03a32011-09-14 17:04:16 -07001653 case R.id.snapshot_go_live:
1654 goLive();
1655 return true;
1656
Michael Kolb8233fac2010-10-26 16:08:53 -07001657 case R.id.share_page_menu_id:
1658 Tab currentTab = mTabControl.getCurrentTab();
1659 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001660 return false;
1661 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001662 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001663 break;
1664
1665 case R.id.dump_nav_menu_id:
1666 getCurrentTopWebView().debugDump();
1667 break;
1668
Michael Kolb8233fac2010-10-26 16:08:53 -07001669 case R.id.zoom_in_menu_id:
1670 getCurrentTopWebView().zoomIn();
1671 break;
1672
1673 case R.id.zoom_out_menu_id:
1674 getCurrentTopWebView().zoomOut();
1675 break;
1676
1677 case R.id.view_downloads_menu_id:
1678 viewDownloads();
1679 break;
1680
John Reck42229bc2011-08-19 13:26:43 -07001681 case R.id.ua_desktop_menu_id:
1682 WebView web = getCurrentWebView();
1683 mSettings.toggleDesktopUseragent(web);
1684 web.loadUrl(web.getOriginalUrl());
1685 break;
1686
Michael Kolb8233fac2010-10-26 16:08:53 -07001687 case R.id.window_one_menu_id:
1688 case R.id.window_two_menu_id:
1689 case R.id.window_three_menu_id:
1690 case R.id.window_four_menu_id:
1691 case R.id.window_five_menu_id:
1692 case R.id.window_six_menu_id:
1693 case R.id.window_seven_menu_id:
1694 case R.id.window_eight_menu_id:
1695 {
1696 int menuid = item.getItemId();
1697 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1698 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1699 Tab desiredTab = mTabControl.getTab(id);
1700 if (desiredTab != null &&
1701 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001702 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001703 }
1704 break;
1705 }
1706 }
1707 }
1708 break;
1709
1710 default:
1711 return false;
1712 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001713 return true;
1714 }
1715
John Recke1a03a32011-09-14 17:04:16 -07001716 private void goLive() {
1717 Tab t = getCurrentTab();
1718 t.loadUrl(t.getUrl(), null);
1719 }
1720
Michael Kolb315d5022011-10-13 12:47:11 -07001721 @Override
1722 public void showPageInfo() {
1723 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
1724 }
1725
Michael Kolb8233fac2010-10-26 16:08:53 -07001726 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001727 // Let the History and Bookmark fragments handle menus they created.
1728 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1729 return false;
1730 }
1731
Michael Kolb8233fac2010-10-26 16:08:53 -07001732 int id = item.getItemId();
1733 boolean result = true;
1734 switch (id) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001735 // -- Browser context menu
1736 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001737 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001738 case R.id.copy_link_context_menu_id:
1739 final WebView webView = getCurrentTopWebView();
1740 if (null == webView) {
1741 result = false;
1742 break;
1743 }
1744 final HashMap<String, WebView> hrefMap =
1745 new HashMap<String, WebView>();
1746 hrefMap.put("webview", webView);
1747 final Message msg = mHandler.obtainMessage(
1748 FOCUS_NODE_HREF, id, 0, hrefMap);
1749 webView.requestFocusNodeHref(msg);
1750 break;
1751
1752 default:
1753 // For other context menus
1754 result = onOptionsItemSelected(item);
1755 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001756 return result;
1757 }
1758
1759 /**
1760 * support programmatically opening the context menu
1761 */
1762 public void openContextMenu(View view) {
1763 mActivity.openContextMenu(view);
1764 }
1765
1766 /**
1767 * programmatically open the options menu
1768 */
1769 public void openOptionsMenu() {
1770 mActivity.openOptionsMenu();
1771 }
1772
1773 public boolean onMenuOpened(int featureId, Menu menu) {
1774 if (mOptionsMenuOpen) {
1775 if (mConfigChanged) {
1776 // We do not need to make any changes to the state of the
1777 // title bar, since the only thing that happened was a
1778 // change in orientation
1779 mConfigChanged = false;
1780 } else {
1781 if (!mExtendedMenuOpen) {
1782 mExtendedMenuOpen = true;
1783 mUi.onExtendedMenuOpened();
1784 } else {
1785 // Switching the menu back to icon view, so show the
1786 // title bar once again.
1787 mExtendedMenuOpen = false;
1788 mUi.onExtendedMenuClosed(mInLoad);
Michael Kolb8233fac2010-10-26 16:08:53 -07001789 }
1790 }
1791 } else {
1792 // The options menu is closed, so open it, and show the title
1793 mOptionsMenuOpen = true;
1794 mConfigChanged = false;
1795 mExtendedMenuOpen = false;
1796 mUi.onOptionsMenuOpened();
1797 }
1798 return true;
1799 }
1800
1801 public void onOptionsMenuClosed(Menu menu) {
1802 mOptionsMenuOpen = false;
1803 mUi.onOptionsMenuClosed(mInLoad);
1804 }
1805
1806 public void onContextMenuClosed(Menu menu) {
1807 mUi.onContextMenuClosed(menu, mInLoad);
1808 }
1809
1810 // Helper method for getting the top window.
1811 @Override
1812 public WebView getCurrentTopWebView() {
1813 return mTabControl.getCurrentTopWebView();
1814 }
1815
1816 @Override
1817 public WebView getCurrentWebView() {
1818 return mTabControl.getCurrentWebView();
1819 }
1820
1821 /*
1822 * This method is called as a result of the user selecting the options
1823 * menu to see the download window. It shows the download window on top of
1824 * the current window.
1825 */
1826 void viewDownloads() {
1827 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1828 mActivity.startActivity(intent);
1829 }
1830
John Reck30b065e2011-07-19 10:58:05 -07001831 int getActionModeHeight() {
1832 TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
1833 new int[] { android.R.attr.actionBarSize });
1834 int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
1835 actionBarSizeTypedArray.recycle();
1836 return size;
1837 }
1838
Michael Kolb8233fac2010-10-26 16:08:53 -07001839 // action mode
1840
1841 void onActionModeStarted(ActionMode mode) {
1842 mUi.onActionModeStarted(mode);
1843 mActionMode = mode;
1844 }
1845
1846 /*
1847 * True if a custom ActionMode (i.e. find or select) is in use.
1848 */
1849 @Override
1850 public boolean isInCustomActionMode() {
1851 return mActionMode != null;
1852 }
1853
1854 /*
1855 * End the current ActionMode.
1856 */
1857 @Override
1858 public void endActionMode() {
1859 if (mActionMode != null) {
1860 mActionMode.finish();
1861 }
1862 }
1863
1864 /*
1865 * Called by find and select when they are finished. Replace title bars
1866 * as necessary.
1867 */
1868 public void onActionModeFinished(ActionMode mode) {
1869 if (!isInCustomActionMode()) return;
1870 mUi.onActionModeFinished(mInLoad);
1871 mActionMode = null;
1872 }
1873
1874 boolean isInLoad() {
1875 return mInLoad;
1876 }
1877
1878 // bookmark handling
1879
1880 /**
1881 * add the current page as a bookmark to the given folder id
1882 * @param folderId use -1 for the default folder
John Reckd3e4d5b2011-07-13 15:48:43 -07001883 * @param editExisting If true, check to see whether the site is already
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001884 * bookmarked, and if it is, edit that bookmark. If false, and
1885 * the site is already bookmarked, do not attempt to edit the
1886 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001887 */
1888 @Override
John Reckd3e4d5b2011-07-13 15:48:43 -07001889 public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
John Recka60fffa2011-09-06 16:30:29 -07001890 WebView w = getCurrentTopWebView();
1891 if (w == null) {
1892 return null;
1893 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001894 Intent i = new Intent(mActivity,
1895 AddBookmarkPage.class);
Michael Kolb8233fac2010-10-26 16:08:53 -07001896 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1897 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1898 String touchIconUrl = w.getTouchIconUrl();
1899 if (touchIconUrl != null) {
1900 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1901 WebSettings settings = w.getSettings();
1902 if (settings != null) {
1903 i.putExtra(AddBookmarkPage.USER_AGENT,
1904 settings.getUserAgentString());
1905 }
1906 }
1907 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1908 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1909 getDesiredThumbnailHeight(mActivity)));
1910 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07001911 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001912 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1913 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001914 // Put the dialog at the upper right of the screen, covering the
1915 // star on the title bar.
1916 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07001917 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07001918 }
1919
1920 // file chooser
1921 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1922 mUploadHandler = new UploadHandler(this);
1923 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1924 }
1925
1926 // thumbnails
1927
1928 /**
1929 * Return the desired width for thumbnail screenshots, which are stored in
1930 * the database, and used on the bookmarks screen.
1931 * @param context Context for finding out the density of the screen.
1932 * @return desired width for thumbnail screenshot.
1933 */
1934 static int getDesiredThumbnailWidth(Context context) {
1935 return context.getResources().getDimensionPixelOffset(
1936 R.dimen.bookmarkThumbnailWidth);
1937 }
1938
1939 /**
1940 * Return the desired height for thumbnail screenshots, which are stored in
1941 * the database, and used on the bookmarks screen.
1942 * @param context Context for finding out the density of the screen.
1943 * @return desired height for thumbnail screenshot.
1944 */
1945 static int getDesiredThumbnailHeight(Context context) {
1946 return context.getResources().getDimensionPixelOffset(
1947 R.dimen.bookmarkThumbnailHeight);
1948 }
1949
John Reck8cc92352011-07-06 17:41:52 -07001950 static Bitmap createScreenshot(WebView view, int width, int height) {
John Reckd7dd9b22011-08-30 09:18:29 -07001951 if (view == null || view.getContentHeight() == 0
1952 || view.getContentWidth() == 0) {
1953 return null;
1954 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001955 // We render to a bitmap 2x the desired size so that we can then
1956 // re-scale it with filtering since canvas.scale doesn't filter
1957 // This helps reduce aliasing at the cost of being slightly blurry
1958 final int filter_scale = 2;
John Reckd7dd9b22011-08-30 09:18:29 -07001959 int scaledWidth = width * filter_scale;
1960 int scaledHeight = height * filter_scale;
1961 if (sThumbnailBitmap == null || sThumbnailBitmap.getWidth() != scaledWidth
1962 || sThumbnailBitmap.getHeight() != scaledHeight) {
1963 if (sThumbnailBitmap != null) {
1964 sThumbnailBitmap.recycle();
1965 sThumbnailBitmap = null;
1966 }
1967 sThumbnailBitmap =
1968 Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.RGB_565);
Michael Kolb8233fac2010-10-26 16:08:53 -07001969 }
John Reckd7dd9b22011-08-30 09:18:29 -07001970 Canvas canvas = new Canvas(sThumbnailBitmap);
1971 int contentWidth = view.getContentWidth();
1972 float overviewScale = scaledWidth / (view.getScale() * contentWidth);
1973 if (view instanceof BrowserWebView) {
1974 int dy = -((BrowserWebView)view).getTitleHeight();
1975 canvas.translate(0, dy * overviewScale);
1976 }
1977
1978 canvas.scale(overviewScale, overviewScale);
1979
1980 if (view instanceof BrowserWebView) {
1981 ((BrowserWebView)view).drawContent(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07001982 } else {
John Reckd7dd9b22011-08-30 09:18:29 -07001983 view.draw(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07001984 }
John Reckd7dd9b22011-08-30 09:18:29 -07001985 Bitmap ret = Bitmap.createScaledBitmap(sThumbnailBitmap,
1986 width, height, true);
Dianne Hackborn43cfe8a2011-08-02 16:59:35 -07001987 canvas.setBitmap(null);
John Reck5c6ac2f2011-01-05 10:18:03 -08001988 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001989 }
1990
John Reck34ef2672011-02-10 11:30:55 -08001991 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001992 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07001993 // FIXME: Would like to make sure there is actually something to
1994 // draw, but the API for that (WebViewCore.pictureReady()) is not
1995 // currently accessible here.
1996
John Reck34ef2672011-02-10 11:30:55 -08001997 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08001998 if (view == null) {
1999 // Tab was destroyed
2000 return;
2001 }
John Reck34ef2672011-02-10 11:30:55 -08002002 final String url = tab.getUrl();
2003 final String originalUrl = view.getOriginalUrl();
2004
2005 if (TextUtils.isEmpty(url)) {
2006 return;
2007 }
2008
2009 // Only update thumbnails for web urls (http(s)://), not for
2010 // about:, javascript:, data:, etc...
2011 // Unless it is a bookmarked site, then always update
2012 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2013 return;
2014 }
2015
Michael Kolb8233fac2010-10-26 16:08:53 -07002016 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2017 getDesiredThumbnailHeight(mActivity));
2018 if (bm == null) {
2019 return;
2020 }
2021
2022 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002023 new AsyncTask<Void, Void, Void>() {
2024 @Override
2025 protected Void doInBackground(Void... unused) {
2026 Cursor cursor = null;
2027 try {
2028 // TODO: Clean this up
2029 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2030 if (cursor != null && cursor.moveToFirst()) {
2031 final ByteArrayOutputStream os =
2032 new ByteArrayOutputStream();
2033 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002034
John Reck34ef2672011-02-10 11:30:55 -08002035 ContentValues values = new ContentValues();
2036 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002037
John Reck34ef2672011-02-10 11:30:55 -08002038 do {
John Reck617fd832011-02-16 14:35:59 -08002039 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002040 cr.update(Images.CONTENT_URI, values, null, null);
2041 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002042 }
John Reck34ef2672011-02-10 11:30:55 -08002043 } catch (IllegalStateException e) {
2044 // Ignore
2045 } finally {
2046 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002047 }
John Reck34ef2672011-02-10 11:30:55 -08002048 return null;
2049 }
2050 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002051 }
2052
2053 private class Copy implements OnMenuItemClickListener {
2054 private CharSequence mText;
2055
2056 public boolean onMenuItemClick(MenuItem item) {
2057 copy(mText);
2058 return true;
2059 }
2060
2061 public Copy(CharSequence toCopy) {
2062 mText = toCopy;
2063 }
2064 }
2065
Leon Scroggins63c02662010-11-18 15:16:27 -05002066 private static class Download implements OnMenuItemClickListener {
2067 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002068 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002069 private boolean mPrivateBrowsing;
George Mount387d45d2011-10-07 15:57:53 -07002070 private static final String FALLBACK_EXTENSION = "dat";
2071 private static final String IMAGE_BASE_FORMAT = "yyyy-MM-dd-HH-mm-ss-";
Michael Kolb8233fac2010-10-26 16:08:53 -07002072
2073 public boolean onMenuItemClick(MenuItem item) {
George Mount387d45d2011-10-07 15:57:53 -07002074 if (DataUri.isDataUri(mText)) {
2075 saveDataUri();
2076 } else {
2077 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
2078 null, null, mPrivateBrowsing);
2079 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002080 return true;
2081 }
2082
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002083 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002084 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002085 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002086 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002087 }
George Mount387d45d2011-10-07 15:57:53 -07002088
2089 /**
2090 * Treats mText as a data URI and writes its contents to a file
2091 * based on the current time.
2092 */
2093 private void saveDataUri() {
2094 FileOutputStream outputStream = null;
2095 try {
2096 DataUri uri = new DataUri(mText);
2097 File target = getTarget(uri);
2098 outputStream = new FileOutputStream(target);
2099 outputStream.write(uri.getData());
2100 final DownloadManager manager =
2101 (DownloadManager) mActivity.getSystemService(Context.DOWNLOAD_SERVICE);
2102 manager.addCompletedDownload(target.getName(),
2103 mActivity.getTitle().toString(), false,
2104 uri.getMimeType(), target.getAbsolutePath(),
George Mount7501bf42011-11-17 11:17:03 -08002105 (long)uri.getData().length, true);
George Mount387d45d2011-10-07 15:57:53 -07002106 } catch (IOException e) {
2107 Log.e(LOGTAG, "Could not save data URL");
2108 } finally {
2109 if (outputStream != null) {
2110 try {
2111 outputStream.close();
2112 } catch (IOException e) {
2113 // ignore close errors
2114 }
2115 }
2116 }
2117 }
2118
2119 /**
2120 * Creates a File based on the current time stamp and uses
2121 * the mime type of the DataUri to get the extension.
2122 */
2123 private File getTarget(DataUri uri) throws IOException {
2124 File dir = mActivity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
2125 DateFormat format = new SimpleDateFormat(IMAGE_BASE_FORMAT);
2126 String nameBase = format.format(new Date());
2127 String mimeType = uri.getMimeType();
2128 MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
2129 String extension = mimeTypeMap.getExtensionFromMimeType(mimeType);
2130 if (extension == null) {
2131 Log.w(LOGTAG, "Unknown mime type in data URI" + mimeType);
2132 extension = FALLBACK_EXTENSION;
2133 }
2134 extension = "." + extension; // createTempFile needs the '.'
2135 File targetFile = File.createTempFile(nameBase, extension, dir);
2136 return targetFile;
2137 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002138 }
2139
Cary Clark8974d282010-11-22 10:46:05 -05002140 private static class SelectText implements OnMenuItemClickListener {
2141 private WebView mWebView;
2142
2143 public boolean onMenuItemClick(MenuItem item) {
2144 if (mWebView != null) {
2145 return mWebView.selectText();
2146 }
2147 return false;
2148 }
2149
2150 public SelectText(WebView webView) {
2151 mWebView = webView;
2152 }
2153
2154 }
2155
Michael Kolb8233fac2010-10-26 16:08:53 -07002156 /********************** TODO: UI stuff *****************************/
2157
2158 // these methods have been copied, they still need to be cleaned up
2159
2160 /****************** tabs ***************************************************/
2161
2162 // basic tab interactions:
2163
2164 // it is assumed that tabcontrol already knows about the tab
2165 protected void addTab(Tab tab) {
2166 mUi.addTab(tab);
2167 }
2168
2169 protected void removeTab(Tab tab) {
2170 mUi.removeTab(tab);
2171 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002172 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002173 }
2174
Michael Kolbf2055602011-04-09 17:20:03 -07002175 @Override
2176 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002177 // monkey protection against delayed start
2178 if (tab != null) {
2179 mTabControl.setCurrentTab(tab);
2180 // the tab is guaranteed to have a webview after setCurrentTab
2181 mUi.setActiveTab(tab);
2182 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002183 }
2184
John Reck8bcafc12011-08-29 16:43:02 -07002185 protected void closeEmptyTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002186 Tab current = mTabControl.getCurrentTab();
2187 if (current != null
2188 && current.getWebView().copyBackForwardList().getSize() == 0) {
John Reck8bcafc12011-08-29 16:43:02 -07002189 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002190 }
2191 }
2192
John Reck26b18322011-06-21 13:08:58 -07002193 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002194 // Dismiss the subwindow if applicable.
2195 dismissSubWindow(appTab);
2196 // Since we might kill the WebView, remove it from the
2197 // content view first.
2198 mUi.detachTab(appTab);
2199 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002200 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002201 // TODO: analyze why the remove and add are necessary
2202 mUi.attachTab(appTab);
2203 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002204 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002205 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002206 } else {
2207 // If the tab was the current tab, we have to attach
2208 // it to the view system again.
2209 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002210 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002211 }
2212 }
2213
2214 // Remove the sub window if it exists. Also called by TabControl when the
2215 // user clicks the 'X' to dismiss a sub window.
2216 public void dismissSubWindow(Tab tab) {
2217 removeSubWindow(tab);
2218 // dismiss the subwindow. This will destroy the WebView.
2219 tab.dismissSubWindow();
2220 getCurrentTopWebView().requestFocus();
2221 }
2222
2223 @Override
2224 public void removeSubWindow(Tab t) {
2225 if (t.getSubWebView() != null) {
2226 mUi.removeSubWindow(t.getSubViewContainer());
2227 }
2228 }
2229
2230 @Override
2231 public void attachSubWindow(Tab tab) {
2232 if (tab.getSubWebView() != null) {
2233 mUi.attachSubWindow(tab.getSubViewContainer());
2234 getCurrentTopWebView().requestFocus();
2235 }
2236 }
2237
Mathew Inwood29721c22011-06-29 17:55:24 +01002238 private Tab showPreloadedTab(final UrlData urlData) {
2239 if (!urlData.isPreloaded()) {
2240 return null;
2241 }
2242 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2243 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2244 if (sbQuery != null) {
Mathew Inwood9ad1eac2011-09-15 11:29:50 +01002245 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002246 // Could not submit query. Fallback to regular tab creation
2247 tabControl.destroy();
2248 return null;
2249 }
2250 }
Michael Kolbff6a7482011-07-26 16:37:15 -07002251 // check tab count and make room for new tab
2252 if (!mTabControl.canCreateNewTab()) {
2253 Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
2254 if (leastUsed != null) {
2255 closeTab(leastUsed);
2256 }
2257 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002258 Tab t = tabControl.getTab();
Mathew Inwoode09305e2011-09-02 12:03:26 +01002259 t.refreshIdAfterPreload();
Mathew Inwood29721c22011-06-29 17:55:24 +01002260 mTabControl.addPreloadedTab(t);
2261 addTab(t);
2262 setActiveTab(t);
2263 return t;
2264 }
2265
Michael Kolb7bcafde2011-05-09 13:55:59 -07002266 // open a non inconito tab with the given url data
2267 // and set as active tab
2268 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002269 Tab tab = showPreloadedTab(urlData);
2270 if (tab == null) {
2271 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002272 if ((tab != null) && !urlData.isEmpty()) {
2273 loadUrlDataIn(tab, urlData);
2274 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002275 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002276 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002277 }
2278
Michael Kolb843510f2010-12-09 10:51:49 -08002279 @Override
2280 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002281 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002282 }
2283
Michael Kolb8233fac2010-10-26 16:08:53 -07002284 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002285 public Tab openIncognitoTab() {
2286 return openTab(INCOGNITO_URI, true, true, false);
2287 }
2288
2289 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002290 public Tab openTab(String url, boolean incognito, boolean setActive,
2291 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002292 return openTab(url, incognito, setActive, useCurrent, null);
2293 }
2294
2295 @Override
2296 public Tab openTab(String url, Tab parent, boolean setActive,
2297 boolean useCurrent) {
2298 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2299 setActive, useCurrent, parent);
2300 }
2301
2302 public Tab openTab(String url, boolean incognito, boolean setActive,
2303 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002304 Tab tab = createNewTab(incognito, setActive, useCurrent);
2305 if (tab != null) {
John Reck5949c662011-05-27 09:52:29 -07002306 if (parent != null && parent != tab) {
2307 parent.addChildTab(tab);
2308 }
Michael Kolb519d2282011-05-09 17:03:19 -07002309 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002310 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002311 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002312 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002313 return tab;
2314 }
2315
2316 // this method will attempt to create a new tab
2317 // incognito: private browsing tab
2318 // setActive: ste tab as current tab
2319 // useCurrent: if no new tab can be created, return current tab
2320 private Tab createNewTab(boolean incognito, boolean setActive,
2321 boolean useCurrent) {
2322 Tab tab = null;
2323 if (mTabControl.canCreateNewTab()) {
2324 tab = mTabControl.createNewTab(incognito);
2325 addTab(tab);
2326 if (setActive) {
2327 setActiveTab(tab);
2328 }
2329 } else {
2330 if (useCurrent) {
2331 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002332 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002333 } else {
2334 mUi.showMaxTabsWarning();
2335 }
2336 }
2337 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002338 }
2339
John Reck2bc80422011-06-30 15:11:49 -07002340 @Override
2341 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2342 SnapshotTab tab = null;
2343 if (mTabControl.canCreateNewTab()) {
2344 tab = mTabControl.createSnapshotTab(snapshotId);
2345 addTab(tab);
2346 if (setActive) {
2347 setActiveTab(tab);
2348 }
2349 } else {
2350 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07002351 }
2352 return tab;
2353 }
2354
Michael Kolb8233fac2010-10-26 16:08:53 -07002355 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002356 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002357 * @return boolean True if we successfully switched to a different tab. If
2358 * the indexth tab is null, or if that tab is the same as
2359 * the current one, return false.
2360 */
2361 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002362 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002363 Tab currentTab = mTabControl.getCurrentTab();
2364 if (tab == null || tab == currentTab) {
2365 return false;
2366 }
2367 setActiveTab(tab);
2368 return true;
2369 }
2370
2371 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002372 public void closeCurrentTab() {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002373 closeCurrentTab(false);
2374 }
2375
2376 protected void closeCurrentTab(boolean andQuit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002377 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07002378 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07002379 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08002380 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002381 return;
2382 }
Michael Kolbc831b632011-05-11 09:30:34 -07002383 final Tab current = mTabControl.getCurrentTab();
2384 final int pos = mTabControl.getCurrentPosition();
2385 Tab newTab = current.getParent();
2386 if (newTab == null) {
2387 newTab = mTabControl.getTab(pos + 1);
2388 if (newTab == null) {
2389 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002390 }
2391 }
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002392 if (andQuit) {
2393 mTabControl.setCurrentTab(newTab);
2394 closeTab(current);
2395 } else if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002396 // Close window
2397 closeTab(current);
2398 }
2399 }
2400
2401 /**
2402 * Close the tab, remove its associated title bar, and adjust mTabControl's
2403 * current tab to a valid value.
2404 */
2405 @Override
2406 public void closeTab(Tab tab) {
John Reck28263772011-10-11 17:13:42 -07002407 if (tab == mTabControl.getCurrentTab()) {
2408 closeCurrentTab();
2409 } else {
2410 removeTab(tab);
2411 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002412 }
2413
Michael Kolb8233fac2010-10-26 16:08:53 -07002414 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07002415 protected void loadUrlFromContext(String url) {
2416 Tab tab = getCurrentTab();
2417 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002418 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07002419 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002420 url = UrlUtils.smartUrlFilter(url);
2421 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07002422 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07002423 }
2424 }
2425 }
2426
2427 /**
2428 * Load the URL into the given WebView and update the title bar
2429 * to reflect the new load. Call this instead of WebView.loadUrl
2430 * directly.
2431 * @param view The WebView used to load url.
2432 * @param url The URL to load.
2433 */
John Reck71e51422011-07-01 16:49:28 -07002434 @Override
2435 public void loadUrl(Tab tab, String url) {
John Reck26b18322011-06-21 13:08:58 -07002436 loadUrl(tab, url, null);
2437 }
2438
2439 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
2440 if (tab != null) {
2441 dismissSubWindow(tab);
2442 tab.loadUrl(url, headers);
Michael Kolba53c9892011-10-05 13:31:40 -07002443 mUi.onProgressChanged(tab);
John Reck26b18322011-06-21 13:08:58 -07002444 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002445 }
2446
2447 /**
2448 * Load UrlData into a Tab and update the title bar to reflect the new
2449 * load. Call this instead of UrlData.loadIn directly.
2450 * @param t The Tab used to load.
2451 * @param data The UrlData being loaded.
2452 */
2453 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07002454 if (data != null) {
2455 if (data.mVoiceIntent != null) {
2456 t.activateVoiceSearchMode(data.mVoiceIntent);
Michael Kolb14612442011-06-24 13:06:29 -07002457 } else if (data.isPreloaded()) {
2458 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07002459 } else {
2460 loadUrl(t, data.mUrl, data.mHeaders);
2461 }
2462 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002463 }
2464
John Reck30c714c2010-12-16 17:30:34 -08002465 @Override
2466 public void onUserCanceledSsl(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08002467 // TODO: Figure out the "right" behavior
John Reckef654f12011-07-12 16:42:08 -07002468 if (tab.canGoBack()) {
2469 tab.goBack();
John Reck30c714c2010-12-16 17:30:34 -08002470 } else {
John Reckef654f12011-07-12 16:42:08 -07002471 tab.loadUrl(mSettings.getHomePage(), null);
John Reck30c714c2010-12-16 17:30:34 -08002472 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002473 }
2474
2475 void goBackOnePageOrQuit() {
2476 Tab current = mTabControl.getCurrentTab();
2477 if (current == null) {
2478 /*
2479 * Instead of finishing the activity, simply push this to the back
2480 * of the stack and let ActivityManager to choose the foreground
2481 * activity. As BrowserActivity is singleTask, it will be always the
2482 * root of the task. So we can use either true or false for
2483 * moveTaskToBack().
2484 */
2485 mActivity.moveTaskToBack(true);
2486 return;
2487 }
John Reckef654f12011-07-12 16:42:08 -07002488 if (current.canGoBack()) {
2489 current.goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07002490 } else {
2491 // Check to see if we are closing a window that was created by
2492 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002493 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002494 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002495 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002496 // Now we close the other tab
2497 closeTab(current);
2498 } else {
Michael Kolbe28b3472011-08-04 16:54:31 -07002499 if ((current.getAppId() != null) || current.closeOnBack()) {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002500 closeCurrentTab(true);
Michael Kolbe28b3472011-08-04 16:54:31 -07002501 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002502 /*
2503 * Instead of finishing the activity, simply push this to the back
2504 * of the stack and let ActivityManager to choose the foreground
2505 * activity. As BrowserActivity is singleTask, it will be always the
2506 * root of the task. So we can use either true or false for
2507 * moveTaskToBack().
2508 */
2509 mActivity.moveTaskToBack(true);
2510 }
2511 }
2512 }
2513
2514 /**
2515 * Feed the previously stored results strings to the BrowserProvider so that
2516 * the SearchDialog will show them instead of the standard searches.
2517 * @param result String to show on the editable line of the SearchDialog.
2518 */
2519 @Override
2520 public void showVoiceSearchResults(String result) {
2521 ContentProviderClient client = mActivity.getContentResolver()
2522 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2523 ContentProvider prov = client.getLocalContentProvider();
2524 BrowserProvider bp = (BrowserProvider) prov;
2525 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2526 client.release();
2527
2528 Bundle bundle = createGoogleSearchSourceBundle(
2529 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2530 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2531 startSearch(result, false, bundle, false);
2532 }
2533
2534 private void startSearch(String initialQuery, boolean selectInitialQuery,
2535 Bundle appSearchData, boolean globalSearch) {
2536 if (appSearchData == null) {
2537 appSearchData = createGoogleSearchSourceBundle(
2538 GOOGLE_SEARCH_SOURCE_TYPE);
2539 }
2540
2541 SearchEngine searchEngine = mSettings.getSearchEngine();
2542 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2543 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2544 }
2545 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2546 globalSearch);
2547 }
2548
2549 private Bundle createGoogleSearchSourceBundle(String source) {
2550 Bundle bundle = new Bundle();
2551 bundle.putString(Search.SOURCE, source);
2552 return bundle;
2553 }
2554
2555 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002556 * helper method for key handler
2557 * returns the current tab if it can't advance
2558 */
Michael Kolbc831b632011-05-11 09:30:34 -07002559 private Tab getNextTab() {
2560 return mTabControl.getTab(Math.min(mTabControl.getTabCount() - 1,
2561 mTabControl.getCurrentPosition() + 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002562 }
2563
2564 /**
2565 * helper method for key handler
2566 * returns the current tab if it can't advance
2567 */
Michael Kolbc831b632011-05-11 09:30:34 -07002568 private Tab getPrevTab() {
2569 return mTabControl.getTab(Math.max(0,
2570 mTabControl.getCurrentPosition() - 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002571 }
2572
2573 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002574 * handle key events in browser
2575 *
2576 * @param keyCode
2577 * @param event
2578 * @return true if handled, false to pass to super
2579 */
2580 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002581 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002582 // Even if MENU is already held down, we need to call to super to open
2583 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002584 if (!noModifiers
2585 && ((KeyEvent.KEYCODE_MENU == keyCode)
2586 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2587 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002588 mMenuIsDown = true;
2589 return false;
2590 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002591
Cary Clark8ff8c662010-12-29 15:03:05 -05002592 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07002593 Tab tab = getCurrentTab();
2594 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05002595
Cary Clark160bbb92011-01-10 11:17:07 -05002596 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2597 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002598
Michael Kolb8233fac2010-10-26 16:08:53 -07002599 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002600 case KeyEvent.KEYCODE_TAB:
2601 if (event.isCtrlPressed()) {
2602 if (event.isShiftPressed()) {
2603 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002604 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002605 } else {
2606 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002607 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002608 }
2609 return true;
2610 }
2611 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002612 case KeyEvent.KEYCODE_SPACE:
2613 // WebView/WebTextView handle the keys in the KeyDown. As
2614 // the Activity's shortcut keys are only handled when WebView
2615 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002616 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002617 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002618 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002619 pageDown();
2620 }
2621 return true;
2622 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002623 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002624 event.startTracking();
2625 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07002626 case KeyEvent.KEYCODE_FORWARD:
2627 if (!noModifiers) break;
2628 tab.goForward();
2629 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002630 case KeyEvent.KEYCODE_DPAD_LEFT:
2631 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002632 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05002633 return true;
2634 }
2635 break;
2636 case KeyEvent.KEYCODE_DPAD_RIGHT:
2637 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002638 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05002639 return true;
2640 }
2641 break;
2642 case KeyEvent.KEYCODE_A:
2643 if (ctrl) {
2644 webView.selectAll();
2645 return true;
2646 }
2647 break;
Michael Kolba4183062011-01-16 10:43:21 -08002648// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002649 case KeyEvent.KEYCODE_C:
2650 if (ctrl) {
2651 webView.copySelection();
2652 return true;
2653 }
2654 break;
Michael Kolba4183062011-01-16 10:43:21 -08002655// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002656// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002657// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002658// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002659// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002660// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002661// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002662// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002663// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002664// case KeyEvent.KEYCODE_M: // unused
2665// case KeyEvent.KEYCODE_N: // in Chrome: new window
2666// case KeyEvent.KEYCODE_O: // in Chrome: open file
2667// case KeyEvent.KEYCODE_P: // in Chrome: print page
2668// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002669// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002670// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2671 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002672 // we can't use the ctrl/shift flags, they check for
2673 // exclusive use of a modifier
2674 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002675 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002676 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002677 } else {
2678 openTabToHomePage();
2679 }
2680 return true;
2681 }
2682 break;
2683// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2684// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb5ae15bd2011-08-16 17:09:27 -07002685// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002686// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2687// case KeyEvent.KEYCODE_Y: // unused
2688// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002689 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002690 // it is a regular key and webview is not null
2691 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002692 }
2693
John Recke6bf4ab2011-02-24 15:48:05 -08002694 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2695 switch(keyCode) {
2696 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07002697 if (mUi.isWebShowing()) {
Michael Kolb315d5022011-10-13 12:47:11 -07002698 bookmarksOrHistoryPicker(ComboViews.History);
John Recke6bf4ab2011-02-24 15:48:05 -08002699 return true;
2700 }
2701 break;
2702 }
2703 return false;
2704 }
2705
Michael Kolb8233fac2010-10-26 16:08:53 -07002706 boolean onKeyUp(int keyCode, KeyEvent event) {
Michael Kolb2814a362011-05-19 15:49:41 -07002707 if (KeyEvent.KEYCODE_MENU == keyCode) {
2708 mMenuIsDown = false;
2709 if (event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002710 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002711 }
2712 }
Cary Clark160bbb92011-01-10 11:17:07 -05002713 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002714 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002715 case KeyEvent.KEYCODE_BACK:
2716 if (event.isTracking() && !event.isCanceled()) {
2717 onBackKey();
2718 return true;
2719 }
2720 break;
2721 }
2722 return false;
2723 }
2724
2725 public boolean isMenuDown() {
2726 return mMenuIsDown;
2727 }
2728
Ben Murdoch8029a772010-11-16 11:58:21 +00002729 public void setupAutoFill(Message message) {
2730 // Open the settings activity at the AutoFill profile fragment so that
2731 // the user can create a new profile. When they return, we will dispatch
2732 // the message so that we can autofill the form using their new profile.
2733 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2734 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2735 AutoFillSettingsFragment.class.getName());
2736 mAutoFillSetupMessage = message;
2737 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2738 }
John Reckb3417f02011-01-14 11:01:05 -08002739
2740 @Override
Narayan Kamath5119edd2011-02-23 15:49:17 +00002741 public void registerDropdownChangeListener(DropdownChangeListener d) {
2742 mUi.registerDropdownChangeListener(d);
2743 }
Michael Kolbfbc579a2011-07-07 15:59:33 -07002744
2745 public boolean onSearchRequested() {
2746 mUi.editUrl(false);
2747 return true;
2748 }
2749
John Reck1cf4b792011-07-26 10:22:22 -07002750 @Override
2751 public boolean shouldCaptureThumbnails() {
2752 return mUi.shouldCaptureThumbnails();
2753 }
2754
Michael Kolbc3af0672011-08-09 10:24:41 -07002755 @Override
2756 public void setBlockEvents(boolean block) {
2757 mBlockEvents = block;
2758 }
2759
2760 public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002761 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002762 }
2763
2764 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002765 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002766 }
2767
2768 public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002769 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002770 }
2771
2772 public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002773 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002774 }
2775
2776 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002777 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002778 }
2779
Michael Kolb8233fac2010-10-26 16:08:53 -07002780}