blob: 81ba9411642a4b751096e99ad36751d8fec61089 [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) {
John Reck847b5322011-04-14 17:02:18 -0700265 doStart(icicle, intent);
266 } else {
267 mCrashRecoveryHandler.startRecovery(intent);
268 }
269 }
270
271 void doStart(final Bundle icicle, final Intent intent) {
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 Kolbc831b632011-05-11 09:30:34 -0700299 onPreloginFinished(icicle, intent, currentTabId, restoreIncognitoTabs);
Patrick Scott7d50a932011-02-04 09:27:26 -0500300 }
301 });
302 }
303
Michael Kolbc831b632011-05-11 09:30:34 -0700304 private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId,
Patrick Scott7d50a932011-02-04 09:27:26 -0500305 boolean restoreIncognitoTabs) {
Michael Kolbc831b632011-05-11 09:30:34 -0700306 if (currentTabId == -1) {
John Reck1cf4b792011-07-26 10:22:22 -0700307 BackgroundHandler.execute(new PruneThumbnails(mActivity, null));
Michael Kolb8233fac2010-10-26 16:08:53 -0700308 final Bundle extra = intent.getExtras();
309 // Create an initial tab.
310 // If the intent is ACTION_VIEW and data is not null, the Browser is
311 // invoked to view the content by another application. In this case,
312 // the tab will be close when exit.
Michael Kolb14612442011-06-24 13:06:29 -0700313 UrlData urlData = IntentHandler.getUrlDataFromIntent(intent);
Michael Kolb7bcafde2011-05-09 13:55:59 -0700314 Tab t = null;
315 if (urlData.isEmpty()) {
316 t = openTabToHomePage();
317 } else {
318 t = openTab(urlData);
319 }
320 if (t != null) {
321 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
322 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700323 WebView webView = t.getWebView();
324 if (extra != null) {
325 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
326 if (scale > 0 && scale <= 1000) {
327 webView.setInitialScale(scale);
328 }
329 }
John Reckd8c74522011-06-14 08:45:00 -0700330 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700331 } else {
Michael Kolbc831b632011-05-11 09:30:34 -0700332 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
Patrick Scott7d50a932011-02-04 09:27:26 -0500333 mUi.needsRestoreAllTabs());
John Reck1cf4b792011-07-26 10:22:22 -0700334 List<Tab> tabs = mTabControl.getTabs();
335 ArrayList<Long> restoredTabs = new ArrayList<Long>(tabs.size());
336 for (Tab t : tabs) {
337 restoredTabs.add(t.getId());
338 }
339 BackgroundHandler.execute(new PruneThumbnails(mActivity, restoredTabs));
John Reck52be4782011-08-26 15:37:29 -0700340 if (tabs.size() == 0) {
341 openTabToHomePage();
342 }
John Reck1cf4b792011-07-26 10:22:22 -0700343 mUi.updateTabs(tabs);
Michael Kolb8233fac2010-10-26 16:08:53 -0700344 // TabControl.restoreState() will create a new tab even if
345 // restoring the state fails.
346 setActiveTab(mTabControl.getCurrentTab());
John Reck9dd4a412011-10-05 14:55:30 -0700347 // Handle the intent if needed. If icicle != null, we are restoring
348 // and the intent will be stale - ignore it.
349 if (icicle == null) {
350 mIntentHandler.onNewIntent(intent);
351 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700352 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700353 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700354 String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb8233fac2010-10-26 16:08:53 -0700355 if (jsFlags.trim().length() != 0) {
356 getCurrentWebView().setJsFlags(jsFlags);
357 }
John Reck439c9a52010-12-14 10:04:39 -0800358 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
359 bookmarksOrHistoryPicker(false);
360 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700361 }
362
John Reck1cf4b792011-07-26 10:22:22 -0700363 private static class PruneThumbnails implements Runnable {
364 private Context mContext;
365 private List<Long> mIds;
366
367 PruneThumbnails(Context context, List<Long> preserveIds) {
368 mContext = context.getApplicationContext();
369 mIds = preserveIds;
370 }
371
372 @Override
373 public void run() {
374 ContentResolver cr = mContext.getContentResolver();
375 if (mIds == null || mIds.size() == 0) {
376 cr.delete(Thumbnails.CONTENT_URI, null, null);
377 } else {
378 int length = mIds.size();
379 StringBuilder where = new StringBuilder();
380 where.append(Thumbnails._ID);
381 where.append(" not in (");
382 for (int i = 0; i < length; i++) {
383 where.append(mIds.get(i));
384 if (i < (length - 1)) {
385 where.append(",");
386 }
387 }
388 where.append(")");
389 cr.delete(Thumbnails.CONTENT_URI, where.toString(), null);
390 }
391 }
392
393 }
394
Michael Kolb1514bb72010-11-22 09:11:48 -0800395 @Override
396 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700397 return mFactory;
398 }
399
400 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800401 public void onSetWebView(Tab tab, WebView view) {
402 mUi.onSetWebView(tab, view);
403 }
404
405 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800406 public void createSubWindow(Tab tab) {
407 endActionMode();
408 WebView mainView = tab.getWebView();
409 WebView subView = mFactory.createWebView((mainView == null)
410 ? false
411 : mainView.isPrivateBrowsingEnabled());
412 mUi.createSubWindow(tab, subView);
413 }
414
415 @Override
Michael Kolb14612442011-06-24 13:06:29 -0700416 public Context getContext() {
417 return mActivity;
418 }
419
420 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700421 public Activity getActivity() {
422 return mActivity;
423 }
424
425 void setUi(UI ui) {
426 mUi = ui;
427 }
428
429 BrowserSettings getSettings() {
430 return mSettings;
431 }
432
433 IntentHandler getIntentHandler() {
434 return mIntentHandler;
435 }
436
437 @Override
438 public UI getUi() {
439 return mUi;
440 }
441
442 int getMaxTabs() {
443 return mActivity.getResources().getInteger(R.integer.max_tabs);
444 }
445
446 @Override
447 public TabControl getTabControl() {
448 return mTabControl;
449 }
450
Michael Kolb1bf23132010-11-19 12:55:12 -0800451 @Override
452 public List<Tab> getTabs() {
453 return mTabControl.getTabs();
454 }
455
John Reckaf262e72011-07-25 13:55:44 -0700456 // Open the icon database.
457 private void openIconDatabase() {
458 // We have to call getInstance on the UI thread
459 final WebIconDatabase instance = WebIconDatabase.getInstance();
460 BackgroundHandler.execute(new Runnable() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000461
John Reckaf262e72011-07-25 13:55:44 -0700462 @Override
463 public void run() {
464 instance.open(mActivity.getDir("icons", 0).getPath());
Michael Kolb8233fac2010-10-26 16:08:53 -0700465 }
John Reckaf262e72011-07-25 13:55:44 -0700466 });
Michael Kolb8233fac2010-10-26 16:08:53 -0700467 }
468
469 private void startHandler() {
470 mHandler = new Handler() {
471
472 @Override
473 public void handleMessage(Message msg) {
474 switch (msg.what) {
475 case OPEN_BOOKMARKS:
476 bookmarksOrHistoryPicker(false);
477 break;
478 case FOCUS_NODE_HREF:
479 {
480 String url = (String) msg.getData().get("url");
481 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500482 String src = (String) msg.getData().get("src");
483 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700484 if (TextUtils.isEmpty(url)) {
485 break;
486 }
487 HashMap focusNodeMap = (HashMap) msg.obj;
488 WebView view = (WebView) focusNodeMap.get("webview");
489 // Only apply the action if the top window did not change.
490 if (getCurrentTopWebView() != view) {
491 break;
492 }
493 switch (msg.arg1) {
494 case R.id.open_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700495 loadUrlFromContext(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700496 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500497 case R.id.view_image_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700498 loadUrlFromContext(src);
Cary Clark043c2d62010-12-15 11:19:39 -0500499 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500500 case R.id.open_newtab_context_menu_id:
501 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -0700502 openTab(url, parent,
503 !mSettings.openInBackground(), true);
Leon Scroggins026f2542010-11-22 13:26:12 -0500504 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700505 case R.id.copy_link_context_menu_id:
506 copy(url);
507 break;
508 case R.id.save_link_context_menu_id:
509 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500510 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000511 mActivity, url, null, null, null,
512 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700513 break;
514 }
515 break;
516 }
517
518 case LOAD_URL:
John Reck26b18322011-06-21 13:08:58 -0700519 loadUrlFromContext((String) msg.obj);
Michael Kolb8233fac2010-10-26 16:08:53 -0700520 break;
521
522 case STOP_LOAD:
523 stopLoading();
524 break;
525
526 case RELEASE_WAKELOCK:
John Reckf57c0292011-07-21 18:15:39 -0700527 if (mWakeLock != null && mWakeLock.isHeld()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700528 mWakeLock.release();
529 // if we reach here, Browser should be still in the
530 // background loading after WAKELOCK_TIMEOUT (5-min).
531 // To avoid burning the battery, stop loading.
532 mTabControl.stopAllLoading();
533 }
534 break;
535
536 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800537 Tab tab = (Tab) msg.obj;
538 if (tab != null) {
539 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700540 }
541 break;
542 }
543 }
544 };
545
546 }
547
John Reckef654f12011-07-12 16:42:08 -0700548 @Override
Martijn Coenenb2f93552011-06-14 10:48:35 +0200549 public Tab getCurrentTab() {
550 return mTabControl.getCurrentTab();
551 }
552
Michael Kolbba99c5d2010-11-29 14:57:41 -0800553 @Override
554 public void shareCurrentPage() {
555 shareCurrentPage(mTabControl.getCurrentTab());
556 }
557
558 private void shareCurrentPage(Tab tab) {
559 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800560 sharePage(mActivity, tab.getTitle(),
561 tab.getUrl(), tab.getFavicon(),
562 createScreenshot(tab.getWebView(),
563 getDesiredThumbnailWidth(mActivity),
564 getDesiredThumbnailHeight(mActivity)));
565 }
566 }
567
Michael Kolb8233fac2010-10-26 16:08:53 -0700568 /**
569 * Share a page, providing the title, url, favicon, and a screenshot. Uses
570 * an {@link Intent} to launch the Activity chooser.
571 * @param c Context used to launch a new Activity.
572 * @param title Title of the page. Stored in the Intent with
573 * {@link Intent#EXTRA_SUBJECT}
574 * @param url URL of the page. Stored in the Intent with
575 * {@link Intent#EXTRA_TEXT}
576 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
577 * with {@link Browser#EXTRA_SHARE_FAVICON}
578 * @param screenshot Bitmap of a screenshot of the page. Stored in the
579 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
580 */
581 static final void sharePage(Context c, String title, String url,
582 Bitmap favicon, Bitmap screenshot) {
583 Intent send = new Intent(Intent.ACTION_SEND);
584 send.setType("text/plain");
585 send.putExtra(Intent.EXTRA_TEXT, url);
586 send.putExtra(Intent.EXTRA_SUBJECT, title);
587 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
588 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
589 try {
590 c.startActivity(Intent.createChooser(send, c.getString(
591 R.string.choosertitle_sharevia)));
592 } catch(android.content.ActivityNotFoundException ex) {
593 // if no app handles it, do nothing
594 }
595 }
596
597 private void copy(CharSequence text) {
598 ClipboardManager cm = (ClipboardManager) mActivity
599 .getSystemService(Context.CLIPBOARD_SERVICE);
600 cm.setText(text);
601 }
602
603 // lifecycle
604
605 protected void onConfgurationChanged(Configuration config) {
606 mConfigChanged = true;
607 if (mPageDialogsHandler != null) {
608 mPageDialogsHandler.onConfigurationChanged(config);
609 }
610 mUi.onConfigurationChanged(config);
611 }
612
613 @Override
614 public void handleNewIntent(Intent intent) {
Michael Kolb59e232c2011-08-18 17:19:53 -0700615 if (!mUi.isWebShowing()) {
616 mUi.showWeb(false);
617 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700618 mIntentHandler.onNewIntent(intent);
619 }
620
621 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800622 if (mUi.isCustomViewShowing()) {
623 hideCustomView();
624 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700625 if (mActivityPaused) {
626 Log.e(LOGTAG, "BrowserActivity is already paused.");
627 return;
628 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700629 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800630 Tab tab = mTabControl.getCurrentTab();
631 if (tab != null) {
632 tab.pause();
633 if (!pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700634 if (mWakeLock == null) {
635 PowerManager pm = (PowerManager) mActivity
636 .getSystemService(Context.POWER_SERVICE);
637 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
638 }
Michael Kolb70976932010-11-30 11:34:01 -0800639 mWakeLock.acquire();
640 mHandler.sendMessageDelayed(mHandler
641 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
642 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700643 }
644 mUi.onPause();
645 mNetworkHandler.onPause();
646
647 WebView.disablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100648 NfcHandler.unregister(mActivity);
John Reckd7dd9b22011-08-30 09:18:29 -0700649 if (sThumbnailBitmap != null) {
650 sThumbnailBitmap.recycle();
651 sThumbnailBitmap = null;
652 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700653 }
654
John Reck1cf4b792011-07-26 10:22:22 -0700655 void onSaveInstanceState(Bundle outState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700656 // the default implementation requires each view to have an id. As the
657 // browser handles the state itself and it doesn't use id for the views,
658 // don't call the default implementation. Otherwise it will trigger the
659 // warning like this, "couldn't save which view has focus because the
660 // focused view XXX has no id".
661
662 // Save all the tabs
John Reck1cf4b792011-07-26 10:22:22 -0700663 mTabControl.saveState(outState);
John Reck24f18262011-06-17 14:47:20 -0700664 if (!outState.isEmpty()) {
665 // Save time so that we know how old incognito tabs (if any) are.
666 outState.putSerializable("lastActiveDate", Calendar.getInstance());
667 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700668 }
669
670 void onResume() {
671 if (!mActivityPaused) {
672 Log.e(LOGTAG, "BrowserActivity is already resumed.");
673 return;
674 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700675 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800676 Tab current = mTabControl.getCurrentTab();
677 if (current != null) {
678 current.resume();
679 resumeWebViewTimers(current);
680 }
John Reckf57c0292011-07-21 18:15:39 -0700681 releaseWakeLock();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200682
Michael Kolb8233fac2010-10-26 16:08:53 -0700683 mUi.onResume();
684 mNetworkHandler.onResume();
685 WebView.enablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100686 NfcHandler.register(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700687 }
688
John Reckf57c0292011-07-21 18:15:39 -0700689 private void releaseWakeLock() {
690 if (mWakeLock != null && mWakeLock.isHeld()) {
691 mHandler.removeMessages(RELEASE_WAKELOCK);
692 mWakeLock.release();
693 }
694 }
695
Michael Kolb70976932010-11-30 11:34:01 -0800696 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800697 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800698 * @param tab guaranteed non-null
699 */
700 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700701 boolean inLoad = tab.inPageLoad();
702 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
703 CookieSyncManager.getInstance().startSync();
704 WebView w = tab.getWebView();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100705 WebViewTimersControl.getInstance().onBrowserActivityResume(w);
Michael Kolb8233fac2010-10-26 16:08:53 -0700706 }
707 }
708
Michael Kolb70976932010-11-30 11:34:01 -0800709 /**
710 * Pause all WebView timers using the WebView of the given tab
711 * @param tab
712 * @return true if the timers are paused or tab is null
713 */
714 private boolean pauseWebViewTimers(Tab tab) {
715 if (tab == null) {
716 return true;
717 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700718 CookieSyncManager.getInstance().stopSync();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100719 WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView());
Michael Kolb8233fac2010-10-26 16:08:53 -0700720 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700721 }
Michael Kolb70976932010-11-30 11:34:01 -0800722 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700723 }
724
725 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800726 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700727 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
728 mUploadHandler = null;
729 }
730 if (mTabControl == null) return;
731 mUi.onDestroy();
732 // Remove the current tab and sub window
733 Tab t = mTabControl.getCurrentTab();
734 if (t != null) {
735 dismissSubWindow(t);
736 removeTab(t);
737 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500738 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700739 // Destroy all the tabs
740 mTabControl.destroy();
741 WebIconDatabase.getInstance().close();
742 // Stop watching the default geolocation permissions
743 mSystemAllowGeolocationOrigins.stop();
744 mSystemAllowGeolocationOrigins = null;
745 }
746
747 protected boolean isActivityPaused() {
748 return mActivityPaused;
749 }
750
751 protected void onLowMemory() {
752 mTabControl.freeMemory();
753 }
754
755 @Override
756 public boolean shouldShowErrorConsole() {
757 return mShouldShowErrorConsole;
758 }
759
760 protected void setShouldShowErrorConsole(boolean show) {
761 if (show == mShouldShowErrorConsole) {
762 // Nothing to do.
763 return;
764 }
765 mShouldShowErrorConsole = show;
766 Tab t = mTabControl.getCurrentTab();
767 if (t == null) {
768 // There is no current tab so we cannot toggle the error console
769 return;
770 }
771 mUi.setShouldShowErrorConsole(t, show);
772 }
773
774 @Override
775 public void stopLoading() {
776 mLoadStopped = true;
777 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700778 WebView w = getCurrentTopWebView();
779 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700780 mUi.onPageStopped(tab);
781 }
782
783 boolean didUserStopLoading() {
784 return mLoadStopped;
785 }
786
787 // WebViewController
788
789 @Override
John Reck324d4402011-01-11 16:56:42 -0800790 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700791
792 // We've started to load a new page. If there was a pending message
793 // to save a screenshot then we will now take the new page and save
794 // an incorrect screenshot. Therefore, remove any pending thumbnail
795 // messages from the queue.
796 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800797 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700798
799 // reset sync timer to avoid sync starts during loading a page
800 CookieSyncManager.getInstance().resetSync();
801
802 if (!mNetworkHandler.isNetworkUp()) {
803 view.setNetworkAvailable(false);
804 }
805
806 // when BrowserActivity just starts, onPageStarted may be called before
807 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
808 // to start the timer. As we won't switch tabs while an activity is in
809 // pause state, we can ensure calling resume and pause in pair.
810 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800811 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700812 }
813 mLoadStopped = false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700814 endActionMode();
815
John Reck30c714c2010-12-16 17:30:34 -0800816 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700817
John Reck324d4402011-01-11 16:56:42 -0800818 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700819 // update the bookmark database for favicon
820 maybeUpdateFavicon(tab, null, url, favicon);
821
822 Performance.tracePageStart(url);
823
824 // Performance probe
825 if (false) {
826 Performance.onPageStarted();
827 }
828
829 }
830
831 @Override
John Reck324d4402011-01-11 16:56:42 -0800832 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800833 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800834 if (!tab.isPrivateBrowsingEnabled()
John Reckd8c74522011-06-14 08:45:00 -0700835 && !TextUtils.isEmpty(tab.getUrl())
836 && !tab.isSnapshot()) {
John Recka1696282011-07-08 14:10:37 -0700837 // Only update the bookmark screenshot if the user did not
838 // cancel the load early and there is not already
839 // a pending update for the tab.
Michael Kolb8233fac2010-10-26 16:08:53 -0700840 if (tab.inForeground() && !didUserStopLoading()
841 || !tab.inForeground()) {
John Recka1696282011-07-08 14:10:37 -0700842 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
843 mHandler.sendMessageDelayed(mHandler.obtainMessage(
844 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
845 500);
846 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700847 }
848 }
849 // pause the WebView timer and release the wake lock if it is finished
850 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800851 if (mActivityPaused && pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700852 releaseWakeLock();
Michael Kolb8233fac2010-10-26 16:08:53 -0700853 }
Martijn Coenenb2f93552011-06-14 10:48:35 +0200854
Michael Kolb8233fac2010-10-26 16:08:53 -0700855 // Performance probe
856 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800857 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700858 }
859
860 Performance.tracePageFinished();
861 }
862
863 @Override
John Reck30c714c2010-12-16 17:30:34 -0800864 public void onProgressChanged(Tab tab) {
John Reck6c2e2f32011-08-22 13:41:23 -0700865 mCrashRecoveryHandler.backupState();
John Reck30c714c2010-12-16 17:30:34 -0800866 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700867
868 if (newProgress == 100) {
869 CookieSyncManager.getInstance().sync();
870 // onProgressChanged() may continue to be called after the main
871 // frame has finished loading, as any remaining sub frames continue
872 // to load. We'll only get called once though with newProgress as
873 // 100 when everything is loaded. (onPageFinished is called once
874 // when the main frame completes loading regardless of the state of
875 // any sub frames so calls to onProgressChanges may continue after
876 // onPageFinished has executed)
877 if (mInLoad) {
878 mInLoad = false;
879 updateInLoadMenuItems(mCachedMenu);
880 }
881 } else {
882 if (!mInLoad) {
883 // onPageFinished may have already been called but a subframe is
884 // still loading and updating the progress. Reset mInLoad and
885 // update the menu items.
886 mInLoad = true;
887 updateInLoadMenuItems(mCachedMenu);
888 }
889 }
John Reck30c714c2010-12-16 17:30:34 -0800890 mUi.onProgressChanged(tab);
891 }
892
893 @Override
Steve Block2466eff2011-10-03 15:33:09 +0100894 public void onUpdatedSecurityState(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800895 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700896 }
897
898 @Override
899 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800900 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800901 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800902 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700903 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
904 return;
905 }
906 // Update the title in the history database if not in private browsing mode
907 if (!tab.isPrivateBrowsingEnabled()) {
John Reckf57c0292011-07-21 18:15:39 -0700908 DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700909 }
910 }
911
912 @Override
913 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800914 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700915 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
916 }
917
918 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800919 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
920 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700921 }
922
923 @Override
924 public boolean shouldOverrideKeyEvent(KeyEvent event) {
925 if (mMenuIsDown) {
926 // only check shortcut key when MENU is held
927 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
928 event);
929 } else {
930 return false;
931 }
932 }
933
934 @Override
935 public void onUnhandledKeyEvent(KeyEvent event) {
936 if (!isActivityPaused()) {
937 if (event.getAction() == KeyEvent.ACTION_DOWN) {
938 mActivity.onKeyDown(event.getKeyCode(), event);
939 } else {
940 mActivity.onKeyUp(event.getKeyCode(), event);
941 }
942 }
943 }
944
945 @Override
John Reck324d4402011-01-11 16:56:42 -0800946 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700947 // Don't save anything in private browsing mode
948 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800949 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700950
John Reck324d4402011-01-11 16:56:42 -0800951 if (TextUtils.isEmpty(url)
952 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700953 return;
954 }
John Reckf57c0292011-07-21 18:15:39 -0700955 DataController.getInstance(mActivity).updateVisitedHistory(url);
John Reck6c2e2f32011-08-22 13:41:23 -0700956 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -0700957 }
958
959 @Override
960 public void getVisitedHistory(final ValueCallback<String[]> callback) {
961 AsyncTask<Void, Void, String[]> task =
962 new AsyncTask<Void, Void, String[]>() {
963 @Override
964 public String[] doInBackground(Void... unused) {
965 return Browser.getVisitedHistory(mActivity.getContentResolver());
966 }
967 @Override
968 public void onPostExecute(String[] result) {
969 callback.onReceiveValue(result);
970 }
971 };
972 task.execute();
973 }
974
975 @Override
976 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
977 final HttpAuthHandler handler, final String host,
978 final String realm) {
979 String username = null;
980 String password = null;
981
982 boolean reuseHttpAuthUsernamePassword
983 = handler.useHttpAuthUsernamePassword();
984
985 if (reuseHttpAuthUsernamePassword && view != null) {
986 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
987 if (credentials != null && credentials.length == 2) {
988 username = credentials[0];
989 password = credentials[1];
990 }
991 }
992
993 if (username != null && password != null) {
994 handler.proceed(username, password);
995 } else {
Ben Murdochfdd37112011-08-05 15:48:14 +0100996 if (tab.inForeground() && !handler.suppressDialog()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700997 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
998 } else {
999 handler.cancel();
1000 }
1001 }
1002 }
1003
1004 @Override
1005 public void onDownloadStart(Tab tab, String url, String userAgent,
1006 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001007 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -05001008 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001009 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
1010 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001011 // This Tab was opened for the sole purpose of downloading a
1012 // file. Remove it.
1013 if (tab == mTabControl.getCurrentTab()) {
1014 // In this case, the Tab is still on top.
1015 goBackOnePageOrQuit();
1016 } else {
1017 // In this case, it is not.
1018 closeTab(tab);
1019 }
1020 }
1021 }
1022
1023 @Override
1024 public Bitmap getDefaultVideoPoster() {
1025 return mUi.getDefaultVideoPoster();
1026 }
1027
1028 @Override
1029 public View getVideoLoadingProgressView() {
1030 return mUi.getVideoLoadingProgressView();
1031 }
1032
1033 @Override
1034 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1035 SslError error) {
1036 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1037 }
1038
Patrick Scott92066772011-03-10 08:46:27 -05001039 @Override
1040 public void showAutoLogin(Tab tab) {
1041 assert tab.inForeground();
1042 // Update the title bar to show the auto-login request.
1043 mUi.showAutoLogin(tab);
1044 }
1045
1046 @Override
1047 public void hideAutoLogin(Tab tab) {
1048 assert tab.inForeground();
1049 mUi.hideAutoLogin(tab);
1050 }
1051
Michael Kolb8233fac2010-10-26 16:08:53 -07001052 // helper method
1053
1054 /*
1055 * Update the favorites icon if the private browsing isn't enabled and the
1056 * icon is valid.
1057 */
1058 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1059 final String url, Bitmap favicon) {
1060 if (favicon == null) {
1061 return;
1062 }
1063 if (!tab.isPrivateBrowsingEnabled()) {
1064 Bookmarks.updateFavicon(mActivity
1065 .getContentResolver(), originalUrl, url, favicon);
1066 }
1067 }
1068
Leon Scroggins4cd97792010-12-03 15:31:56 -05001069 @Override
1070 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001071 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001072 mUi.bookmarkedStatusHasChanged(tab);
1073 }
1074
Michael Kolb8233fac2010-10-26 16:08:53 -07001075 // end WebViewController
1076
1077 protected void pageUp() {
1078 getCurrentTopWebView().pageUp(false);
1079 }
1080
1081 protected void pageDown() {
1082 getCurrentTopWebView().pageDown(false);
1083 }
1084
1085 // callback from phone title bar
1086 public void editUrl() {
1087 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001088 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001089 }
1090
Michael Kolbcfa3af52010-12-14 10:36:11 -08001091 public void startVoiceSearch() {
1092 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1093 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1094 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1095 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1096 mActivity.getComponentName().flattenToString());
1097 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001098 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001099 mActivity.startActivity(intent);
1100 }
1101
Michael Kolb11d19782011-03-20 10:17:40 -07001102 @Override
1103 public void activateVoiceSearchMode(String title, List<String> results) {
1104 mUi.showVoiceTitleBar(title, results);
Michael Kolb8233fac2010-10-26 16:08:53 -07001105 }
1106
1107 public void revertVoiceSearchMode(Tab tab) {
1108 mUi.revertVoiceTitleBar(tab);
1109 }
1110
Michael Kolb736990c2011-03-20 10:01:20 -07001111 public boolean supportsVoiceSearch() {
John Reck35e9dd62011-04-25 09:01:54 -07001112 SearchEngine searchEngine = getSettings().getSearchEngine();
Michael Kolb736990c2011-03-20 10:01:20 -07001113 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1114 }
1115
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001116 public void showCustomView(Tab tab, View view, int requestedOrientation,
Michael Kolb8233fac2010-10-26 16:08:53 -07001117 WebChromeClient.CustomViewCallback callback) {
1118 if (tab.inForeground()) {
1119 if (mUi.isCustomViewShowing()) {
1120 callback.onCustomViewHidden();
1121 return;
1122 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001123 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001124 // Save the menu state and set it to empty while the custom
1125 // view is showing.
1126 mOldMenuState = mMenuState;
1127 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001128 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001129 }
1130 }
1131
1132 @Override
1133 public void hideCustomView() {
1134 if (mUi.isCustomViewShowing()) {
1135 mUi.onHideCustomView();
1136 // Reset the old menu state.
1137 mMenuState = mOldMenuState;
1138 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001139 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001140 }
1141 }
1142
1143 protected void onActivityResult(int requestCode, int resultCode,
1144 Intent intent) {
1145 if (getCurrentTopWebView() == null) return;
1146 switch (requestCode) {
1147 case PREFERENCES_PAGE:
1148 if (resultCode == Activity.RESULT_OK && intent != null) {
1149 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001150 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001151 mTabControl.removeParentChildRelationShips();
1152 }
1153 }
1154 break;
1155 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001156 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001157 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001158 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001159 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001160 case AUTOFILL_SETUP:
1161 // Determine whether a profile was actually set up or not
1162 // and if so, send the message back to the WebTextView to
1163 // fill the form with the new profile.
1164 if (getSettings().getAutoFillProfile() != null) {
1165 mAutoFillSetupMessage.sendToTarget();
1166 mAutoFillSetupMessage = null;
1167 }
1168 break;
John Reckd3e4d5b2011-07-13 15:48:43 -07001169 case COMBO_VIEW:
1170 if (intent == null || resultCode != Activity.RESULT_OK) {
1171 break;
1172 }
John Reck3ba45532011-08-11 16:26:53 -07001173 mUi.showWeb(false);
John Reckd3e4d5b2011-07-13 15:48:43 -07001174 if (Intent.ACTION_VIEW.equals(intent.getAction())) {
1175 Tab t = getCurrentTab();
1176 Uri uri = intent.getData();
1177 loadUrl(t, uri.toString());
1178 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
1179 String[] urls = intent.getStringArrayExtra(
1180 ComboViewActivity.EXTRA_OPEN_ALL);
1181 Tab parent = getCurrentTab();
1182 for (String url : urls) {
1183 parent = openTab(url, parent,
1184 !mSettings.openInBackground(), true);
1185 }
1186 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
1187 long id = intent.getLongExtra(
1188 ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
1189 if (id >= 0) {
1190 createNewSnapshotTab(id, true);
1191 }
1192 }
1193 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001194 default:
1195 break;
1196 }
1197 getCurrentTopWebView().requestFocus();
1198 }
1199
1200 /**
1201 * Open the Go page.
1202 * @param startWithHistory If true, open starting on the history tab.
1203 * Otherwise, start with the bookmarks tab.
1204 */
1205 @Override
1206 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1207 if (mTabControl.getCurrentWebView() == null) {
1208 return;
1209 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001210 // clear action mode
1211 if (isInCustomActionMode()) {
1212 endActionMode();
1213 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001214 Bundle extras = new Bundle();
1215 // Disable opening in a new window if we have maxed out the windows
1216 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1217 !mTabControl.canCreateNewTab());
John Reck2bc80422011-06-30 15:11:49 -07001218 mUi.showComboView(startWithHistory
1219 ? ComboViews.History : ComboViews.Bookmarks, 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();
1515 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1516 counter.setVisible(showDebugSettings);
1517 counter.setEnabled(showDebugSettings);
John Reck42229bc2011-08-19 13:26:43 -07001518 final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
1519 uaSwitcher.setChecked(isDesktopUa);
John Recke1a03a32011-09-14 17:04:16 -07001520 menu.setGroupVisible(R.id.LIVE_MENU, isLive);
1521 menu.setGroupVisible(R.id.SNAPSHOT_MENU, !isLive);
Michael Kolb4bf79712011-07-14 14:18:12 -07001522
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001523 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001524 }
1525
Michael Kolb8233fac2010-10-26 16:08:53 -07001526 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001527 if (null == getCurrentTopWebView()) {
1528 return false;
1529 }
1530 if (mMenuIsDown) {
1531 // The shortcut action consumes the MENU. Even if it is still down,
1532 // it won't trigger the next shortcut action. In the case of the
1533 // shortcut action triggering a new activity, like Bookmarks, we
1534 // won't get onKeyUp for MENU. So it is important to reset it here.
1535 mMenuIsDown = false;
1536 }
Michael Kolb3ca12752011-07-20 13:52:25 -07001537 if (mUi.onOptionsItemSelected(item)) {
1538 // ui callback handled it
1539 return true;
1540 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001541 switch (item.getItemId()) {
1542 // -- Main menu
1543 case R.id.new_tab_menu_id:
1544 openTabToHomePage();
1545 break;
1546
1547 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001548 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001549 break;
1550
1551 case R.id.goto_menu_id:
1552 editUrl();
1553 break;
1554
1555 case R.id.bookmarks_menu_id:
1556 bookmarksOrHistoryPicker(false);
1557 break;
1558
Michael Kolb8233fac2010-10-26 16:08:53 -07001559 case R.id.add_bookmark_menu_id:
John Recka60fffa2011-09-06 16:30:29 -07001560 Intent bookmarkIntent = createBookmarkCurrentPageIntent(false);
1561 if (bookmarkIntent != null) {
1562 mActivity.startActivity(bookmarkIntent);
1563 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001564 break;
1565
1566 case R.id.stop_reload_menu_id:
1567 if (mInLoad) {
1568 stopLoading();
1569 } else {
1570 getCurrentTopWebView().reload();
1571 }
1572 break;
1573
1574 case R.id.back_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001575 getCurrentTab().goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07001576 break;
1577
1578 case R.id.forward_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001579 getCurrentTab().goForward();
Michael Kolb8233fac2010-10-26 16:08:53 -07001580 break;
1581
1582 case R.id.close_menu_id:
1583 // Close the subwindow if it exists.
1584 if (mTabControl.getCurrentSubWindow() != null) {
1585 dismissSubWindow(mTabControl.getCurrentTab());
1586 break;
1587 }
1588 closeCurrentTab();
1589 break;
1590
1591 case R.id.homepage_menu_id:
1592 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07001593 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07001594 break;
1595
1596 case R.id.preferences_menu_id:
1597 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1598 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1599 getCurrentTopWebView().getUrl());
1600 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1601 break;
1602
1603 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001604 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001605 break;
1606
John Reck2bc80422011-06-30 15:11:49 -07001607 case R.id.save_snapshot_menu_id:
1608 final Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07001609 if (source == null) break;
John Reckd8c74522011-06-14 08:45:00 -07001610 final ContentResolver cr = mActivity.getContentResolver();
1611 final ContentValues values = source.createSnapshotValues();
John Reck2bc80422011-06-30 15:11:49 -07001612 if (values != null) {
1613 new AsyncTask<Tab, Void, Long>() {
John Reckd8c74522011-06-14 08:45:00 -07001614
John Reck2bc80422011-06-30 15:11:49 -07001615 @Override
1616 protected Long doInBackground(Tab... params) {
1617 Uri result = cr.insert(Snapshots.CONTENT_URI, values);
1618 long id = ContentUris.parseId(result);
1619 return id;
John Reckd8c74522011-06-14 08:45:00 -07001620 }
John Reckf33b1632011-06-04 20:00:23 -07001621
John Reck2bc80422011-06-30 15:11:49 -07001622 @Override
1623 protected void onPostExecute(Long id) {
1624 Bundle b = new Bundle();
1625 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
1626 mUi.showComboView(ComboViews.Snapshots, b);
1627 };
1628 }.execute(source);
1629 } else {
1630 Toast.makeText(mActivity, R.string.snapshot_failed,
Leon Scrogginsac993842011-02-02 12:54:07 -05001631 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001632 }
Leon Scrogginsac993842011-02-02 12:54:07 -05001633 break;
1634
Michael Kolb8233fac2010-10-26 16:08:53 -07001635 case R.id.page_info_menu_id:
Huahui Wuae0c0412011-06-28 10:17:05 -07001636 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001637 break;
1638
John Recke1a03a32011-09-14 17:04:16 -07001639 case R.id.snapshot_go_live:
1640 goLive();
1641 return true;
1642
Michael Kolb8233fac2010-10-26 16:08:53 -07001643 case R.id.classic_history_menu_id:
1644 bookmarksOrHistoryPicker(true);
1645 break;
1646
Michael Kolb8233fac2010-10-26 16:08:53 -07001647 case R.id.share_page_menu_id:
1648 Tab currentTab = mTabControl.getCurrentTab();
1649 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001650 return false;
1651 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001652 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001653 break;
1654
1655 case R.id.dump_nav_menu_id:
1656 getCurrentTopWebView().debugDump();
1657 break;
1658
1659 case R.id.dump_counters_menu_id:
1660 getCurrentTopWebView().dumpV8Counters();
1661 break;
1662
1663 case R.id.zoom_in_menu_id:
1664 getCurrentTopWebView().zoomIn();
1665 break;
1666
1667 case R.id.zoom_out_menu_id:
1668 getCurrentTopWebView().zoomOut();
1669 break;
1670
1671 case R.id.view_downloads_menu_id:
1672 viewDownloads();
1673 break;
1674
John Reck42229bc2011-08-19 13:26:43 -07001675 case R.id.ua_desktop_menu_id:
1676 WebView web = getCurrentWebView();
1677 mSettings.toggleDesktopUseragent(web);
1678 web.loadUrl(web.getOriginalUrl());
1679 break;
1680
Michael Kolb8233fac2010-10-26 16:08:53 -07001681 case R.id.window_one_menu_id:
1682 case R.id.window_two_menu_id:
1683 case R.id.window_three_menu_id:
1684 case R.id.window_four_menu_id:
1685 case R.id.window_five_menu_id:
1686 case R.id.window_six_menu_id:
1687 case R.id.window_seven_menu_id:
1688 case R.id.window_eight_menu_id:
1689 {
1690 int menuid = item.getItemId();
1691 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1692 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1693 Tab desiredTab = mTabControl.getTab(id);
1694 if (desiredTab != null &&
1695 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001696 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001697 }
1698 break;
1699 }
1700 }
1701 }
1702 break;
1703
1704 default:
1705 return false;
1706 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001707 return true;
1708 }
1709
John Recke1a03a32011-09-14 17:04:16 -07001710 private void goLive() {
1711 Tab t = getCurrentTab();
1712 t.loadUrl(t.getUrl(), null);
1713 }
1714
Michael Kolb8233fac2010-10-26 16:08:53 -07001715 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001716 // Let the History and Bookmark fragments handle menus they created.
1717 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1718 return false;
1719 }
1720
Michael Kolb8233fac2010-10-26 16:08:53 -07001721 int id = item.getItemId();
1722 boolean result = true;
1723 switch (id) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001724 // -- Browser context menu
1725 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001726 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001727 case R.id.copy_link_context_menu_id:
1728 final WebView webView = getCurrentTopWebView();
1729 if (null == webView) {
1730 result = false;
1731 break;
1732 }
1733 final HashMap<String, WebView> hrefMap =
1734 new HashMap<String, WebView>();
1735 hrefMap.put("webview", webView);
1736 final Message msg = mHandler.obtainMessage(
1737 FOCUS_NODE_HREF, id, 0, hrefMap);
1738 webView.requestFocusNodeHref(msg);
1739 break;
1740
1741 default:
1742 // For other context menus
1743 result = onOptionsItemSelected(item);
1744 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001745 return result;
1746 }
1747
1748 /**
1749 * support programmatically opening the context menu
1750 */
1751 public void openContextMenu(View view) {
1752 mActivity.openContextMenu(view);
1753 }
1754
1755 /**
1756 * programmatically open the options menu
1757 */
1758 public void openOptionsMenu() {
1759 mActivity.openOptionsMenu();
1760 }
1761
1762 public boolean onMenuOpened(int featureId, Menu menu) {
1763 if (mOptionsMenuOpen) {
1764 if (mConfigChanged) {
1765 // We do not need to make any changes to the state of the
1766 // title bar, since the only thing that happened was a
1767 // change in orientation
1768 mConfigChanged = false;
1769 } else {
1770 if (!mExtendedMenuOpen) {
1771 mExtendedMenuOpen = true;
1772 mUi.onExtendedMenuOpened();
1773 } else {
1774 // Switching the menu back to icon view, so show the
1775 // title bar once again.
1776 mExtendedMenuOpen = false;
1777 mUi.onExtendedMenuClosed(mInLoad);
Michael Kolb8233fac2010-10-26 16:08:53 -07001778 }
1779 }
1780 } else {
1781 // The options menu is closed, so open it, and show the title
1782 mOptionsMenuOpen = true;
1783 mConfigChanged = false;
1784 mExtendedMenuOpen = false;
1785 mUi.onOptionsMenuOpened();
1786 }
1787 return true;
1788 }
1789
1790 public void onOptionsMenuClosed(Menu menu) {
1791 mOptionsMenuOpen = false;
1792 mUi.onOptionsMenuClosed(mInLoad);
1793 }
1794
1795 public void onContextMenuClosed(Menu menu) {
1796 mUi.onContextMenuClosed(menu, mInLoad);
1797 }
1798
1799 // Helper method for getting the top window.
1800 @Override
1801 public WebView getCurrentTopWebView() {
1802 return mTabControl.getCurrentTopWebView();
1803 }
1804
1805 @Override
1806 public WebView getCurrentWebView() {
1807 return mTabControl.getCurrentWebView();
1808 }
1809
1810 /*
1811 * This method is called as a result of the user selecting the options
1812 * menu to see the download window. It shows the download window on top of
1813 * the current window.
1814 */
1815 void viewDownloads() {
1816 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1817 mActivity.startActivity(intent);
1818 }
1819
John Reck30b065e2011-07-19 10:58:05 -07001820 int getActionModeHeight() {
1821 TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
1822 new int[] { android.R.attr.actionBarSize });
1823 int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
1824 actionBarSizeTypedArray.recycle();
1825 return size;
1826 }
1827
Michael Kolb8233fac2010-10-26 16:08:53 -07001828 // action mode
1829
1830 void onActionModeStarted(ActionMode mode) {
1831 mUi.onActionModeStarted(mode);
1832 mActionMode = mode;
1833 }
1834
1835 /*
1836 * True if a custom ActionMode (i.e. find or select) is in use.
1837 */
1838 @Override
1839 public boolean isInCustomActionMode() {
1840 return mActionMode != null;
1841 }
1842
1843 /*
1844 * End the current ActionMode.
1845 */
1846 @Override
1847 public void endActionMode() {
1848 if (mActionMode != null) {
1849 mActionMode.finish();
1850 }
1851 }
1852
1853 /*
1854 * Called by find and select when they are finished. Replace title bars
1855 * as necessary.
1856 */
1857 public void onActionModeFinished(ActionMode mode) {
1858 if (!isInCustomActionMode()) return;
1859 mUi.onActionModeFinished(mInLoad);
1860 mActionMode = null;
1861 }
1862
1863 boolean isInLoad() {
1864 return mInLoad;
1865 }
1866
1867 // bookmark handling
1868
1869 /**
1870 * add the current page as a bookmark to the given folder id
1871 * @param folderId use -1 for the default folder
John Reckd3e4d5b2011-07-13 15:48:43 -07001872 * @param editExisting If true, check to see whether the site is already
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001873 * bookmarked, and if it is, edit that bookmark. If false, and
1874 * the site is already bookmarked, do not attempt to edit the
1875 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001876 */
1877 @Override
John Reckd3e4d5b2011-07-13 15:48:43 -07001878 public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
John Recka60fffa2011-09-06 16:30:29 -07001879 WebView w = getCurrentTopWebView();
1880 if (w == null) {
1881 return null;
1882 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001883 Intent i = new Intent(mActivity,
1884 AddBookmarkPage.class);
Michael Kolb8233fac2010-10-26 16:08:53 -07001885 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1886 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1887 String touchIconUrl = w.getTouchIconUrl();
1888 if (touchIconUrl != null) {
1889 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1890 WebSettings settings = w.getSettings();
1891 if (settings != null) {
1892 i.putExtra(AddBookmarkPage.USER_AGENT,
1893 settings.getUserAgentString());
1894 }
1895 }
1896 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1897 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1898 getDesiredThumbnailHeight(mActivity)));
1899 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07001900 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001901 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1902 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001903 // Put the dialog at the upper right of the screen, covering the
1904 // star on the title bar.
1905 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07001906 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07001907 }
1908
1909 // file chooser
1910 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1911 mUploadHandler = new UploadHandler(this);
1912 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1913 }
1914
1915 // thumbnails
1916
1917 /**
1918 * Return the desired width for thumbnail screenshots, which are stored in
1919 * the database, and used on the bookmarks screen.
1920 * @param context Context for finding out the density of the screen.
1921 * @return desired width for thumbnail screenshot.
1922 */
1923 static int getDesiredThumbnailWidth(Context context) {
1924 return context.getResources().getDimensionPixelOffset(
1925 R.dimen.bookmarkThumbnailWidth);
1926 }
1927
1928 /**
1929 * Return the desired height 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 height for thumbnail screenshot.
1933 */
1934 static int getDesiredThumbnailHeight(Context context) {
1935 return context.getResources().getDimensionPixelOffset(
1936 R.dimen.bookmarkThumbnailHeight);
1937 }
1938
John Reck8cc92352011-07-06 17:41:52 -07001939 static Bitmap createScreenshot(WebView view, int width, int height) {
John Reckd7dd9b22011-08-30 09:18:29 -07001940 if (view == null || view.getContentHeight() == 0
1941 || view.getContentWidth() == 0) {
1942 return null;
1943 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001944 // We render to a bitmap 2x the desired size so that we can then
1945 // re-scale it with filtering since canvas.scale doesn't filter
1946 // This helps reduce aliasing at the cost of being slightly blurry
1947 final int filter_scale = 2;
John Reckd7dd9b22011-08-30 09:18:29 -07001948 int scaledWidth = width * filter_scale;
1949 int scaledHeight = height * filter_scale;
1950 if (sThumbnailBitmap == null || sThumbnailBitmap.getWidth() != scaledWidth
1951 || sThumbnailBitmap.getHeight() != scaledHeight) {
1952 if (sThumbnailBitmap != null) {
1953 sThumbnailBitmap.recycle();
1954 sThumbnailBitmap = null;
1955 }
1956 sThumbnailBitmap =
1957 Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.RGB_565);
Michael Kolb8233fac2010-10-26 16:08:53 -07001958 }
John Reckd7dd9b22011-08-30 09:18:29 -07001959 Canvas canvas = new Canvas(sThumbnailBitmap);
1960 int contentWidth = view.getContentWidth();
1961 float overviewScale = scaledWidth / (view.getScale() * contentWidth);
1962 if (view instanceof BrowserWebView) {
1963 int dy = -((BrowserWebView)view).getTitleHeight();
1964 canvas.translate(0, dy * overviewScale);
1965 }
1966
1967 canvas.scale(overviewScale, overviewScale);
1968
1969 if (view instanceof BrowserWebView) {
1970 ((BrowserWebView)view).drawContent(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07001971 } else {
John Reckd7dd9b22011-08-30 09:18:29 -07001972 view.draw(canvas);
Michael Kolb8233fac2010-10-26 16:08:53 -07001973 }
John Reckd7dd9b22011-08-30 09:18:29 -07001974 Bitmap ret = Bitmap.createScaledBitmap(sThumbnailBitmap,
1975 width, height, true);
Dianne Hackborn43cfe8a2011-08-02 16:59:35 -07001976 canvas.setBitmap(null);
John Reck5c6ac2f2011-01-05 10:18:03 -08001977 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001978 }
1979
John Reck34ef2672011-02-10 11:30:55 -08001980 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001981 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07001982 // FIXME: Would like to make sure there is actually something to
1983 // draw, but the API for that (WebViewCore.pictureReady()) is not
1984 // currently accessible here.
1985
John Reck34ef2672011-02-10 11:30:55 -08001986 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08001987 if (view == null) {
1988 // Tab was destroyed
1989 return;
1990 }
John Reck34ef2672011-02-10 11:30:55 -08001991 final String url = tab.getUrl();
1992 final String originalUrl = view.getOriginalUrl();
1993
1994 if (TextUtils.isEmpty(url)) {
1995 return;
1996 }
1997
1998 // Only update thumbnails for web urls (http(s)://), not for
1999 // about:, javascript:, data:, etc...
2000 // Unless it is a bookmarked site, then always update
2001 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2002 return;
2003 }
2004
Michael Kolb8233fac2010-10-26 16:08:53 -07002005 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2006 getDesiredThumbnailHeight(mActivity));
2007 if (bm == null) {
2008 return;
2009 }
2010
2011 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002012 new AsyncTask<Void, Void, Void>() {
2013 @Override
2014 protected Void doInBackground(Void... unused) {
2015 Cursor cursor = null;
2016 try {
2017 // TODO: Clean this up
2018 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2019 if (cursor != null && cursor.moveToFirst()) {
2020 final ByteArrayOutputStream os =
2021 new ByteArrayOutputStream();
2022 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002023
John Reck34ef2672011-02-10 11:30:55 -08002024 ContentValues values = new ContentValues();
2025 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002026
John Reck34ef2672011-02-10 11:30:55 -08002027 do {
John Reck617fd832011-02-16 14:35:59 -08002028 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002029 cr.update(Images.CONTENT_URI, values, null, null);
2030 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002031 }
John Reck34ef2672011-02-10 11:30:55 -08002032 } catch (IllegalStateException e) {
2033 // Ignore
2034 } finally {
2035 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002036 }
John Reck34ef2672011-02-10 11:30:55 -08002037 return null;
2038 }
2039 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002040 }
2041
2042 private class Copy implements OnMenuItemClickListener {
2043 private CharSequence mText;
2044
2045 public boolean onMenuItemClick(MenuItem item) {
2046 copy(mText);
2047 return true;
2048 }
2049
2050 public Copy(CharSequence toCopy) {
2051 mText = toCopy;
2052 }
2053 }
2054
Leon Scroggins63c02662010-11-18 15:16:27 -05002055 private static class Download implements OnMenuItemClickListener {
2056 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002057 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002058 private boolean mPrivateBrowsing;
George Mount387d45d2011-10-07 15:57:53 -07002059 private static final String FALLBACK_EXTENSION = "dat";
2060 private static final String IMAGE_BASE_FORMAT = "yyyy-MM-dd-HH-mm-ss-";
Michael Kolb8233fac2010-10-26 16:08:53 -07002061
2062 public boolean onMenuItemClick(MenuItem item) {
George Mount387d45d2011-10-07 15:57:53 -07002063 if (DataUri.isDataUri(mText)) {
2064 saveDataUri();
2065 } else {
2066 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
2067 null, null, mPrivateBrowsing);
2068 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002069 return true;
2070 }
2071
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002072 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002073 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002074 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002075 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002076 }
George Mount387d45d2011-10-07 15:57:53 -07002077
2078 /**
2079 * Treats mText as a data URI and writes its contents to a file
2080 * based on the current time.
2081 */
2082 private void saveDataUri() {
2083 FileOutputStream outputStream = null;
2084 try {
2085 DataUri uri = new DataUri(mText);
2086 File target = getTarget(uri);
2087 outputStream = new FileOutputStream(target);
2088 outputStream.write(uri.getData());
2089 final DownloadManager manager =
2090 (DownloadManager) mActivity.getSystemService(Context.DOWNLOAD_SERVICE);
2091 manager.addCompletedDownload(target.getName(),
2092 mActivity.getTitle().toString(), false,
2093 uri.getMimeType(), target.getAbsolutePath(),
2094 (long)uri.getData().length, false);
2095 } catch (IOException e) {
2096 Log.e(LOGTAG, "Could not save data URL");
2097 } finally {
2098 if (outputStream != null) {
2099 try {
2100 outputStream.close();
2101 } catch (IOException e) {
2102 // ignore close errors
2103 }
2104 }
2105 }
2106 }
2107
2108 /**
2109 * Creates a File based on the current time stamp and uses
2110 * the mime type of the DataUri to get the extension.
2111 */
2112 private File getTarget(DataUri uri) throws IOException {
2113 File dir = mActivity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
2114 DateFormat format = new SimpleDateFormat(IMAGE_BASE_FORMAT);
2115 String nameBase = format.format(new Date());
2116 String mimeType = uri.getMimeType();
2117 MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
2118 String extension = mimeTypeMap.getExtensionFromMimeType(mimeType);
2119 if (extension == null) {
2120 Log.w(LOGTAG, "Unknown mime type in data URI" + mimeType);
2121 extension = FALLBACK_EXTENSION;
2122 }
2123 extension = "." + extension; // createTempFile needs the '.'
2124 File targetFile = File.createTempFile(nameBase, extension, dir);
2125 return targetFile;
2126 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002127 }
2128
Cary Clark8974d282010-11-22 10:46:05 -05002129 private static class SelectText implements OnMenuItemClickListener {
2130 private WebView mWebView;
2131
2132 public boolean onMenuItemClick(MenuItem item) {
2133 if (mWebView != null) {
2134 return mWebView.selectText();
2135 }
2136 return false;
2137 }
2138
2139 public SelectText(WebView webView) {
2140 mWebView = webView;
2141 }
2142
2143 }
2144
Michael Kolb8233fac2010-10-26 16:08:53 -07002145 /********************** TODO: UI stuff *****************************/
2146
2147 // these methods have been copied, they still need to be cleaned up
2148
2149 /****************** tabs ***************************************************/
2150
2151 // basic tab interactions:
2152
2153 // it is assumed that tabcontrol already knows about the tab
2154 protected void addTab(Tab tab) {
2155 mUi.addTab(tab);
2156 }
2157
2158 protected void removeTab(Tab tab) {
2159 mUi.removeTab(tab);
2160 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002161 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002162 }
2163
Michael Kolbf2055602011-04-09 17:20:03 -07002164 @Override
2165 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002166 // monkey protection against delayed start
2167 if (tab != null) {
2168 mTabControl.setCurrentTab(tab);
2169 // the tab is guaranteed to have a webview after setCurrentTab
2170 mUi.setActiveTab(tab);
2171 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002172 }
2173
John Reck8bcafc12011-08-29 16:43:02 -07002174 protected void closeEmptyTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002175 Tab current = mTabControl.getCurrentTab();
2176 if (current != null
2177 && current.getWebView().copyBackForwardList().getSize() == 0) {
John Reck8bcafc12011-08-29 16:43:02 -07002178 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002179 }
2180 }
2181
John Reck26b18322011-06-21 13:08:58 -07002182 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002183 // Dismiss the subwindow if applicable.
2184 dismissSubWindow(appTab);
2185 // Since we might kill the WebView, remove it from the
2186 // content view first.
2187 mUi.detachTab(appTab);
2188 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002189 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002190 // TODO: analyze why the remove and add are necessary
2191 mUi.attachTab(appTab);
2192 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002193 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002194 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002195 } else {
2196 // If the tab was the current tab, we have to attach
2197 // it to the view system again.
2198 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002199 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002200 }
2201 }
2202
2203 // Remove the sub window if it exists. Also called by TabControl when the
2204 // user clicks the 'X' to dismiss a sub window.
2205 public void dismissSubWindow(Tab tab) {
2206 removeSubWindow(tab);
2207 // dismiss the subwindow. This will destroy the WebView.
2208 tab.dismissSubWindow();
2209 getCurrentTopWebView().requestFocus();
2210 }
2211
2212 @Override
2213 public void removeSubWindow(Tab t) {
2214 if (t.getSubWebView() != null) {
2215 mUi.removeSubWindow(t.getSubViewContainer());
2216 }
2217 }
2218
2219 @Override
2220 public void attachSubWindow(Tab tab) {
2221 if (tab.getSubWebView() != null) {
2222 mUi.attachSubWindow(tab.getSubViewContainer());
2223 getCurrentTopWebView().requestFocus();
2224 }
2225 }
2226
Mathew Inwood29721c22011-06-29 17:55:24 +01002227 private Tab showPreloadedTab(final UrlData urlData) {
2228 if (!urlData.isPreloaded()) {
2229 return null;
2230 }
2231 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2232 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2233 if (sbQuery != null) {
Mathew Inwood9ad1eac2011-09-15 11:29:50 +01002234 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002235 // Could not submit query. Fallback to regular tab creation
2236 tabControl.destroy();
2237 return null;
2238 }
2239 }
Michael Kolbff6a7482011-07-26 16:37:15 -07002240 // check tab count and make room for new tab
2241 if (!mTabControl.canCreateNewTab()) {
2242 Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
2243 if (leastUsed != null) {
2244 closeTab(leastUsed);
2245 }
2246 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002247 Tab t = tabControl.getTab();
Mathew Inwoode09305e2011-09-02 12:03:26 +01002248 t.refreshIdAfterPreload();
Mathew Inwood29721c22011-06-29 17:55:24 +01002249 mTabControl.addPreloadedTab(t);
2250 addTab(t);
2251 setActiveTab(t);
2252 return t;
2253 }
2254
Michael Kolb7bcafde2011-05-09 13:55:59 -07002255 // open a non inconito tab with the given url data
2256 // and set as active tab
2257 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002258 Tab tab = showPreloadedTab(urlData);
2259 if (tab == null) {
2260 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002261 if ((tab != null) && !urlData.isEmpty()) {
2262 loadUrlDataIn(tab, urlData);
2263 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002264 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002265 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002266 }
2267
Michael Kolb843510f2010-12-09 10:51:49 -08002268 @Override
2269 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002270 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002271 }
2272
Michael Kolb8233fac2010-10-26 16:08:53 -07002273 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002274 public Tab openIncognitoTab() {
2275 return openTab(INCOGNITO_URI, true, true, false);
2276 }
2277
2278 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002279 public Tab openTab(String url, boolean incognito, boolean setActive,
2280 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002281 return openTab(url, incognito, setActive, useCurrent, null);
2282 }
2283
2284 @Override
2285 public Tab openTab(String url, Tab parent, boolean setActive,
2286 boolean useCurrent) {
2287 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2288 setActive, useCurrent, parent);
2289 }
2290
2291 public Tab openTab(String url, boolean incognito, boolean setActive,
2292 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002293 Tab tab = createNewTab(incognito, setActive, useCurrent);
2294 if (tab != null) {
John Reck5949c662011-05-27 09:52:29 -07002295 if (parent != null && parent != tab) {
2296 parent.addChildTab(tab);
2297 }
Michael Kolb519d2282011-05-09 17:03:19 -07002298 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002299 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002300 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002301 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002302 return tab;
2303 }
2304
2305 // this method will attempt to create a new tab
2306 // incognito: private browsing tab
2307 // setActive: ste tab as current tab
2308 // useCurrent: if no new tab can be created, return current tab
2309 private Tab createNewTab(boolean incognito, boolean setActive,
2310 boolean useCurrent) {
2311 Tab tab = null;
2312 if (mTabControl.canCreateNewTab()) {
2313 tab = mTabControl.createNewTab(incognito);
2314 addTab(tab);
2315 if (setActive) {
2316 setActiveTab(tab);
2317 }
2318 } else {
2319 if (useCurrent) {
2320 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002321 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002322 } else {
2323 mUi.showMaxTabsWarning();
2324 }
2325 }
2326 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002327 }
2328
John Reck2bc80422011-06-30 15:11:49 -07002329 @Override
2330 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2331 SnapshotTab tab = null;
2332 if (mTabControl.canCreateNewTab()) {
2333 tab = mTabControl.createSnapshotTab(snapshotId);
2334 addTab(tab);
2335 if (setActive) {
2336 setActiveTab(tab);
2337 }
2338 } else {
2339 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07002340 }
2341 return tab;
2342 }
2343
Michael Kolb8233fac2010-10-26 16:08:53 -07002344 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002345 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002346 * @return boolean True if we successfully switched to a different tab. If
2347 * the indexth tab is null, or if that tab is the same as
2348 * the current one, return false.
2349 */
2350 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002351 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002352 Tab currentTab = mTabControl.getCurrentTab();
2353 if (tab == null || tab == currentTab) {
2354 return false;
2355 }
2356 setActiveTab(tab);
2357 return true;
2358 }
2359
2360 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002361 public void closeCurrentTab() {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002362 closeCurrentTab(false);
2363 }
2364
2365 protected void closeCurrentTab(boolean andQuit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002366 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07002367 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07002368 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08002369 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002370 return;
2371 }
Michael Kolbc831b632011-05-11 09:30:34 -07002372 final Tab current = mTabControl.getCurrentTab();
2373 final int pos = mTabControl.getCurrentPosition();
2374 Tab newTab = current.getParent();
2375 if (newTab == null) {
2376 newTab = mTabControl.getTab(pos + 1);
2377 if (newTab == null) {
2378 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002379 }
2380 }
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002381 if (andQuit) {
2382 mTabControl.setCurrentTab(newTab);
2383 closeTab(current);
2384 } else if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002385 // Close window
2386 closeTab(current);
2387 }
2388 }
2389
2390 /**
2391 * Close the tab, remove its associated title bar, and adjust mTabControl's
2392 * current tab to a valid value.
2393 */
2394 @Override
2395 public void closeTab(Tab tab) {
Michael Kolb2d59c322011-01-25 13:18:55 -08002396 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002397 }
2398
Michael Kolb8233fac2010-10-26 16:08:53 -07002399 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07002400 protected void loadUrlFromContext(String url) {
2401 Tab tab = getCurrentTab();
2402 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002403 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07002404 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002405 url = UrlUtils.smartUrlFilter(url);
2406 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07002407 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07002408 }
2409 }
2410 }
2411
2412 /**
2413 * Load the URL into the given WebView and update the title bar
2414 * to reflect the new load. Call this instead of WebView.loadUrl
2415 * directly.
2416 * @param view The WebView used to load url.
2417 * @param url The URL to load.
2418 */
John Reck71e51422011-07-01 16:49:28 -07002419 @Override
2420 public void loadUrl(Tab tab, String url) {
John Reck26b18322011-06-21 13:08:58 -07002421 loadUrl(tab, url, null);
2422 }
2423
2424 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
2425 if (tab != null) {
2426 dismissSubWindow(tab);
2427 tab.loadUrl(url, headers);
Michael Kolba53c9892011-10-05 13:31:40 -07002428 mUi.onProgressChanged(tab);
John Reck26b18322011-06-21 13:08:58 -07002429 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002430 }
2431
2432 /**
2433 * Load UrlData into a Tab and update the title bar to reflect the new
2434 * load. Call this instead of UrlData.loadIn directly.
2435 * @param t The Tab used to load.
2436 * @param data The UrlData being loaded.
2437 */
2438 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07002439 if (data != null) {
2440 if (data.mVoiceIntent != null) {
2441 t.activateVoiceSearchMode(data.mVoiceIntent);
Michael Kolb14612442011-06-24 13:06:29 -07002442 } else if (data.isPreloaded()) {
2443 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07002444 } else {
2445 loadUrl(t, data.mUrl, data.mHeaders);
2446 }
2447 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002448 }
2449
John Reck30c714c2010-12-16 17:30:34 -08002450 @Override
2451 public void onUserCanceledSsl(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08002452 // TODO: Figure out the "right" behavior
John Reckef654f12011-07-12 16:42:08 -07002453 if (tab.canGoBack()) {
2454 tab.goBack();
John Reck30c714c2010-12-16 17:30:34 -08002455 } else {
John Reckef654f12011-07-12 16:42:08 -07002456 tab.loadUrl(mSettings.getHomePage(), null);
John Reck30c714c2010-12-16 17:30:34 -08002457 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002458 }
2459
2460 void goBackOnePageOrQuit() {
2461 Tab current = mTabControl.getCurrentTab();
2462 if (current == null) {
2463 /*
2464 * Instead of finishing the activity, simply push this to the back
2465 * of the stack and let ActivityManager to choose the foreground
2466 * activity. As BrowserActivity is singleTask, it will be always the
2467 * root of the task. So we can use either true or false for
2468 * moveTaskToBack().
2469 */
2470 mActivity.moveTaskToBack(true);
2471 return;
2472 }
John Reckef654f12011-07-12 16:42:08 -07002473 if (current.canGoBack()) {
2474 current.goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07002475 } else {
2476 // Check to see if we are closing a window that was created by
2477 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002478 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002479 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002480 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002481 // Now we close the other tab
2482 closeTab(current);
2483 } else {
Michael Kolbe28b3472011-08-04 16:54:31 -07002484 if ((current.getAppId() != null) || current.closeOnBack()) {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07002485 closeCurrentTab(true);
Michael Kolbe28b3472011-08-04 16:54:31 -07002486 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002487 /*
2488 * Instead of finishing the activity, simply push this to the back
2489 * of the stack and let ActivityManager to choose the foreground
2490 * activity. As BrowserActivity is singleTask, it will be always the
2491 * root of the task. So we can use either true or false for
2492 * moveTaskToBack().
2493 */
2494 mActivity.moveTaskToBack(true);
2495 }
2496 }
2497 }
2498
2499 /**
2500 * Feed the previously stored results strings to the BrowserProvider so that
2501 * the SearchDialog will show them instead of the standard searches.
2502 * @param result String to show on the editable line of the SearchDialog.
2503 */
2504 @Override
2505 public void showVoiceSearchResults(String result) {
2506 ContentProviderClient client = mActivity.getContentResolver()
2507 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2508 ContentProvider prov = client.getLocalContentProvider();
2509 BrowserProvider bp = (BrowserProvider) prov;
2510 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2511 client.release();
2512
2513 Bundle bundle = createGoogleSearchSourceBundle(
2514 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2515 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2516 startSearch(result, false, bundle, false);
2517 }
2518
2519 private void startSearch(String initialQuery, boolean selectInitialQuery,
2520 Bundle appSearchData, boolean globalSearch) {
2521 if (appSearchData == null) {
2522 appSearchData = createGoogleSearchSourceBundle(
2523 GOOGLE_SEARCH_SOURCE_TYPE);
2524 }
2525
2526 SearchEngine searchEngine = mSettings.getSearchEngine();
2527 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2528 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2529 }
2530 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2531 globalSearch);
2532 }
2533
2534 private Bundle createGoogleSearchSourceBundle(String source) {
2535 Bundle bundle = new Bundle();
2536 bundle.putString(Search.SOURCE, source);
2537 return bundle;
2538 }
2539
2540 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002541 * helper method for key handler
2542 * returns the current tab if it can't advance
2543 */
Michael Kolbc831b632011-05-11 09:30:34 -07002544 private Tab getNextTab() {
2545 return mTabControl.getTab(Math.min(mTabControl.getTabCount() - 1,
2546 mTabControl.getCurrentPosition() + 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002547 }
2548
2549 /**
2550 * helper method for key handler
2551 * returns the current tab if it can't advance
2552 */
Michael Kolbc831b632011-05-11 09:30:34 -07002553 private Tab getPrevTab() {
2554 return mTabControl.getTab(Math.max(0,
2555 mTabControl.getCurrentPosition() - 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002556 }
2557
2558 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002559 * handle key events in browser
2560 *
2561 * @param keyCode
2562 * @param event
2563 * @return true if handled, false to pass to super
2564 */
2565 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002566 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002567 // Even if MENU is already held down, we need to call to super to open
2568 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002569 if (!noModifiers
2570 && ((KeyEvent.KEYCODE_MENU == keyCode)
2571 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2572 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002573 mMenuIsDown = true;
2574 return false;
2575 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002576
Cary Clark8ff8c662010-12-29 15:03:05 -05002577 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07002578 Tab tab = getCurrentTab();
2579 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05002580
Cary Clark160bbb92011-01-10 11:17:07 -05002581 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2582 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002583
Michael Kolb8233fac2010-10-26 16:08:53 -07002584 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002585 case KeyEvent.KEYCODE_TAB:
2586 if (event.isCtrlPressed()) {
2587 if (event.isShiftPressed()) {
2588 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002589 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002590 } else {
2591 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002592 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002593 }
2594 return true;
2595 }
2596 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002597 case KeyEvent.KEYCODE_SPACE:
2598 // WebView/WebTextView handle the keys in the KeyDown. As
2599 // the Activity's shortcut keys are only handled when WebView
2600 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002601 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002602 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002603 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002604 pageDown();
2605 }
2606 return true;
2607 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002608 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002609 event.startTracking();
2610 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07002611 case KeyEvent.KEYCODE_FORWARD:
2612 if (!noModifiers) break;
2613 tab.goForward();
2614 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002615 case KeyEvent.KEYCODE_DPAD_LEFT:
2616 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002617 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05002618 return true;
2619 }
2620 break;
2621 case KeyEvent.KEYCODE_DPAD_RIGHT:
2622 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07002623 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05002624 return true;
2625 }
2626 break;
2627 case KeyEvent.KEYCODE_A:
2628 if (ctrl) {
2629 webView.selectAll();
2630 return true;
2631 }
2632 break;
Michael Kolba4183062011-01-16 10:43:21 -08002633// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002634 case KeyEvent.KEYCODE_C:
2635 if (ctrl) {
2636 webView.copySelection();
2637 return true;
2638 }
2639 break;
Michael Kolba4183062011-01-16 10:43:21 -08002640// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002641// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002642// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002643// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002644// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002645// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002646// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002647// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002648// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002649// case KeyEvent.KEYCODE_M: // unused
2650// case KeyEvent.KEYCODE_N: // in Chrome: new window
2651// case KeyEvent.KEYCODE_O: // in Chrome: open file
2652// case KeyEvent.KEYCODE_P: // in Chrome: print page
2653// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002654// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002655// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2656 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002657 // we can't use the ctrl/shift flags, they check for
2658 // exclusive use of a modifier
2659 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002660 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002661 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002662 } else {
2663 openTabToHomePage();
2664 }
2665 return true;
2666 }
2667 break;
2668// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2669// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb5ae15bd2011-08-16 17:09:27 -07002670// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002671// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2672// case KeyEvent.KEYCODE_Y: // unused
2673// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002674 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002675 // it is a regular key and webview is not null
2676 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002677 }
2678
John Recke6bf4ab2011-02-24 15:48:05 -08002679 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2680 switch(keyCode) {
2681 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07002682 if (mUi.isWebShowing()) {
John Recke6bf4ab2011-02-24 15:48:05 -08002683 bookmarksOrHistoryPicker(true);
2684 return true;
2685 }
2686 break;
2687 }
2688 return false;
2689 }
2690
Michael Kolb8233fac2010-10-26 16:08:53 -07002691 boolean onKeyUp(int keyCode, KeyEvent event) {
Michael Kolb2814a362011-05-19 15:49:41 -07002692 if (KeyEvent.KEYCODE_MENU == keyCode) {
2693 mMenuIsDown = false;
2694 if (event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002695 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002696 }
2697 }
Cary Clark160bbb92011-01-10 11:17:07 -05002698 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002699 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002700 case KeyEvent.KEYCODE_BACK:
2701 if (event.isTracking() && !event.isCanceled()) {
2702 onBackKey();
2703 return true;
2704 }
2705 break;
2706 }
2707 return false;
2708 }
2709
2710 public boolean isMenuDown() {
2711 return mMenuIsDown;
2712 }
2713
Ben Murdoch8029a772010-11-16 11:58:21 +00002714 public void setupAutoFill(Message message) {
2715 // Open the settings activity at the AutoFill profile fragment so that
2716 // the user can create a new profile. When they return, we will dispatch
2717 // the message so that we can autofill the form using their new profile.
2718 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2719 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2720 AutoFillSettingsFragment.class.getName());
2721 mAutoFillSetupMessage = message;
2722 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2723 }
John Reckb3417f02011-01-14 11:01:05 -08002724
2725 @Override
Narayan Kamath5119edd2011-02-23 15:49:17 +00002726 public void registerDropdownChangeListener(DropdownChangeListener d) {
2727 mUi.registerDropdownChangeListener(d);
2728 }
Michael Kolbfbc579a2011-07-07 15:59:33 -07002729
2730 public boolean onSearchRequested() {
2731 mUi.editUrl(false);
2732 return true;
2733 }
2734
John Reck1cf4b792011-07-26 10:22:22 -07002735 @Override
2736 public boolean shouldCaptureThumbnails() {
2737 return mUi.shouldCaptureThumbnails();
2738 }
2739
Michael Kolbc3af0672011-08-09 10:24:41 -07002740 @Override
2741 public void setBlockEvents(boolean block) {
2742 mBlockEvents = block;
2743 }
2744
2745 public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002746 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002747 }
2748
2749 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07002750 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002751 }
2752
2753 public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002754 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002755 }
2756
2757 public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002758 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002759 }
2760
2761 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07002762 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07002763 }
2764
Michael Kolb8233fac2010-10-26 16:08:53 -07002765}