blob: 9046745f01d71fae1e864b63084f83213f4ab8ea [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;
Leon Scroggins1961ed22010-12-07 15:22:21 -050033import android.database.ContentObserver;
Michael Kolb8233fac2010-10-26 16:08:53 -070034import android.database.Cursor;
35import android.database.sqlite.SQLiteDatabase;
Michael Kolb8233fac2010-10-26 16:08:53 -070036import android.graphics.Bitmap;
37import android.graphics.Canvas;
38import android.graphics.Picture;
39import android.net.Uri;
40import android.net.http.SslError;
41import android.os.AsyncTask;
42import android.os.Bundle;
Leon Scrogginsac993842011-02-02 12:54:07 -050043import 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;
67import android.view.View;
68import android.webkit.CookieManager;
69import android.webkit.CookieSyncManager;
70import android.webkit.HttpAuthHandler;
71import android.webkit.SslErrorHandler;
72import android.webkit.ValueCallback;
73import android.webkit.WebChromeClient;
74import android.webkit.WebIconDatabase;
75import android.webkit.WebSettings;
76import android.webkit.WebView;
Leon Scrogginsac993842011-02-02 12:54:07 -050077import android.widget.Toast;
Michael Kolb8233fac2010-10-26 16:08:53 -070078
Michael Kolb4bd767d2011-05-27 11:33:55 -070079import com.android.browser.IntentHandler.UrlData;
80import com.android.browser.UI.DropdownChangeListener;
81import com.android.browser.provider.BrowserProvider;
John Reckd8c74522011-06-14 08:45:00 -070082import com.android.browser.provider.BrowserProvider2.Snapshots;
Michael Kolb4bd767d2011-05-27 11:33:55 -070083import com.android.browser.search.SearchEngine;
84import com.android.common.Search;
85
Michael Kolb8233fac2010-10-26 16:08:53 -070086import java.io.ByteArrayOutputStream;
87import java.io.File;
88import java.net.URLEncoder;
89import java.util.Calendar;
90import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -080091import java.util.List;
John Reck26b18322011-06-21 13:08:58 -070092import java.util.Map;
Michael Kolb8233fac2010-10-26 16:08:53 -070093
94/**
95 * Controller for browser
96 */
97public class Controller
98 implements WebViewController, UiController {
99
100 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800101 private static final String SEND_APP_ID_EXTRA =
102 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
Michael Kolba4261fd2011-05-05 11:27:37 -0700103 private static final String INCOGNITO_URI = "browser:incognito";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800104
Michael Kolb8233fac2010-10-26 16:08:53 -0700105
106 // public message ids
107 public final static int LOAD_URL = 1001;
108 public final static int STOP_LOAD = 1002;
109
110 // Message Ids
111 private static final int FOCUS_NODE_HREF = 102;
112 private static final int RELEASE_WAKELOCK = 107;
113
114 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
115
116 private static final int OPEN_BOOKMARKS = 201;
117
118 private static final int EMPTY_MENU = -1;
119
Michael Kolb8233fac2010-10-26 16:08:53 -0700120 // activity requestCode
121 final static int PREFERENCES_PAGE = 3;
122 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000123 final static int AUTOFILL_SETUP = 5;
124
Michael Kolb8233fac2010-10-26 16:08:53 -0700125 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
126
127 // As the ids are dynamically created, we can't guarantee that they will
128 // be in sequence, so this static array maps ids to a window number.
129 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
130 { R.id.window_one_menu_id, R.id.window_two_menu_id,
131 R.id.window_three_menu_id, R.id.window_four_menu_id,
132 R.id.window_five_menu_id, R.id.window_six_menu_id,
133 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
134
135 // "source" parameter for Google search through search key
136 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
137 // "source" parameter for Google search through simplily type
138 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
139
Guang Zhu9e78f512011-05-04 11:45:11 -0700140 // "no-crash-recovery" parameter in intetnt to suppress crash recovery
141 final static String NO_CRASH_RECOVERY = "no-crash-recovery";
142
Michael Kolb8233fac2010-10-26 16:08:53 -0700143 private Activity mActivity;
144 private UI mUi;
145 private TabControl mTabControl;
146 private BrowserSettings mSettings;
147 private WebViewFactory mFactory;
John Reckb3417f02011-01-14 11:01:05 -0800148 private OptionsMenuHandler mOptionsMenuHandler = null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700149
150 private WakeLock mWakeLock;
151
152 private UrlHandler mUrlHandler;
153 private UploadHandler mUploadHandler;
154 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700155 private PageDialogsHandler mPageDialogsHandler;
156 private NetworkStateHandler mNetworkHandler;
Martijn Coenenb2f93552011-06-14 10:48:35 +0200157 private NfcHandler mNfcHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700158
Ben Murdoch8029a772010-11-16 11:58:21 +0000159 private Message mAutoFillSetupMessage;
160
Michael Kolb8233fac2010-10-26 16:08:53 -0700161 private boolean mShouldShowErrorConsole;
162
163 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
164
165 // FIXME, temp address onPrepareMenu performance problem.
166 // When we move everything out of view, we should rewrite this.
167 private int mCurrentMenuState = 0;
168 private int mMenuState = R.id.MAIN_MENU;
169 private int mOldMenuState = EMPTY_MENU;
170 private Menu mCachedMenu;
171
Michael Kolb8233fac2010-10-26 16:08:53 -0700172 private boolean mMenuIsDown;
173
174 // For select and find, we keep track of the ActionMode so that
175 // finish() can be called as desired.
176 private ActionMode mActionMode;
177
178 /**
179 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
180 * of whether the configuration has changed. The first onMenuOpened call
181 * after a configuration change is simply a reopening of the same menu
182 * (i.e. mIconView did not change).
183 */
184 private boolean mConfigChanged;
185
186 /**
187 * Keeps track of whether the options menu is open. This is important in
188 * determining whether to show or hide the title bar overlay
189 */
190 private boolean mOptionsMenuOpen;
191
192 /**
193 * Whether or not the options menu is in its bigger, popup menu form. When
194 * true, we want the title bar overlay to be gone. When false, we do not.
195 * Only meaningful if mOptionsMenuOpen is true.
196 */
197 private boolean mExtendedMenuOpen;
198
199 private boolean mInLoad;
200
201 private boolean mActivityPaused = true;
202 private boolean mLoadStopped;
203
204 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500205 // Checks to see when the bookmarks database has changed, and updates the
206 // Tabs' notion of whether they represent bookmarked sites.
207 private ContentObserver mBookmarksObserver;
John Reck0ebd3ac2010-12-09 11:14:04 -0800208 private DataController mDataController;
John Reck847b5322011-04-14 17:02:18 -0700209 private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700210
211 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
212 @Override
213 public Void doInBackground(File... files) {
214 if (files != null) {
215 for (File f : files) {
216 if (!f.delete()) {
217 Log.e(LOGTAG, f.getPath() + " was not deleted");
218 }
219 }
220 }
221 return null;
222 }
223 }
224
225 public Controller(Activity browser) {
226 mActivity = browser;
227 mSettings = BrowserSettings.getInstance();
John Reck0ebd3ac2010-12-09 11:14:04 -0800228 mDataController = DataController.getInstance(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700229 mTabControl = new TabControl(this);
230 mSettings.setController(this);
John Reck378a4102011-06-09 16:23:01 -0700231 mCrashRecoveryHandler = CrashRecoveryHandler.initialize(this);
Michael Kolb14612442011-06-24 13:06:29 -0700232 mFactory = new BrowserWebViewFactory(browser);
Michael Kolb8233fac2010-10-26 16:08:53 -0700233
234 mUrlHandler = new UrlHandler(this);
235 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700236 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
Martijn Coenenb2f93552011-06-14 10:48:35 +0200237 mNfcHandler = new NfcHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700238
239 PowerManager pm = (PowerManager) mActivity
240 .getSystemService(Context.POWER_SERVICE);
241 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
242
243 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500244 mBookmarksObserver = new ContentObserver(mHandler) {
245 @Override
246 public void onChange(boolean selfChange) {
247 int size = mTabControl.getTabCount();
248 for (int i = 0; i < size; i++) {
249 mTabControl.getTab(i).updateBookmarkedStatus();
250 }
251 }
252
253 };
254 browser.getContentResolver().registerContentObserver(
255 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700256
257 mNetworkHandler = new NetworkStateHandler(mActivity, this);
258 // Start watching the default geolocation permissions
259 mSystemAllowGeolocationOrigins =
260 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
261 mSystemAllowGeolocationOrigins.start();
262
263 retainIconsOnStartup();
264 }
265
Patrick Scott7d50a932011-02-04 09:27:26 -0500266 void start(final Bundle icicle, final Intent intent) {
Guang Zhu9e78f512011-05-04 11:45:11 -0700267 boolean noCrashRecovery = intent.getBooleanExtra(NO_CRASH_RECOVERY, false);
268 if (icicle != null || noCrashRecovery) {
John Reck847b5322011-04-14 17:02:18 -0700269 doStart(icicle, intent);
270 } else {
271 mCrashRecoveryHandler.startRecovery(intent);
272 }
273 }
274
275 void doStart(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700276 // Unless the last browser usage was within 24 hours, destroy any
277 // remaining incognito tabs.
278
279 Calendar lastActiveDate = icicle != null ?
280 (Calendar) icicle.getSerializable("lastActiveDate") : null;
281 Calendar today = Calendar.getInstance();
282 Calendar yesterday = Calendar.getInstance();
283 yesterday.add(Calendar.DATE, -1);
284
Patrick Scott7d50a932011-02-04 09:27:26 -0500285 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700286 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800287 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700288
Patrick Scott7d50a932011-02-04 09:27:26 -0500289 // Find out if we will restore any state and remember the tab.
Michael Kolbc831b632011-05-11 09:30:34 -0700290 final long currentTabId =
Patrick Scott7d50a932011-02-04 09:27:26 -0500291 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000292
Michael Kolbc831b632011-05-11 09:30:34 -0700293 if (currentTabId == -1) {
Patrick Scott7d50a932011-02-04 09:27:26 -0500294 // Not able to restore so we go ahead and clear session cookies. We
295 // must do this before trying to login the user as we don't want to
296 // clear any session cookies set during login.
297 CookieManager.getInstance().removeSessionCookie();
298 }
299
Patrick Scottd43e75a2011-03-14 14:47:23 -0400300 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500301 new Runnable() {
302 @Override public void run() {
Michael Kolbc831b632011-05-11 09:30:34 -0700303 onPreloginFinished(icicle, intent, currentTabId, restoreIncognitoTabs);
Patrick Scott7d50a932011-02-04 09:27:26 -0500304 }
305 });
306 }
307
Michael Kolbc831b632011-05-11 09:30:34 -0700308 private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId,
Patrick Scott7d50a932011-02-04 09:27:26 -0500309 boolean restoreIncognitoTabs) {
Michael Kolbc831b632011-05-11 09:30:34 -0700310 if (currentTabId == -1) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700311 final Bundle extra = intent.getExtras();
312 // Create an initial tab.
313 // If the intent is ACTION_VIEW and data is not null, the Browser is
314 // invoked to view the content by another application. In this case,
315 // the tab will be close when exit.
Michael Kolb14612442011-06-24 13:06:29 -0700316 UrlData urlData = IntentHandler.getUrlDataFromIntent(intent);
Michael Kolb7bcafde2011-05-09 13:55:59 -0700317 Tab t = null;
318 if (urlData.isEmpty()) {
319 t = openTabToHomePage();
320 } else {
321 t = openTab(urlData);
322 }
323 if (t != null) {
324 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
325 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700326 WebView webView = t.getWebView();
327 if (extra != null) {
328 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
329 if (scale > 0 && scale <= 1000) {
330 webView.setInitialScale(scale);
331 }
332 }
John Reckd8c74522011-06-14 08:45:00 -0700333 mTabControl.loadSnapshotTabs();
334 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700335 } else {
Michael Kolbc831b632011-05-11 09:30:34 -0700336 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
Patrick Scott7d50a932011-02-04 09:27:26 -0500337 mUi.needsRestoreAllTabs());
Michael Kolb1bf23132010-11-19 12:55:12 -0800338 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700339 // TabControl.restoreState() will create a new tab even if
340 // restoring the state fails.
341 setActiveTab(mTabControl.getCurrentTab());
John Reckdb22ec42011-06-29 11:31:24 -0700342 // Handle the intent
343 mIntentHandler.onNewIntent(intent);
Michael Kolb8233fac2010-10-26 16:08:53 -0700344 }
345 // clear up the thumbnail directory, which is no longer used;
346 // ideally this should only be run once after an upgrade from
347 // a previous version of the browser
348 new ClearThumbnails().execute(mTabControl.getThumbnailDir()
349 .listFiles());
350 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700351 String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb8233fac2010-10-26 16:08:53 -0700352 if (jsFlags.trim().length() != 0) {
353 getCurrentWebView().setJsFlags(jsFlags);
354 }
John Reck439c9a52010-12-14 10:04:39 -0800355 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
356 bookmarksOrHistoryPicker(false);
357 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700358 }
359
Michael Kolb1514bb72010-11-22 09:11:48 -0800360 @Override
361 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700362 return mFactory;
363 }
364
365 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800366 public void onSetWebView(Tab tab, WebView view) {
367 mUi.onSetWebView(tab, view);
368 }
369
370 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800371 public void createSubWindow(Tab tab) {
372 endActionMode();
373 WebView mainView = tab.getWebView();
374 WebView subView = mFactory.createWebView((mainView == null)
375 ? false
376 : mainView.isPrivateBrowsingEnabled());
377 mUi.createSubWindow(tab, subView);
378 }
379
380 @Override
Michael Kolb14612442011-06-24 13:06:29 -0700381 public Context getContext() {
382 return mActivity;
383 }
384
385 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700386 public Activity getActivity() {
387 return mActivity;
388 }
389
390 void setUi(UI ui) {
391 mUi = ui;
392 }
393
394 BrowserSettings getSettings() {
395 return mSettings;
396 }
397
398 IntentHandler getIntentHandler() {
399 return mIntentHandler;
400 }
401
402 @Override
403 public UI getUi() {
404 return mUi;
405 }
406
407 int getMaxTabs() {
408 return mActivity.getResources().getInteger(R.integer.max_tabs);
409 }
410
411 @Override
412 public TabControl getTabControl() {
413 return mTabControl;
414 }
415
Michael Kolb1bf23132010-11-19 12:55:12 -0800416 @Override
417 public List<Tab> getTabs() {
418 return mTabControl.getTabs();
419 }
420
Michael Kolb8233fac2010-10-26 16:08:53 -0700421 // Open the icon database and retain all the icons for visited sites.
Ben Murdoch9446b932010-11-25 16:20:14 +0000422 // This is done on a background thread so as not to stall startup.
Michael Kolb8233fac2010-10-26 16:08:53 -0700423 private void retainIconsOnStartup() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000424 // WebIconDatabase needs to be retrieved on the UI thread so that if
425 // it has not been created successfully yet the Handler is started on the
426 // UI thread.
427 new RetainIconsOnStartupTask(WebIconDatabase.getInstance()).execute();
428 }
429
430 private class RetainIconsOnStartupTask extends AsyncTask<Void, Void, Void> {
431 private WebIconDatabase mDb;
432
433 public RetainIconsOnStartupTask(WebIconDatabase db) {
434 mDb = db;
435 }
436
John Recka00cbbd2010-12-16 12:38:19 -0800437 @Override
Ben Murdoch9446b932010-11-25 16:20:14 +0000438 protected Void doInBackground(Void... unused) {
439 mDb.open(mActivity.getDir("icons", 0).getPath());
440 Cursor c = null;
441 try {
442 c = Browser.getAllBookmarks(mActivity.getContentResolver());
443 if (c.moveToFirst()) {
444 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
445 do {
446 String url = c.getString(urlIndex);
447 mDb.retainIconForPageUrl(url);
448 } while (c.moveToNext());
449 }
450 } catch (IllegalStateException e) {
451 Log.e(LOGTAG, "retainIconsOnStartup", e);
452 } finally {
453 if (c != null) c.close();
Michael Kolb8233fac2010-10-26 16:08:53 -0700454 }
Ben Murdoch9446b932010-11-25 16:20:14 +0000455
456 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700457 }
458 }
459
460 private void startHandler() {
461 mHandler = new Handler() {
462
463 @Override
464 public void handleMessage(Message msg) {
465 switch (msg.what) {
466 case OPEN_BOOKMARKS:
467 bookmarksOrHistoryPicker(false);
468 break;
469 case FOCUS_NODE_HREF:
470 {
471 String url = (String) msg.getData().get("url");
472 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500473 String src = (String) msg.getData().get("src");
474 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700475 if (TextUtils.isEmpty(url)) {
476 break;
477 }
478 HashMap focusNodeMap = (HashMap) msg.obj;
479 WebView view = (WebView) focusNodeMap.get("webview");
480 // Only apply the action if the top window did not change.
481 if (getCurrentTopWebView() != view) {
482 break;
483 }
484 switch (msg.arg1) {
485 case R.id.open_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700486 loadUrlFromContext(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700487 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500488 case R.id.view_image_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700489 loadUrlFromContext(src);
Cary Clark043c2d62010-12-15 11:19:39 -0500490 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500491 case R.id.open_newtab_context_menu_id:
492 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -0700493 openTab(url, parent,
494 !mSettings.openInBackground(), true);
Leon Scroggins026f2542010-11-22 13:26:12 -0500495 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700496 case R.id.copy_link_context_menu_id:
497 copy(url);
498 break;
499 case R.id.save_link_context_menu_id:
500 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500501 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000502 mActivity, url, null, null, null,
503 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700504 break;
505 }
506 break;
507 }
508
509 case LOAD_URL:
John Reck26b18322011-06-21 13:08:58 -0700510 loadUrlFromContext((String) msg.obj);
Michael Kolb8233fac2010-10-26 16:08:53 -0700511 break;
512
513 case STOP_LOAD:
514 stopLoading();
515 break;
516
517 case RELEASE_WAKELOCK:
518 if (mWakeLock.isHeld()) {
519 mWakeLock.release();
520 // if we reach here, Browser should be still in the
521 // background loading after WAKELOCK_TIMEOUT (5-min).
522 // To avoid burning the battery, stop loading.
523 mTabControl.stopAllLoading();
524 }
525 break;
526
527 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800528 Tab tab = (Tab) msg.obj;
529 if (tab != null) {
530 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700531 }
532 break;
533 }
534 }
535 };
536
537 }
538
Martijn Coenenb2f93552011-06-14 10:48:35 +0200539
540 public Tab getCurrentTab() {
541 return mTabControl.getCurrentTab();
542 }
543
Michael Kolbba99c5d2010-11-29 14:57:41 -0800544 @Override
545 public void shareCurrentPage() {
546 shareCurrentPage(mTabControl.getCurrentTab());
547 }
548
549 private void shareCurrentPage(Tab tab) {
550 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800551 sharePage(mActivity, tab.getTitle(),
552 tab.getUrl(), tab.getFavicon(),
553 createScreenshot(tab.getWebView(),
554 getDesiredThumbnailWidth(mActivity),
555 getDesiredThumbnailHeight(mActivity)));
556 }
557 }
558
Michael Kolb8233fac2010-10-26 16:08:53 -0700559 /**
560 * Share a page, providing the title, url, favicon, and a screenshot. Uses
561 * an {@link Intent} to launch the Activity chooser.
562 * @param c Context used to launch a new Activity.
563 * @param title Title of the page. Stored in the Intent with
564 * {@link Intent#EXTRA_SUBJECT}
565 * @param url URL of the page. Stored in the Intent with
566 * {@link Intent#EXTRA_TEXT}
567 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
568 * with {@link Browser#EXTRA_SHARE_FAVICON}
569 * @param screenshot Bitmap of a screenshot of the page. Stored in the
570 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
571 */
572 static final void sharePage(Context c, String title, String url,
573 Bitmap favicon, Bitmap screenshot) {
574 Intent send = new Intent(Intent.ACTION_SEND);
575 send.setType("text/plain");
576 send.putExtra(Intent.EXTRA_TEXT, url);
577 send.putExtra(Intent.EXTRA_SUBJECT, title);
578 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
579 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
580 try {
581 c.startActivity(Intent.createChooser(send, c.getString(
582 R.string.choosertitle_sharevia)));
583 } catch(android.content.ActivityNotFoundException ex) {
584 // if no app handles it, do nothing
585 }
586 }
587
588 private void copy(CharSequence text) {
589 ClipboardManager cm = (ClipboardManager) mActivity
590 .getSystemService(Context.CLIPBOARD_SERVICE);
591 cm.setText(text);
592 }
593
594 // lifecycle
595
596 protected void onConfgurationChanged(Configuration config) {
597 mConfigChanged = true;
598 if (mPageDialogsHandler != null) {
599 mPageDialogsHandler.onConfigurationChanged(config);
600 }
601 mUi.onConfigurationChanged(config);
602 }
603
604 @Override
605 public void handleNewIntent(Intent intent) {
606 mIntentHandler.onNewIntent(intent);
607 }
608
609 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800610 if (mUi.isCustomViewShowing()) {
611 hideCustomView();
612 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700613 if (mActivityPaused) {
614 Log.e(LOGTAG, "BrowserActivity is already paused.");
615 return;
616 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700617 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800618 Tab tab = mTabControl.getCurrentTab();
619 if (tab != null) {
620 tab.pause();
621 if (!pauseWebViewTimers(tab)) {
622 mWakeLock.acquire();
623 mHandler.sendMessageDelayed(mHandler
624 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
625 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700626 }
627 mUi.onPause();
628 mNetworkHandler.onPause();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200629 mNfcHandler.onPause();
Michael Kolb8233fac2010-10-26 16:08:53 -0700630
631 WebView.disablePlatformNotifications();
John Reck378a4102011-06-09 16:23:01 -0700632 mCrashRecoveryHandler.backupState();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200633
Michael Kolb8233fac2010-10-26 16:08:53 -0700634 }
635
John Reckaed9c542011-05-27 16:08:53 -0700636 void onSaveInstanceState(Bundle outState, boolean saveImages) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700637 // the default implementation requires each view to have an id. As the
638 // browser handles the state itself and it doesn't use id for the views,
639 // don't call the default implementation. Otherwise it will trigger the
640 // warning like this, "couldn't save which view has focus because the
641 // focused view XXX has no id".
642
643 // Save all the tabs
John Reckaed9c542011-05-27 16:08:53 -0700644 mTabControl.saveState(outState, saveImages);
John Reck24f18262011-06-17 14:47:20 -0700645 if (!outState.isEmpty()) {
646 // Save time so that we know how old incognito tabs (if any) are.
647 outState.putSerializable("lastActiveDate", Calendar.getInstance());
648 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700649 }
650
651 void onResume() {
652 if (!mActivityPaused) {
653 Log.e(LOGTAG, "BrowserActivity is already resumed.");
654 return;
655 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700656 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800657 Tab current = mTabControl.getCurrentTab();
658 if (current != null) {
659 current.resume();
660 resumeWebViewTimers(current);
661 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700662 if (mWakeLock.isHeld()) {
663 mHandler.removeMessages(RELEASE_WAKELOCK);
664 mWakeLock.release();
665 }
Martijn Coenenb2f93552011-06-14 10:48:35 +0200666
Michael Kolb8233fac2010-10-26 16:08:53 -0700667 mUi.onResume();
668 mNetworkHandler.onResume();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200669 mNfcHandler.onResume();
Michael Kolb8233fac2010-10-26 16:08:53 -0700670 WebView.enablePlatformNotifications();
671 }
672
Michael Kolb70976932010-11-30 11:34:01 -0800673 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800674 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800675 * @param tab guaranteed non-null
676 */
677 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700678 boolean inLoad = tab.inPageLoad();
679 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
680 CookieSyncManager.getInstance().startSync();
681 WebView w = tab.getWebView();
682 if (w != null) {
683 w.resumeTimers();
684 }
685 }
686 }
687
Michael Kolb70976932010-11-30 11:34:01 -0800688 /**
689 * Pause all WebView timers using the WebView of the given tab
690 * @param tab
691 * @return true if the timers are paused or tab is null
692 */
693 private boolean pauseWebViewTimers(Tab tab) {
694 if (tab == null) {
695 return true;
696 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700697 CookieSyncManager.getInstance().stopSync();
698 WebView w = getCurrentWebView();
699 if (w != null) {
700 w.pauseTimers();
701 }
702 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700703 }
Michael Kolb70976932010-11-30 11:34:01 -0800704 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700705 }
706
707 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800708 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700709 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
710 mUploadHandler = null;
711 }
712 if (mTabControl == null) return;
713 mUi.onDestroy();
714 // Remove the current tab and sub window
715 Tab t = mTabControl.getCurrentTab();
716 if (t != null) {
717 dismissSubWindow(t);
718 removeTab(t);
719 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500720 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700721 // Destroy all the tabs
722 mTabControl.destroy();
723 WebIconDatabase.getInstance().close();
724 // Stop watching the default geolocation permissions
725 mSystemAllowGeolocationOrigins.stop();
726 mSystemAllowGeolocationOrigins = null;
727 }
728
729 protected boolean isActivityPaused() {
730 return mActivityPaused;
731 }
732
733 protected void onLowMemory() {
734 mTabControl.freeMemory();
735 }
736
737 @Override
738 public boolean shouldShowErrorConsole() {
739 return mShouldShowErrorConsole;
740 }
741
742 protected void setShouldShowErrorConsole(boolean show) {
743 if (show == mShouldShowErrorConsole) {
744 // Nothing to do.
745 return;
746 }
747 mShouldShowErrorConsole = show;
748 Tab t = mTabControl.getCurrentTab();
749 if (t == null) {
750 // There is no current tab so we cannot toggle the error console
751 return;
752 }
753 mUi.setShouldShowErrorConsole(t, show);
754 }
755
756 @Override
757 public void stopLoading() {
758 mLoadStopped = true;
759 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700760 WebView w = getCurrentTopWebView();
761 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700762 mUi.onPageStopped(tab);
763 }
764
765 boolean didUserStopLoading() {
766 return mLoadStopped;
767 }
768
769 // WebViewController
770
771 @Override
John Reck324d4402011-01-11 16:56:42 -0800772 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700773
774 // We've started to load a new page. If there was a pending message
775 // to save a screenshot then we will now take the new page and save
776 // an incorrect screenshot. Therefore, remove any pending thumbnail
777 // messages from the queue.
778 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800779 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700780
781 // reset sync timer to avoid sync starts during loading a page
782 CookieSyncManager.getInstance().resetSync();
783
784 if (!mNetworkHandler.isNetworkUp()) {
785 view.setNetworkAvailable(false);
786 }
787
788 // when BrowserActivity just starts, onPageStarted may be called before
789 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
790 // to start the timer. As we won't switch tabs while an activity is in
791 // pause state, we can ensure calling resume and pause in pair.
792 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800793 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700794 }
795 mLoadStopped = false;
796 if (!mNetworkHandler.isNetworkUp()) {
797 mNetworkHandler.createAndShowNetworkDialog();
798 }
799 endActionMode();
800
John Reck30c714c2010-12-16 17:30:34 -0800801 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700802
John Reck324d4402011-01-11 16:56:42 -0800803 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700804 // update the bookmark database for favicon
805 maybeUpdateFavicon(tab, null, url, favicon);
806
807 Performance.tracePageStart(url);
808
809 // Performance probe
810 if (false) {
811 Performance.onPageStarted();
812 }
813
814 }
815
816 @Override
John Reck324d4402011-01-11 16:56:42 -0800817 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800818 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800819 if (!tab.isPrivateBrowsingEnabled()
John Reckd8c74522011-06-14 08:45:00 -0700820 && !TextUtils.isEmpty(tab.getUrl())
821 && !tab.isSnapshot()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700822 if (tab.inForeground() && !didUserStopLoading()
823 || !tab.inForeground()) {
824 // Only update the bookmark screenshot if the user did not
825 // cancel the load early.
826 mHandler.sendMessageDelayed(mHandler.obtainMessage(
John Reck34ef2672011-02-10 11:30:55 -0800827 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
Michael Kolb8233fac2010-10-26 16:08:53 -0700828 500);
829 }
830 }
831 // pause the WebView timer and release the wake lock if it is finished
832 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800833 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700834 if (mWakeLock.isHeld()) {
835 mHandler.removeMessages(RELEASE_WAKELOCK);
836 mWakeLock.release();
837 }
838 }
Martijn Coenenb2f93552011-06-14 10:48:35 +0200839
Michael Kolb8233fac2010-10-26 16:08:53 -0700840 // Performance probe
841 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800842 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700843 }
844
845 Performance.tracePageFinished();
846 }
847
848 @Override
John Reck30c714c2010-12-16 17:30:34 -0800849 public void onProgressChanged(Tab tab) {
850 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700851
852 if (newProgress == 100) {
853 CookieSyncManager.getInstance().sync();
854 // onProgressChanged() may continue to be called after the main
855 // frame has finished loading, as any remaining sub frames continue
856 // to load. We'll only get called once though with newProgress as
857 // 100 when everything is loaded. (onPageFinished is called once
858 // when the main frame completes loading regardless of the state of
859 // any sub frames so calls to onProgressChanges may continue after
860 // onPageFinished has executed)
861 if (mInLoad) {
862 mInLoad = false;
863 updateInLoadMenuItems(mCachedMenu);
864 }
865 } else {
866 if (!mInLoad) {
867 // onPageFinished may have already been called but a subframe is
868 // still loading and updating the progress. Reset mInLoad and
869 // update the menu items.
870 mInLoad = true;
871 updateInLoadMenuItems(mCachedMenu);
872 }
873 }
John Reck30c714c2010-12-16 17:30:34 -0800874 mUi.onProgressChanged(tab);
875 }
876
877 @Override
878 public void onUpdatedLockIcon(Tab tab) {
879 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700880 }
881
882 @Override
883 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800884 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800885 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800886 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700887 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
888 return;
889 }
890 // Update the title in the history database if not in private browsing mode
891 if (!tab.isPrivateBrowsingEnabled()) {
John Reck0ebd3ac2010-12-09 11:14:04 -0800892 mDataController.updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700893 }
894 }
895
896 @Override
897 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800898 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700899 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
900 }
901
902 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800903 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
904 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700905 }
906
907 @Override
908 public boolean shouldOverrideKeyEvent(KeyEvent event) {
909 if (mMenuIsDown) {
910 // only check shortcut key when MENU is held
911 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
912 event);
913 } else {
914 return false;
915 }
916 }
917
918 @Override
919 public void onUnhandledKeyEvent(KeyEvent event) {
920 if (!isActivityPaused()) {
921 if (event.getAction() == KeyEvent.ACTION_DOWN) {
922 mActivity.onKeyDown(event.getKeyCode(), event);
923 } else {
924 mActivity.onKeyUp(event.getKeyCode(), event);
925 }
926 }
927 }
928
929 @Override
John Reck324d4402011-01-11 16:56:42 -0800930 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700931 // Don't save anything in private browsing mode
932 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800933 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700934
John Reck324d4402011-01-11 16:56:42 -0800935 if (TextUtils.isEmpty(url)
936 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700937 return;
938 }
John Reck0ebd3ac2010-12-09 11:14:04 -0800939 mDataController.updateVisitedHistory(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700940 WebIconDatabase.getInstance().retainIconForPageUrl(url);
John Reck847b5322011-04-14 17:02:18 -0700941 if (!mActivityPaused) {
942 // Since we clear the state in onPause, don't backup the current
943 // state if we are already paused
944 mCrashRecoveryHandler.backupState();
945 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700946 }
947
948 @Override
949 public void getVisitedHistory(final ValueCallback<String[]> callback) {
950 AsyncTask<Void, Void, String[]> task =
951 new AsyncTask<Void, Void, String[]>() {
952 @Override
953 public String[] doInBackground(Void... unused) {
954 return Browser.getVisitedHistory(mActivity.getContentResolver());
955 }
956 @Override
957 public void onPostExecute(String[] result) {
958 callback.onReceiveValue(result);
959 }
960 };
961 task.execute();
962 }
963
964 @Override
965 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
966 final HttpAuthHandler handler, final String host,
967 final String realm) {
968 String username = null;
969 String password = null;
970
971 boolean reuseHttpAuthUsernamePassword
972 = handler.useHttpAuthUsernamePassword();
973
974 if (reuseHttpAuthUsernamePassword && view != null) {
975 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
976 if (credentials != null && credentials.length == 2) {
977 username = credentials[0];
978 password = credentials[1];
979 }
980 }
981
982 if (username != null && password != null) {
983 handler.proceed(username, password);
984 } else {
985 if (tab.inForeground()) {
986 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
987 } else {
988 handler.cancel();
989 }
990 }
991 }
992
993 @Override
994 public void onDownloadStart(Tab tab, String url, String userAgent,
995 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000996 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -0500997 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000998 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
999 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001000 // This Tab was opened for the sole purpose of downloading a
1001 // file. Remove it.
1002 if (tab == mTabControl.getCurrentTab()) {
1003 // In this case, the Tab is still on top.
1004 goBackOnePageOrQuit();
1005 } else {
1006 // In this case, it is not.
1007 closeTab(tab);
1008 }
1009 }
1010 }
1011
1012 @Override
1013 public Bitmap getDefaultVideoPoster() {
1014 return mUi.getDefaultVideoPoster();
1015 }
1016
1017 @Override
1018 public View getVideoLoadingProgressView() {
1019 return mUi.getVideoLoadingProgressView();
1020 }
1021
1022 @Override
1023 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1024 SslError error) {
1025 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1026 }
1027
Patrick Scott92066772011-03-10 08:46:27 -05001028 @Override
1029 public void showAutoLogin(Tab tab) {
1030 assert tab.inForeground();
1031 // Update the title bar to show the auto-login request.
1032 mUi.showAutoLogin(tab);
1033 }
1034
1035 @Override
1036 public void hideAutoLogin(Tab tab) {
1037 assert tab.inForeground();
1038 mUi.hideAutoLogin(tab);
1039 }
1040
Michael Kolb8233fac2010-10-26 16:08:53 -07001041 // helper method
1042
1043 /*
1044 * Update the favorites icon if the private browsing isn't enabled and the
1045 * icon is valid.
1046 */
1047 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1048 final String url, Bitmap favicon) {
1049 if (favicon == null) {
1050 return;
1051 }
1052 if (!tab.isPrivateBrowsingEnabled()) {
1053 Bookmarks.updateFavicon(mActivity
1054 .getContentResolver(), originalUrl, url, favicon);
1055 }
1056 }
1057
Leon Scroggins4cd97792010-12-03 15:31:56 -05001058 @Override
1059 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001060 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001061 mUi.bookmarkedStatusHasChanged(tab);
1062 }
1063
Michael Kolb8233fac2010-10-26 16:08:53 -07001064 // end WebViewController
1065
1066 protected void pageUp() {
1067 getCurrentTopWebView().pageUp(false);
1068 }
1069
1070 protected void pageDown() {
1071 getCurrentTopWebView().pageDown(false);
1072 }
1073
1074 // callback from phone title bar
1075 public void editUrl() {
1076 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001077 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001078 }
1079
Michael Kolbcfa3af52010-12-14 10:36:11 -08001080 public void startVoiceSearch() {
1081 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1082 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1083 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1084 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1085 mActivity.getComponentName().flattenToString());
1086 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001087 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001088 mActivity.startActivity(intent);
1089 }
1090
Michael Kolb11d19782011-03-20 10:17:40 -07001091 @Override
1092 public void activateVoiceSearchMode(String title, List<String> results) {
1093 mUi.showVoiceTitleBar(title, results);
Michael Kolb8233fac2010-10-26 16:08:53 -07001094 }
1095
1096 public void revertVoiceSearchMode(Tab tab) {
1097 mUi.revertVoiceTitleBar(tab);
1098 }
1099
Michael Kolb736990c2011-03-20 10:01:20 -07001100 public boolean supportsVoiceSearch() {
John Reck35e9dd62011-04-25 09:01:54 -07001101 SearchEngine searchEngine = getSettings().getSearchEngine();
Michael Kolb736990c2011-03-20 10:01:20 -07001102 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1103 }
1104
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001105 public void showCustomView(Tab tab, View view, int requestedOrientation,
Michael Kolb8233fac2010-10-26 16:08:53 -07001106 WebChromeClient.CustomViewCallback callback) {
1107 if (tab.inForeground()) {
1108 if (mUi.isCustomViewShowing()) {
1109 callback.onCustomViewHidden();
1110 return;
1111 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001112 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001113 // Save the menu state and set it to empty while the custom
1114 // view is showing.
1115 mOldMenuState = mMenuState;
1116 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001117 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001118 }
1119 }
1120
1121 @Override
1122 public void hideCustomView() {
1123 if (mUi.isCustomViewShowing()) {
1124 mUi.onHideCustomView();
1125 // Reset the old menu state.
1126 mMenuState = mOldMenuState;
1127 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001128 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001129 }
1130 }
1131
1132 protected void onActivityResult(int requestCode, int resultCode,
1133 Intent intent) {
1134 if (getCurrentTopWebView() == null) return;
1135 switch (requestCode) {
1136 case PREFERENCES_PAGE:
1137 if (resultCode == Activity.RESULT_OK && intent != null) {
1138 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001139 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001140 mTabControl.removeParentChildRelationShips();
1141 }
1142 }
1143 break;
1144 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001145 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001146 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001147 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001148 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001149 case AUTOFILL_SETUP:
1150 // Determine whether a profile was actually set up or not
1151 // and if so, send the message back to the WebTextView to
1152 // fill the form with the new profile.
1153 if (getSettings().getAutoFillProfile() != null) {
1154 mAutoFillSetupMessage.sendToTarget();
1155 mAutoFillSetupMessage = null;
1156 }
1157 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001158 default:
1159 break;
1160 }
1161 getCurrentTopWebView().requestFocus();
1162 }
1163
1164 /**
1165 * Open the Go page.
1166 * @param startWithHistory If true, open starting on the history tab.
1167 * Otherwise, start with the bookmarks tab.
1168 */
1169 @Override
1170 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1171 if (mTabControl.getCurrentWebView() == null) {
1172 return;
1173 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001174 // clear action mode
1175 if (isInCustomActionMode()) {
1176 endActionMode();
1177 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001178 Bundle extras = new Bundle();
1179 // Disable opening in a new window if we have maxed out the windows
1180 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1181 !mTabControl.canCreateNewTab());
1182 mUi.showComboView(startWithHistory, extras);
1183 }
1184
1185 // combo view callbacks
1186
1187 /**
1188 * callback from ComboPage when clear history is requested
1189 */
1190 public void onRemoveParentChildRelationships() {
1191 mTabControl.removeParentChildRelationShips();
1192 }
1193
1194 /**
1195 * callback from ComboPage when bookmark/history selection
1196 */
1197 @Override
1198 public void onUrlSelected(String url, boolean newTab) {
1199 removeComboView();
1200 if (!TextUtils.isEmpty(url)) {
1201 if (newTab) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07001202 final Tab parent = mTabControl.getCurrentTab();
1203 openTab(url,
1204 (parent != null) && parent.isPrivateBrowsingEnabled(),
1205 !mSettings.openInBackground(),
1206 true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001207 } else {
1208 final Tab currentTab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07001209 loadUrl(currentTab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07001210 }
1211 }
1212 }
1213
1214 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07001215 * dismiss the ComboPage
1216 */
1217 @Override
1218 public void removeComboView() {
1219 mUi.hideComboView();
1220 }
1221
1222 // active tabs page handling
1223
1224 protected void showActiveTabsPage() {
1225 mMenuState = EMPTY_MENU;
1226 mUi.showActiveTabsPage();
1227 }
1228
1229 /**
1230 * Remove the active tabs page.
1231 * @param needToAttach If true, the active tabs page did not attach a tab
1232 * to the content view, so we need to do that here.
1233 */
1234 @Override
1235 public void removeActiveTabsPage(boolean needToAttach) {
1236 mMenuState = R.id.MAIN_MENU;
1237 mUi.removeActiveTabsPage();
1238 if (needToAttach) {
1239 setActiveTab(mTabControl.getCurrentTab());
1240 }
1241 getCurrentTopWebView().requestFocus();
1242 }
1243
1244 // key handling
1245 protected void onBackKey() {
1246 if (!mUi.onBackKey()) {
1247 WebView subwindow = mTabControl.getCurrentSubWindow();
1248 if (subwindow != null) {
1249 if (subwindow.canGoBack()) {
1250 subwindow.goBack();
1251 } else {
1252 dismissSubWindow(mTabControl.getCurrentTab());
1253 }
1254 } else {
1255 goBackOnePageOrQuit();
1256 }
1257 }
1258 }
1259
Michael Kolb4bd767d2011-05-27 11:33:55 -07001260 protected boolean onMenuKey() {
1261 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001262 }
1263
Michael Kolb8233fac2010-10-26 16:08:53 -07001264 // menu handling and state
1265 // TODO: maybe put into separate handler
1266
1267 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckb3417f02011-01-14 11:01:05 -08001268 if (mOptionsMenuHandler != null) {
1269 return mOptionsMenuHandler.onCreateOptionsMenu(menu);
1270 }
1271
John Reckd73c5a22010-12-22 10:22:50 -08001272 if (mMenuState == EMPTY_MENU) {
1273 return false;
1274 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001275 MenuInflater inflater = mActivity.getMenuInflater();
1276 inflater.inflate(R.menu.browser, menu);
1277 updateInLoadMenuItems(menu);
1278 // hold on to the menu reference here; it is used by the page callbacks
1279 // to update the menu based on loading state
1280 mCachedMenu = menu;
1281 return true;
1282 }
1283
1284 protected void onCreateContextMenu(ContextMenu menu, View v,
1285 ContextMenuInfo menuInfo) {
1286 if (v instanceof TitleBarBase) {
1287 return;
1288 }
1289 if (!(v instanceof WebView)) {
1290 return;
1291 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001292 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001293 WebView.HitTestResult result = webview.getHitTestResult();
1294 if (result == null) {
1295 return;
1296 }
1297
1298 int type = result.getType();
1299 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1300 Log.w(LOGTAG,
1301 "We should not show context menu when nothing is touched");
1302 return;
1303 }
1304 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1305 // let TextView handles context menu
1306 return;
1307 }
1308
1309 // Note, http://b/issue?id=1106666 is requesting that
1310 // an inflated menu can be used again. This is not available
1311 // yet, so inflate each time (yuk!)
1312 MenuInflater inflater = mActivity.getMenuInflater();
1313 inflater.inflate(R.menu.browsercontext, menu);
1314
1315 // Show the correct menu group
1316 final String extra = result.getExtra();
1317 menu.setGroupVisible(R.id.PHONE_MENU,
1318 type == WebView.HitTestResult.PHONE_TYPE);
1319 menu.setGroupVisible(R.id.EMAIL_MENU,
1320 type == WebView.HitTestResult.EMAIL_TYPE);
1321 menu.setGroupVisible(R.id.GEO_MENU,
1322 type == WebView.HitTestResult.GEO_TYPE);
1323 menu.setGroupVisible(R.id.IMAGE_MENU,
1324 type == WebView.HitTestResult.IMAGE_TYPE
1325 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1326 menu.setGroupVisible(R.id.ANCHOR_MENU,
1327 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1328 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001329 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1330 || type == WebView.HitTestResult.PHONE_TYPE
1331 || type == WebView.HitTestResult.EMAIL_TYPE
1332 || type == WebView.HitTestResult.GEO_TYPE;
1333 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1334 if (hitText) {
1335 menu.findItem(R.id.select_text_menu_id)
1336 .setOnMenuItemClickListener(new SelectText(webview));
1337 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001338 // Setup custom handling depending on the type
1339 switch (type) {
1340 case WebView.HitTestResult.PHONE_TYPE:
1341 menu.setHeaderTitle(Uri.decode(extra));
1342 menu.findItem(R.id.dial_context_menu_id).setIntent(
1343 new Intent(Intent.ACTION_VIEW, Uri
1344 .parse(WebView.SCHEME_TEL + extra)));
1345 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1346 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1347 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1348 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1349 addIntent);
1350 menu.findItem(R.id.copy_phone_context_menu_id)
1351 .setOnMenuItemClickListener(
1352 new Copy(extra));
1353 break;
1354
1355 case WebView.HitTestResult.EMAIL_TYPE:
1356 menu.setHeaderTitle(extra);
1357 menu.findItem(R.id.email_context_menu_id).setIntent(
1358 new Intent(Intent.ACTION_VIEW, Uri
1359 .parse(WebView.SCHEME_MAILTO + extra)));
1360 menu.findItem(R.id.copy_mail_context_menu_id)
1361 .setOnMenuItemClickListener(
1362 new Copy(extra));
1363 break;
1364
1365 case WebView.HitTestResult.GEO_TYPE:
1366 menu.setHeaderTitle(extra);
1367 menu.findItem(R.id.map_context_menu_id).setIntent(
1368 new Intent(Intent.ACTION_VIEW, Uri
1369 .parse(WebView.SCHEME_GEO
1370 + URLEncoder.encode(extra))));
1371 menu.findItem(R.id.copy_geo_context_menu_id)
1372 .setOnMenuItemClickListener(
1373 new Copy(extra));
1374 break;
1375
1376 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1377 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001378 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001379 // decide whether to show the open link in new tab option
1380 boolean showNewTab = mTabControl.canCreateNewTab();
1381 MenuItem newTabItem
1382 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001383 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001384 ? R.string.contextmenu_openlink_newwindow_background
1385 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001386 newTabItem.setVisible(showNewTab);
1387 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001388 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1389 newTabItem.setOnMenuItemClickListener(
1390 new MenuItem.OnMenuItemClickListener() {
1391 @Override
1392 public boolean onMenuItemClick(MenuItem item) {
1393 final HashMap<String, WebView> hrefMap =
1394 new HashMap<String, WebView>();
1395 hrefMap.put("webview", webview);
1396 final Message msg = mHandler.obtainMessage(
1397 FOCUS_NODE_HREF,
1398 R.id.open_newtab_context_menu_id,
1399 0, hrefMap);
1400 webview.requestFocusNodeHref(msg);
1401 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001402 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001403 });
1404 } else {
1405 newTabItem.setOnMenuItemClickListener(
1406 new MenuItem.OnMenuItemClickListener() {
1407 @Override
1408 public boolean onMenuItemClick(MenuItem item) {
1409 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001410 openTab(extra, parent,
1411 !mSettings.openInBackground(),
1412 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001413 return true;
1414 }
1415 });
1416 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001417 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001418 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1419 break;
1420 }
1421 // otherwise fall through to handle image part
1422 case WebView.HitTestResult.IMAGE_TYPE:
1423 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1424 menu.setHeaderTitle(extra);
1425 }
1426 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1427 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1428 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001429 setOnMenuItemClickListener(
1430 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001431 menu.findItem(R.id.set_wallpaper_context_menu_id).
1432 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1433 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001434 break;
1435
1436 default:
1437 Log.w(LOGTAG, "We should not get here.");
1438 break;
1439 }
1440 //update the ui
1441 mUi.onContextMenuCreated(menu);
1442 }
1443
1444 /**
1445 * As the menu can be open when loading state changes
1446 * we must manually update the state of the stop/reload menu
1447 * item
1448 */
1449 private void updateInLoadMenuItems(Menu menu) {
1450 if (menu == null) {
1451 return;
1452 }
1453 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1454 MenuItem src = mInLoad ?
1455 menu.findItem(R.id.stop_menu_id):
1456 menu.findItem(R.id.reload_menu_id);
1457 if (src != null) {
1458 dest.setIcon(src.getIcon());
1459 dest.setTitle(src.getTitle());
1460 }
1461 }
1462
John Reckb3417f02011-01-14 11:01:05 -08001463 boolean onPrepareOptionsMenu(Menu menu) {
1464 if (mOptionsMenuHandler != null) {
1465 return mOptionsMenuHandler.onPrepareOptionsMenu(menu);
1466 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001467 // Note: setVisible will decide whether an item is visible; while
1468 // setEnabled() will decide whether an item is enabled, which also means
1469 // whether the matching shortcut key will function.
1470 switch (mMenuState) {
1471 case EMPTY_MENU:
1472 if (mCurrentMenuState != mMenuState) {
1473 menu.setGroupVisible(R.id.MAIN_MENU, false);
1474 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1475 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1476 }
1477 break;
1478 default:
1479 if (mCurrentMenuState != mMenuState) {
1480 menu.setGroupVisible(R.id.MAIN_MENU, true);
1481 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1482 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1483 }
1484 final WebView w = getCurrentTopWebView();
1485 boolean canGoBack = false;
1486 boolean canGoForward = false;
1487 boolean isHome = false;
1488 if (w != null) {
1489 canGoBack = w.canGoBack();
1490 canGoForward = w.canGoForward();
1491 isHome = mSettings.getHomePage().equals(w.getUrl());
1492 }
1493 final MenuItem back = menu.findItem(R.id.back_menu_id);
1494 back.setEnabled(canGoBack);
1495
1496 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1497 home.setEnabled(!isHome);
1498
1499 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1500 forward.setEnabled(canGoForward);
1501
1502 // decide whether to show the share link option
1503 PackageManager pm = mActivity.getPackageManager();
1504 Intent send = new Intent(Intent.ACTION_SEND);
1505 send.setType("text/plain");
1506 ResolveInfo ri = pm.resolveActivity(send,
1507 PackageManager.MATCH_DEFAULT_ONLY);
1508 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1509
John Reck35e9dd62011-04-25 09:01:54 -07001510 boolean isNavDump = mSettings.enableNavDump();
Michael Kolb8233fac2010-10-26 16:08:53 -07001511 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1512 nav.setVisible(isNavDump);
1513 nav.setEnabled(isNavDump);
1514
John Reck35e9dd62011-04-25 09:01:54 -07001515 boolean showDebugSettings = mSettings.isDebugEnabled();
Michael Kolb8233fac2010-10-26 16:08:53 -07001516 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1517 counter.setVisible(showDebugSettings);
1518 counter.setEnabled(showDebugSettings);
1519
John Reckb3417f02011-01-14 11:01:05 -08001520 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1521 newtab.setEnabled(getTabControl().canCreateNewTab());
Michael Kolb8233fac2010-10-26 16:08:53 -07001522
Leon Scroggins81983762011-02-11 15:17:36 -05001523 MenuItem archive = menu.findItem(R.id.save_webarchive_menu_id);
John Reck51d8bad2011-02-28 15:47:47 -08001524 Tab tab = getTabControl().getCurrentTab();
1525 String url = tab != null ? tab.getUrl() : null;
1526 archive.setVisible(!TextUtils.isEmpty(url)
1527 && !url.endsWith(".webarchivexml"));
Michael Kolb8233fac2010-10-26 16:08:53 -07001528 break;
1529 }
1530 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001531 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001532 }
1533
1534 public boolean onOptionsItemSelected(MenuItem item) {
John Reckb3417f02011-01-14 11:01:05 -08001535 if (mOptionsMenuHandler != null &&
1536 mOptionsMenuHandler.onOptionsItemSelected(item)) {
1537 return true;
1538 }
1539
Michael Kolb8233fac2010-10-26 16:08:53 -07001540 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1541 // menu remains active, so ensure comboview is dismissed
1542 // if main menu option is selected
1543 removeComboView();
1544 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001545 if (null == getCurrentTopWebView()) {
1546 return false;
1547 }
1548 if (mMenuIsDown) {
1549 // The shortcut action consumes the MENU. Even if it is still down,
1550 // it won't trigger the next shortcut action. In the case of the
1551 // shortcut action triggering a new activity, like Bookmarks, we
1552 // won't get onKeyUp for MENU. So it is important to reset it here.
1553 mMenuIsDown = false;
1554 }
1555 switch (item.getItemId()) {
1556 // -- Main menu
1557 case R.id.new_tab_menu_id:
1558 openTabToHomePage();
1559 break;
1560
1561 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001562 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001563 break;
1564
1565 case R.id.goto_menu_id:
1566 editUrl();
1567 break;
1568
1569 case R.id.bookmarks_menu_id:
1570 bookmarksOrHistoryPicker(false);
1571 break;
1572
1573 case R.id.active_tabs_menu_id:
1574 showActiveTabsPage();
1575 break;
1576
1577 case R.id.add_bookmark_menu_id:
John Reck3ffc5ca2011-06-10 15:56:06 -07001578 bookmarkCurrentPage(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001579 break;
1580
1581 case R.id.stop_reload_menu_id:
1582 if (mInLoad) {
1583 stopLoading();
1584 } else {
1585 getCurrentTopWebView().reload();
1586 }
1587 break;
1588
1589 case R.id.back_menu_id:
1590 getCurrentTopWebView().goBack();
1591 break;
1592
1593 case R.id.forward_menu_id:
1594 getCurrentTopWebView().goForward();
1595 break;
1596
1597 case R.id.close_menu_id:
1598 // Close the subwindow if it exists.
1599 if (mTabControl.getCurrentSubWindow() != null) {
1600 dismissSubWindow(mTabControl.getCurrentTab());
1601 break;
1602 }
1603 closeCurrentTab();
1604 break;
1605
1606 case R.id.homepage_menu_id:
1607 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07001608 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07001609 break;
1610
1611 case R.id.preferences_menu_id:
1612 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1613 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1614 getCurrentTopWebView().getUrl());
1615 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1616 break;
1617
1618 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001619 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001620 break;
1621
John Reckf33b1632011-06-04 20:00:23 -07001622 case R.id.freeze_tab_menu_id:
1623 // TODO: Show error messages
John Reck541f55a2011-06-07 16:34:43 -07001624 Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07001625 if (source == null) break;
John Reckd8c74522011-06-14 08:45:00 -07001626 final ContentResolver cr = mActivity.getContentResolver();
1627 final ContentValues values = source.createSnapshotValues();
1628 new AsyncTask<Tab, Void, Long>() {
1629 @Override
1630 protected Long doInBackground(Tab... params) {
1631 Tab t = params[0];
1632 if (values == null) {
1633 return t.isSnapshot()
1634 ? ((SnapshotTab)t).getSnapshotId()
1635 : -1;
1636 }
1637 Uri result = cr.insert(Snapshots.CONTENT_URI, values);
1638 long id = ContentUris.parseId(result);
1639 return id;
1640 }
1641
Michael Kolb14612442011-06-24 13:06:29 -07001642 @Override
John Reckd8c74522011-06-14 08:45:00 -07001643 protected void onPostExecute(Long id) {
1644 if (id > 0) {
1645 createNewSnapshotTab(id, true);
1646 }
1647 };
1648 }.execute(source);
John Reckf33b1632011-06-04 20:00:23 -07001649 break;
1650
Leon Scrogginsac993842011-02-02 12:54:07 -05001651 case R.id.save_webarchive_menu_id:
1652 String state = Environment.getExternalStorageState();
1653 if (!Environment.MEDIA_MOUNTED.equals(state)) {
1654 Log.e(LOGTAG, "External storage not mounted");
1655 Toast.makeText(mActivity, R.string.webarchive_failed,
1656 Toast.LENGTH_SHORT).show();
1657 break;
1658 }
1659 final String directory = Environment.getExternalStoragePublicDirectory(
1660 Environment.DIRECTORY_DOWNLOADS) + File.separator;
1661 File dir = new File(directory);
1662 if (!dir.exists() && !dir.mkdirs()) {
1663 Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
1664 Toast.makeText(mActivity, R.string.webarchive_failed,
1665 Toast.LENGTH_SHORT).show();
1666 break;
1667 }
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001668 final WebView topWebView = getCurrentTopWebView();
Leon Scrogginsac993842011-02-02 12:54:07 -05001669 final String title = topWebView.getTitle();
John Reck51d8bad2011-02-28 15:47:47 -08001670 final String url = topWebView.getUrl();
Leon Scrogginsac993842011-02-02 12:54:07 -05001671 topWebView.saveWebArchive(directory, true,
1672 new ValueCallback<String>() {
1673 @Override
1674 public void onReceiveValue(final String value) {
1675 if (value != null) {
1676 File file = new File(value);
1677 final long length = file.length();
1678 if (file.exists() && length > 0) {
Leon Scroggins1cb96552011-02-11 14:22:57 -05001679 Toast.makeText(mActivity, R.string.webarchive_saved,
1680 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001681 final DownloadManager manager = (DownloadManager) mActivity
1682 .getSystemService(Context.DOWNLOAD_SERVICE);
1683 new Thread("Add WebArchive to download manager") {
1684 @Override
1685 public void run() {
Vasu Noria9e30a72011-03-07 11:37:34 -08001686 manager.addCompletedDownload(
1687 null == title ? value : title,
Leon Scrogginsac993842011-02-02 12:54:07 -05001688 value, true, "application/x-webarchive-xml",
1689 value, length, true);
1690 }
1691 }.start();
1692 return;
1693 }
1694 }
John Reck51d8bad2011-02-28 15:47:47 -08001695 DownloadHandler.onDownloadStartNoStream(mActivity,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001696 url, null, null, null, topWebView.isPrivateBrowsingEnabled());
Leon Scrogginsac993842011-02-02 12:54:07 -05001697 }
1698 });
1699 break;
1700
Michael Kolb8233fac2010-10-26 16:08:53 -07001701 case R.id.page_info_menu_id:
Huahui Wuae0c0412011-06-28 10:17:05 -07001702 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001703 break;
1704
1705 case R.id.classic_history_menu_id:
1706 bookmarksOrHistoryPicker(true);
1707 break;
1708
1709 case R.id.title_bar_share_page_url:
1710 case R.id.share_page_menu_id:
1711 Tab currentTab = mTabControl.getCurrentTab();
1712 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001713 return false;
1714 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001715 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001716 break;
1717
1718 case R.id.dump_nav_menu_id:
1719 getCurrentTopWebView().debugDump();
1720 break;
1721
1722 case R.id.dump_counters_menu_id:
1723 getCurrentTopWebView().dumpV8Counters();
1724 break;
1725
1726 case R.id.zoom_in_menu_id:
1727 getCurrentTopWebView().zoomIn();
1728 break;
1729
1730 case R.id.zoom_out_menu_id:
1731 getCurrentTopWebView().zoomOut();
1732 break;
1733
1734 case R.id.view_downloads_menu_id:
1735 viewDownloads();
1736 break;
1737
1738 case R.id.window_one_menu_id:
1739 case R.id.window_two_menu_id:
1740 case R.id.window_three_menu_id:
1741 case R.id.window_four_menu_id:
1742 case R.id.window_five_menu_id:
1743 case R.id.window_six_menu_id:
1744 case R.id.window_seven_menu_id:
1745 case R.id.window_eight_menu_id:
1746 {
1747 int menuid = item.getItemId();
1748 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1749 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1750 Tab desiredTab = mTabControl.getTab(id);
1751 if (desiredTab != null &&
1752 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001753 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001754 }
1755 break;
1756 }
1757 }
1758 }
1759 break;
1760
1761 default:
1762 return false;
1763 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001764 return true;
1765 }
1766
1767 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001768 // Let the History and Bookmark fragments handle menus they created.
1769 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1770 return false;
1771 }
1772
Michael Kolb8233fac2010-10-26 16:08:53 -07001773 int id = item.getItemId();
1774 boolean result = true;
1775 switch (id) {
1776 // For the context menu from the title bar
1777 case R.id.title_bar_copy_page_url:
1778 Tab currentTab = mTabControl.getCurrentTab();
1779 if (null == currentTab) {
1780 result = false;
1781 break;
1782 }
1783 WebView mainView = currentTab.getWebView();
1784 if (null == mainView) {
1785 result = false;
1786 break;
1787 }
1788 copy(mainView.getUrl());
1789 break;
1790 // -- Browser context menu
1791 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001792 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001793 case R.id.copy_link_context_menu_id:
1794 final WebView webView = getCurrentTopWebView();
1795 if (null == webView) {
1796 result = false;
1797 break;
1798 }
1799 final HashMap<String, WebView> hrefMap =
1800 new HashMap<String, WebView>();
1801 hrefMap.put("webview", webView);
1802 final Message msg = mHandler.obtainMessage(
1803 FOCUS_NODE_HREF, id, 0, hrefMap);
1804 webView.requestFocusNodeHref(msg);
1805 break;
1806
1807 default:
1808 // For other context menus
1809 result = onOptionsItemSelected(item);
1810 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001811 return result;
1812 }
1813
1814 /**
1815 * support programmatically opening the context menu
1816 */
1817 public void openContextMenu(View view) {
1818 mActivity.openContextMenu(view);
1819 }
1820
1821 /**
1822 * programmatically open the options menu
1823 */
1824 public void openOptionsMenu() {
1825 mActivity.openOptionsMenu();
1826 }
1827
1828 public boolean onMenuOpened(int featureId, Menu menu) {
1829 if (mOptionsMenuOpen) {
1830 if (mConfigChanged) {
1831 // We do not need to make any changes to the state of the
1832 // title bar, since the only thing that happened was a
1833 // change in orientation
1834 mConfigChanged = false;
1835 } else {
1836 if (!mExtendedMenuOpen) {
1837 mExtendedMenuOpen = true;
1838 mUi.onExtendedMenuOpened();
1839 } else {
1840 // Switching the menu back to icon view, so show the
1841 // title bar once again.
1842 mExtendedMenuOpen = false;
1843 mUi.onExtendedMenuClosed(mInLoad);
Michael Kolb8233fac2010-10-26 16:08:53 -07001844 }
1845 }
1846 } else {
1847 // The options menu is closed, so open it, and show the title
1848 mOptionsMenuOpen = true;
1849 mConfigChanged = false;
1850 mExtendedMenuOpen = false;
1851 mUi.onOptionsMenuOpened();
1852 }
1853 return true;
1854 }
1855
1856 public void onOptionsMenuClosed(Menu menu) {
1857 mOptionsMenuOpen = false;
1858 mUi.onOptionsMenuClosed(mInLoad);
1859 }
1860
1861 public void onContextMenuClosed(Menu menu) {
1862 mUi.onContextMenuClosed(menu, mInLoad);
1863 }
1864
1865 // Helper method for getting the top window.
1866 @Override
1867 public WebView getCurrentTopWebView() {
1868 return mTabControl.getCurrentTopWebView();
1869 }
1870
1871 @Override
1872 public WebView getCurrentWebView() {
1873 return mTabControl.getCurrentWebView();
1874 }
1875
1876 /*
1877 * This method is called as a result of the user selecting the options
1878 * menu to see the download window. It shows the download window on top of
1879 * the current window.
1880 */
1881 void viewDownloads() {
1882 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1883 mActivity.startActivity(intent);
1884 }
1885
1886 // action mode
1887
1888 void onActionModeStarted(ActionMode mode) {
1889 mUi.onActionModeStarted(mode);
1890 mActionMode = mode;
1891 }
1892
1893 /*
1894 * True if a custom ActionMode (i.e. find or select) is in use.
1895 */
1896 @Override
1897 public boolean isInCustomActionMode() {
1898 return mActionMode != null;
1899 }
1900
1901 /*
1902 * End the current ActionMode.
1903 */
1904 @Override
1905 public void endActionMode() {
1906 if (mActionMode != null) {
1907 mActionMode.finish();
1908 }
1909 }
1910
1911 /*
1912 * Called by find and select when they are finished. Replace title bars
1913 * as necessary.
1914 */
1915 public void onActionModeFinished(ActionMode mode) {
1916 if (!isInCustomActionMode()) return;
1917 mUi.onActionModeFinished(mInLoad);
1918 mActionMode = null;
1919 }
1920
1921 boolean isInLoad() {
1922 return mInLoad;
1923 }
1924
1925 // bookmark handling
1926
1927 /**
1928 * add the current page as a bookmark to the given folder id
1929 * @param folderId use -1 for the default folder
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001930 * @param canBeAnEdit If true, check to see whether the site is already
1931 * bookmarked, and if it is, edit that bookmark. If false, and
1932 * the site is already bookmarked, do not attempt to edit the
1933 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001934 */
1935 @Override
John Reck3ffc5ca2011-06-10 15:56:06 -07001936 public void bookmarkCurrentPage(boolean canBeAnEdit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001937 Intent i = new Intent(mActivity,
1938 AddBookmarkPage.class);
1939 WebView w = getCurrentTopWebView();
1940 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1941 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1942 String touchIconUrl = w.getTouchIconUrl();
1943 if (touchIconUrl != null) {
1944 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1945 WebSettings settings = w.getSettings();
1946 if (settings != null) {
1947 i.putExtra(AddBookmarkPage.USER_AGENT,
1948 settings.getUserAgentString());
1949 }
1950 }
1951 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1952 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1953 getDesiredThumbnailHeight(mActivity)));
1954 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001955 if (canBeAnEdit) {
1956 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1957 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001958 // Put the dialog at the upper right of the screen, covering the
1959 // star on the title bar.
1960 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1961 mActivity.startActivity(i);
1962 }
1963
1964 // file chooser
1965 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1966 mUploadHandler = new UploadHandler(this);
1967 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1968 }
1969
1970 // thumbnails
1971
1972 /**
1973 * Return the desired width for thumbnail screenshots, which are stored in
1974 * the database, and used on the bookmarks screen.
1975 * @param context Context for finding out the density of the screen.
1976 * @return desired width for thumbnail screenshot.
1977 */
1978 static int getDesiredThumbnailWidth(Context context) {
1979 return context.getResources().getDimensionPixelOffset(
1980 R.dimen.bookmarkThumbnailWidth);
1981 }
1982
1983 /**
1984 * Return the desired height for thumbnail screenshots, which are stored in
1985 * the database, and used on the bookmarks screen.
1986 * @param context Context for finding out the density of the screen.
1987 * @return desired height for thumbnail screenshot.
1988 */
1989 static int getDesiredThumbnailHeight(Context context) {
1990 return context.getResources().getDimensionPixelOffset(
1991 R.dimen.bookmarkThumbnailHeight);
1992 }
1993
Michael Kolb1acef692011-03-08 14:12:06 -08001994 static Bitmap createScreenshot(Tab tab, int width, int height) {
1995 if ((tab != null) && (tab.getWebView() != null)) {
1996 return createScreenshot(tab.getWebView(), width, height);
1997 }
1998 return null;
1999 }
2000
Michael Kolb8233fac2010-10-26 16:08:53 -07002001 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08002002 // We render to a bitmap 2x the desired size so that we can then
2003 // re-scale it with filtering since canvas.scale doesn't filter
2004 // This helps reduce aliasing at the cost of being slightly blurry
2005 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07002006 Picture thumbnail = view.capturePicture();
2007 if (thumbnail == null) {
2008 return null;
2009 }
John Reck5c6ac2f2011-01-05 10:18:03 -08002010 width *= filter_scale;
2011 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07002012 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
2013 Canvas canvas = new Canvas(bm);
2014 // May need to tweak these values to determine what is the
2015 // best scale factor
2016 int thumbnailWidth = thumbnail.getWidth();
2017 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08002018 float scaleFactor = 1.0f;
Michael Kolbeb95db42011-03-03 10:38:40 -08002019 if (thumbnailWidth > 0 && thumbnailHeight > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08002020 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07002021 } else {
2022 return null;
2023 }
John Reckfe49ab42010-11-16 17:09:37 -08002024
Michael Kolbeb95db42011-03-03 10:38:40 -08002025 float scaleFactorY = (float) height / (float)thumbnailHeight;
2026 if (scaleFactorY > scaleFactor) {
2027 // The picture is narrower than the requested AR
2028 // Center the thumnail and crop the sides
2029 scaleFactor = scaleFactorY;
John Reckfe49ab42010-11-16 17:09:37 -08002030 float wx = (thumbnailWidth * scaleFactor) - width;
2031 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07002032 }
2033
John Reckfe49ab42010-11-16 17:09:37 -08002034 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07002035
2036 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08002037 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
2038 height / filter_scale, true);
2039 bm.recycle();
2040 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07002041 }
2042
John Reck34ef2672011-02-10 11:30:55 -08002043 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002044 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07002045 // FIXME: Would like to make sure there is actually something to
2046 // draw, but the API for that (WebViewCore.pictureReady()) is not
2047 // currently accessible here.
2048
John Reck34ef2672011-02-10 11:30:55 -08002049 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08002050 if (view == null) {
2051 // Tab was destroyed
2052 return;
2053 }
John Reck34ef2672011-02-10 11:30:55 -08002054 final String url = tab.getUrl();
2055 final String originalUrl = view.getOriginalUrl();
2056
2057 if (TextUtils.isEmpty(url)) {
2058 return;
2059 }
2060
2061 // Only update thumbnails for web urls (http(s)://), not for
2062 // about:, javascript:, data:, etc...
2063 // Unless it is a bookmarked site, then always update
2064 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2065 return;
2066 }
2067
Michael Kolb8233fac2010-10-26 16:08:53 -07002068 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2069 getDesiredThumbnailHeight(mActivity));
2070 if (bm == null) {
2071 return;
2072 }
2073
2074 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002075 new AsyncTask<Void, Void, Void>() {
2076 @Override
2077 protected Void doInBackground(Void... unused) {
2078 Cursor cursor = null;
2079 try {
2080 // TODO: Clean this up
2081 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2082 if (cursor != null && cursor.moveToFirst()) {
2083 final ByteArrayOutputStream os =
2084 new ByteArrayOutputStream();
2085 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002086
John Reck34ef2672011-02-10 11:30:55 -08002087 ContentValues values = new ContentValues();
2088 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002089
John Reck34ef2672011-02-10 11:30:55 -08002090 do {
John Reck617fd832011-02-16 14:35:59 -08002091 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002092 cr.update(Images.CONTENT_URI, values, null, null);
2093 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002094 }
John Reck34ef2672011-02-10 11:30:55 -08002095 } catch (IllegalStateException e) {
2096 // Ignore
2097 } finally {
2098 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002099 }
John Reck34ef2672011-02-10 11:30:55 -08002100 return null;
2101 }
2102 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002103 }
2104
2105 private class Copy implements OnMenuItemClickListener {
2106 private CharSequence mText;
2107
2108 public boolean onMenuItemClick(MenuItem item) {
2109 copy(mText);
2110 return true;
2111 }
2112
2113 public Copy(CharSequence toCopy) {
2114 mText = toCopy;
2115 }
2116 }
2117
Leon Scroggins63c02662010-11-18 15:16:27 -05002118 private static class Download implements OnMenuItemClickListener {
2119 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002120 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002121 private boolean mPrivateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002122
2123 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002124 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002125 null, null, mPrivateBrowsing);
Michael Kolb8233fac2010-10-26 16:08:53 -07002126 return true;
2127 }
2128
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002129 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002130 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002131 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002132 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002133 }
2134 }
2135
Cary Clark8974d282010-11-22 10:46:05 -05002136 private static class SelectText implements OnMenuItemClickListener {
2137 private WebView mWebView;
2138
2139 public boolean onMenuItemClick(MenuItem item) {
2140 if (mWebView != null) {
2141 return mWebView.selectText();
2142 }
2143 return false;
2144 }
2145
2146 public SelectText(WebView webView) {
2147 mWebView = webView;
2148 }
2149
2150 }
2151
Michael Kolb8233fac2010-10-26 16:08:53 -07002152 /********************** TODO: UI stuff *****************************/
2153
2154 // these methods have been copied, they still need to be cleaned up
2155
2156 /****************** tabs ***************************************************/
2157
2158 // basic tab interactions:
2159
2160 // it is assumed that tabcontrol already knows about the tab
2161 protected void addTab(Tab tab) {
2162 mUi.addTab(tab);
2163 }
2164
2165 protected void removeTab(Tab tab) {
2166 mUi.removeTab(tab);
2167 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002168 mCrashRecoveryHandler.backupState();
John Reckd8c74522011-06-14 08:45:00 -07002169 if (tab.isSnapshot()) {
2170 SnapshotTab st = (SnapshotTab) tab;
2171 final Uri uri = ContentUris.withAppendedId(
2172 Snapshots.CONTENT_URI, st.getSnapshotId());
2173 final ContentResolver cr = mActivity.getContentResolver();
2174 new Thread() {
2175 @Override
2176 public void run() {
2177 cr.delete(uri, null, null);
2178 }
2179 }.start();
2180 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002181 }
2182
Michael Kolbf2055602011-04-09 17:20:03 -07002183 @Override
2184 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002185 // monkey protection against delayed start
2186 if (tab != null) {
2187 mTabControl.setCurrentTab(tab);
2188 // the tab is guaranteed to have a webview after setCurrentTab
2189 mUi.setActiveTab(tab);
2190 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002191 }
2192
2193 protected void closeEmptyChildTab() {
2194 Tab current = mTabControl.getCurrentTab();
2195 if (current != null
2196 && current.getWebView().copyBackForwardList().getSize() == 0) {
Michael Kolbc831b632011-05-11 09:30:34 -07002197 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002198 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002199 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002200 closeTab(current);
2201 }
2202 }
2203 }
2204
John Reck26b18322011-06-21 13:08:58 -07002205 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002206 // Dismiss the subwindow if applicable.
2207 dismissSubWindow(appTab);
2208 // Since we might kill the WebView, remove it from the
2209 // content view first.
2210 mUi.detachTab(appTab);
2211 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002212 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002213 // TODO: analyze why the remove and add are necessary
2214 mUi.attachTab(appTab);
2215 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002216 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002217 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002218 } else {
2219 // If the tab was the current tab, we have to attach
2220 // it to the view system again.
2221 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002222 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002223 }
2224 }
2225
2226 // Remove the sub window if it exists. Also called by TabControl when the
2227 // user clicks the 'X' to dismiss a sub window.
2228 public void dismissSubWindow(Tab tab) {
2229 removeSubWindow(tab);
2230 // dismiss the subwindow. This will destroy the WebView.
2231 tab.dismissSubWindow();
2232 getCurrentTopWebView().requestFocus();
2233 }
2234
2235 @Override
2236 public void removeSubWindow(Tab t) {
2237 if (t.getSubWebView() != null) {
2238 mUi.removeSubWindow(t.getSubViewContainer());
2239 }
2240 }
2241
2242 @Override
2243 public void attachSubWindow(Tab tab) {
2244 if (tab.getSubWebView() != null) {
2245 mUi.attachSubWindow(tab.getSubViewContainer());
2246 getCurrentTopWebView().requestFocus();
2247 }
2248 }
2249
Michael Kolb7bcafde2011-05-09 13:55:59 -07002250 // open a non inconito tab with the given url data
2251 // and set as active tab
2252 public Tab openTab(UrlData urlData) {
Michael Kolb14612442011-06-24 13:06:29 -07002253 if (urlData.isPreloaded()) {
2254 Tab tab = urlData.getPreloadedTab();
2255 tab.getWebView().clearHistory();
2256 mTabControl.addPreloadedTab(tab);
2257 setActiveTab(tab);
2258 return tab;
2259 } else {
2260 Tab tab = createNewTab(false, true, true);
2261 if ((tab != null) && !urlData.isEmpty()) {
2262 loadUrlDataIn(tab, urlData);
2263 }
2264 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002265 }
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 Reckd8c74522011-06-14 08:45:00 -07002329 private SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2330 SnapshotTab tab = mTabControl.createSnapshotTab(snapshotId);
2331 addTab(tab);
2332 if (setActive) {
2333 setActiveTab(tab);
2334 }
2335 return tab;
2336 }
2337
Michael Kolb8233fac2010-10-26 16:08:53 -07002338 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002339 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002340 * @return boolean True if we successfully switched to a different tab. If
2341 * the indexth tab is null, or if that tab is the same as
2342 * the current one, return false.
2343 */
2344 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002345 public boolean switchToTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002346 // hide combo view if open
2347 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002348 Tab currentTab = mTabControl.getCurrentTab();
2349 if (tab == null || tab == currentTab) {
2350 return false;
2351 }
2352 setActiveTab(tab);
2353 return true;
2354 }
2355
2356 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002357 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002358 // hide combo view if open
2359 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002360 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002361 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002362 return;
2363 }
Michael Kolbc831b632011-05-11 09:30:34 -07002364 final Tab current = mTabControl.getCurrentTab();
2365 final int pos = mTabControl.getCurrentPosition();
2366 Tab newTab = current.getParent();
2367 if (newTab == null) {
2368 newTab = mTabControl.getTab(pos + 1);
2369 if (newTab == null) {
2370 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002371 }
2372 }
Michael Kolbc831b632011-05-11 09:30:34 -07002373 if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002374 // Close window
2375 closeTab(current);
2376 }
2377 }
2378
2379 /**
2380 * Close the tab, remove its associated title bar, and adjust mTabControl's
2381 * current tab to a valid value.
2382 */
2383 @Override
2384 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002385 // hide combo view if open
2386 removeComboView();
Michael Kolb2d59c322011-01-25 13:18:55 -08002387 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002388 }
2389
Michael Kolb8233fac2010-10-26 16:08:53 -07002390 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07002391 protected void loadUrlFromContext(String url) {
2392 Tab tab = getCurrentTab();
2393 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002394 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07002395 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002396 url = UrlUtils.smartUrlFilter(url);
2397 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07002398 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07002399 }
2400 }
2401 }
2402
2403 /**
2404 * Load the URL into the given WebView and update the title bar
2405 * to reflect the new load. Call this instead of WebView.loadUrl
2406 * directly.
2407 * @param view The WebView used to load url.
2408 * @param url The URL to load.
2409 */
John Reck26b18322011-06-21 13:08:58 -07002410 protected void loadUrl(Tab tab, String url) {
2411 loadUrl(tab, url, null);
2412 }
2413
2414 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
2415 if (tab != null) {
2416 dismissSubWindow(tab);
2417 tab.loadUrl(url, headers);
2418 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002419 }
2420
2421 /**
2422 * Load UrlData into a Tab and update the title bar to reflect the new
2423 * load. Call this instead of UrlData.loadIn directly.
2424 * @param t The Tab used to load.
2425 * @param data The UrlData being loaded.
2426 */
2427 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07002428 if (data != null) {
2429 if (data.mVoiceIntent != null) {
2430 t.activateVoiceSearchMode(data.mVoiceIntent);
Michael Kolb14612442011-06-24 13:06:29 -07002431 } else if (data.isPreloaded()) {
2432 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07002433 } else {
2434 loadUrl(t, data.mUrl, data.mHeaders);
2435 }
2436 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002437 }
2438
John Reck30c714c2010-12-16 17:30:34 -08002439 @Override
2440 public void onUserCanceledSsl(Tab tab) {
2441 WebView web = tab.getWebView();
2442 // TODO: Figure out the "right" behavior
2443 if (web.canGoBack()) {
2444 web.goBack();
2445 } else {
2446 web.loadUrl(mSettings.getHomePage());
2447 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002448 }
2449
2450 void goBackOnePageOrQuit() {
2451 Tab current = mTabControl.getCurrentTab();
2452 if (current == null) {
2453 /*
2454 * Instead of finishing the activity, simply push this to the back
2455 * of the stack and let ActivityManager to choose the foreground
2456 * activity. As BrowserActivity is singleTask, it will be always the
2457 * root of the task. So we can use either true or false for
2458 * moveTaskToBack().
2459 */
2460 mActivity.moveTaskToBack(true);
2461 return;
2462 }
2463 WebView w = current.getWebView();
2464 if (w.canGoBack()) {
2465 w.goBack();
2466 } else {
2467 // Check to see if we are closing a window that was created by
2468 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002469 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002470 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002471 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002472 // Now we close the other tab
2473 closeTab(current);
2474 } else {
Michael Kolb8233fac2010-10-26 16:08:53 -07002475 /*
2476 * Instead of finishing the activity, simply push this to the back
2477 * of the stack and let ActivityManager to choose the foreground
2478 * activity. As BrowserActivity is singleTask, it will be always the
2479 * root of the task. So we can use either true or false for
2480 * moveTaskToBack().
2481 */
2482 mActivity.moveTaskToBack(true);
2483 }
2484 }
2485 }
2486
2487 /**
2488 * Feed the previously stored results strings to the BrowserProvider so that
2489 * the SearchDialog will show them instead of the standard searches.
2490 * @param result String to show on the editable line of the SearchDialog.
2491 */
2492 @Override
2493 public void showVoiceSearchResults(String result) {
2494 ContentProviderClient client = mActivity.getContentResolver()
2495 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2496 ContentProvider prov = client.getLocalContentProvider();
2497 BrowserProvider bp = (BrowserProvider) prov;
2498 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2499 client.release();
2500
2501 Bundle bundle = createGoogleSearchSourceBundle(
2502 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2503 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2504 startSearch(result, false, bundle, false);
2505 }
2506
2507 private void startSearch(String initialQuery, boolean selectInitialQuery,
2508 Bundle appSearchData, boolean globalSearch) {
2509 if (appSearchData == null) {
2510 appSearchData = createGoogleSearchSourceBundle(
2511 GOOGLE_SEARCH_SOURCE_TYPE);
2512 }
2513
2514 SearchEngine searchEngine = mSettings.getSearchEngine();
2515 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2516 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2517 }
2518 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2519 globalSearch);
2520 }
2521
2522 private Bundle createGoogleSearchSourceBundle(String source) {
2523 Bundle bundle = new Bundle();
2524 bundle.putString(Search.SOURCE, source);
2525 return bundle;
2526 }
2527
2528 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002529 * helper method for key handler
2530 * returns the current tab if it can't advance
2531 */
Michael Kolbc831b632011-05-11 09:30:34 -07002532 private Tab getNextTab() {
2533 return mTabControl.getTab(Math.min(mTabControl.getTabCount() - 1,
2534 mTabControl.getCurrentPosition() + 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002535 }
2536
2537 /**
2538 * helper method for key handler
2539 * returns the current tab if it can't advance
2540 */
Michael Kolbc831b632011-05-11 09:30:34 -07002541 private Tab getPrevTab() {
2542 return mTabControl.getTab(Math.max(0,
2543 mTabControl.getCurrentPosition() - 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002544 }
2545
2546 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002547 * handle key events in browser
2548 *
2549 * @param keyCode
2550 * @param event
2551 * @return true if handled, false to pass to super
2552 */
2553 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002554 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002555 // Even if MENU is already held down, we need to call to super to open
2556 // the IME on long press.
Michael Kolb2814a362011-05-19 15:49:41 -07002557 if (KeyEvent.KEYCODE_MENU == keyCode) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002558 if (mOptionsMenuHandler != null) {
2559 return false;
2560 } else {
2561 event.startTracking();
2562 return true;
2563 }
Michael Kolb2814a362011-05-19 15:49:41 -07002564 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002565 if (!noModifiers
2566 && ((KeyEvent.KEYCODE_MENU == keyCode)
2567 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2568 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002569 mMenuIsDown = true;
2570 return false;
2571 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002572
Cary Clark8ff8c662010-12-29 15:03:05 -05002573 WebView webView = getCurrentTopWebView();
2574 if (webView == null) return false;
2575
Cary Clark160bbb92011-01-10 11:17:07 -05002576 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2577 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002578
Michael Kolb8233fac2010-10-26 16:08:53 -07002579 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002580 case KeyEvent.KEYCODE_TAB:
2581 if (event.isCtrlPressed()) {
2582 if (event.isShiftPressed()) {
2583 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002584 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002585 } else {
2586 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002587 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002588 }
2589 return true;
2590 }
2591 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002592 case KeyEvent.KEYCODE_SPACE:
2593 // WebView/WebTextView handle the keys in the KeyDown. As
2594 // the Activity's shortcut keys are only handled when WebView
2595 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002596 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002597 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002598 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002599 pageDown();
2600 }
2601 return true;
2602 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002603 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002604 event.startTracking();
2605 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002606 case KeyEvent.KEYCODE_DPAD_LEFT:
2607 if (ctrl) {
2608 webView.goBack();
2609 return true;
2610 }
2611 break;
2612 case KeyEvent.KEYCODE_DPAD_RIGHT:
2613 if (ctrl) {
2614 webView.goForward();
2615 return true;
2616 }
2617 break;
2618 case KeyEvent.KEYCODE_A:
2619 if (ctrl) {
2620 webView.selectAll();
2621 return true;
2622 }
2623 break;
Michael Kolba4183062011-01-16 10:43:21 -08002624// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002625 case KeyEvent.KEYCODE_C:
2626 if (ctrl) {
2627 webView.copySelection();
2628 return true;
2629 }
2630 break;
Michael Kolba4183062011-01-16 10:43:21 -08002631// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002632// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002633// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002634// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002635// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002636// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002637// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002638// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002639// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002640// case KeyEvent.KEYCODE_M: // unused
2641// case KeyEvent.KEYCODE_N: // in Chrome: new window
2642// case KeyEvent.KEYCODE_O: // in Chrome: open file
2643// case KeyEvent.KEYCODE_P: // in Chrome: print page
2644// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002645// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002646// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2647 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002648 // we can't use the ctrl/shift flags, they check for
2649 // exclusive use of a modifier
2650 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002651 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002652 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002653 } else {
2654 openTabToHomePage();
2655 }
2656 return true;
2657 }
2658 break;
2659// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2660// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb1a2eba42011-03-16 16:42:49 -07002661 case KeyEvent.KEYCODE_W: // in Chrome: close tab
2662 if (ctrl) {
2663 closeCurrentTab();
2664 return true;
2665 }
2666 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002667// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2668// case KeyEvent.KEYCODE_Y: // unused
2669// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002670 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002671 // it is a regular key and webview is not null
2672 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002673 }
2674
John Recke6bf4ab2011-02-24 15:48:05 -08002675 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2676 switch(keyCode) {
2677 case KeyEvent.KEYCODE_BACK:
2678 if (mUi.showsWeb()) {
2679 bookmarksOrHistoryPicker(true);
2680 return true;
2681 }
2682 break;
2683 }
2684 return false;
2685 }
2686
Michael Kolb8233fac2010-10-26 16:08:53 -07002687 boolean onKeyUp(int keyCode, KeyEvent event) {
Michael Kolb2814a362011-05-19 15:49:41 -07002688 if (KeyEvent.KEYCODE_MENU == keyCode) {
2689 mMenuIsDown = false;
2690 if (event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002691 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002692 }
2693 }
Cary Clark160bbb92011-01-10 11:17:07 -05002694 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002695 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002696 case KeyEvent.KEYCODE_BACK:
2697 if (event.isTracking() && !event.isCanceled()) {
2698 onBackKey();
2699 return true;
2700 }
2701 break;
2702 }
2703 return false;
2704 }
2705
2706 public boolean isMenuDown() {
2707 return mMenuIsDown;
2708 }
2709
Ben Murdoch8029a772010-11-16 11:58:21 +00002710 public void setupAutoFill(Message message) {
2711 // Open the settings activity at the AutoFill profile fragment so that
2712 // the user can create a new profile. When they return, we will dispatch
2713 // the message so that we can autofill the form using their new profile.
2714 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2715 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2716 AutoFillSettingsFragment.class.getName());
2717 mAutoFillSetupMessage = message;
2718 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2719 }
John Reckb3417f02011-01-14 11:01:05 -08002720
2721 @Override
2722 public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
2723 mOptionsMenuHandler = handler;
2724 }
2725
2726 @Override
2727 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
2728 if (mOptionsMenuHandler == handler) {
2729 mOptionsMenuHandler = null;
2730 }
2731 }
2732
Narayan Kamath5119edd2011-02-23 15:49:17 +00002733 @Override
2734 public void registerDropdownChangeListener(DropdownChangeListener d) {
2735 mUi.registerDropdownChangeListener(d);
2736 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002737}