blob: 447e61b2d97eaca3227f9348fc6ad7fd2472611f [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 Kolb8233fac2010-10-26 16:08:53 -0700232
233 mUrlHandler = new UrlHandler(this);
234 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700235 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
Martijn Coenenb2f93552011-06-14 10:48:35 +0200236 mNfcHandler = new NfcHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700237
238 PowerManager pm = (PowerManager) mActivity
239 .getSystemService(Context.POWER_SERVICE);
240 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
241
242 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500243 mBookmarksObserver = new ContentObserver(mHandler) {
244 @Override
245 public void onChange(boolean selfChange) {
246 int size = mTabControl.getTabCount();
247 for (int i = 0; i < size; i++) {
248 mTabControl.getTab(i).updateBookmarkedStatus();
249 }
250 }
251
252 };
253 browser.getContentResolver().registerContentObserver(
254 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700255
256 mNetworkHandler = new NetworkStateHandler(mActivity, this);
257 // Start watching the default geolocation permissions
258 mSystemAllowGeolocationOrigins =
259 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
260 mSystemAllowGeolocationOrigins.start();
261
262 retainIconsOnStartup();
263 }
264
Patrick Scott7d50a932011-02-04 09:27:26 -0500265 void start(final Bundle icicle, final Intent intent) {
Guang Zhu9e78f512011-05-04 11:45:11 -0700266 boolean noCrashRecovery = intent.getBooleanExtra(NO_CRASH_RECOVERY, false);
267 if (icicle != null || noCrashRecovery) {
John Reck847b5322011-04-14 17:02:18 -0700268 doStart(icicle, intent);
269 } else {
270 mCrashRecoveryHandler.startRecovery(intent);
271 }
272 }
273
274 void doStart(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700275 // Unless the last browser usage was within 24 hours, destroy any
276 // remaining incognito tabs.
277
278 Calendar lastActiveDate = icicle != null ?
279 (Calendar) icicle.getSerializable("lastActiveDate") : null;
280 Calendar today = Calendar.getInstance();
281 Calendar yesterday = Calendar.getInstance();
282 yesterday.add(Calendar.DATE, -1);
283
Patrick Scott7d50a932011-02-04 09:27:26 -0500284 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700285 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800286 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700287
Patrick Scott7d50a932011-02-04 09:27:26 -0500288 // Find out if we will restore any state and remember the tab.
Michael Kolbc831b632011-05-11 09:30:34 -0700289 final long currentTabId =
Patrick Scott7d50a932011-02-04 09:27:26 -0500290 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000291
Michael Kolbc831b632011-05-11 09:30:34 -0700292 if (currentTabId == -1) {
Patrick Scott7d50a932011-02-04 09:27:26 -0500293 // Not able to restore so we go ahead and clear session cookies. We
294 // must do this before trying to login the user as we don't want to
295 // clear any session cookies set during login.
296 CookieManager.getInstance().removeSessionCookie();
297 }
298
Patrick Scottd43e75a2011-03-14 14:47:23 -0400299 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500300 new Runnable() {
301 @Override public void run() {
Michael Kolbc831b632011-05-11 09:30:34 -0700302 onPreloginFinished(icicle, intent, currentTabId, restoreIncognitoTabs);
Patrick Scott7d50a932011-02-04 09:27:26 -0500303 }
304 });
305 }
306
Michael Kolbc831b632011-05-11 09:30:34 -0700307 private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId,
Patrick Scott7d50a932011-02-04 09:27:26 -0500308 boolean restoreIncognitoTabs) {
Michael Kolbc831b632011-05-11 09:30:34 -0700309 if (currentTabId == -1) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700310 final Bundle extra = intent.getExtras();
311 // Create an initial tab.
312 // If the intent is ACTION_VIEW and data is not null, the Browser is
313 // invoked to view the content by another application. In this case,
314 // the tab will be close when exit.
315 UrlData urlData = mIntentHandler.getUrlDataFromIntent(intent);
Michael Kolb7bcafde2011-05-09 13:55:59 -0700316 Tab t = null;
317 if (urlData.isEmpty()) {
318 t = openTabToHomePage();
319 } else {
320 t = openTab(urlData);
321 }
322 if (t != null) {
323 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
324 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700325 WebView webView = t.getWebView();
326 if (extra != null) {
327 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
328 if (scale > 0 && scale <= 1000) {
329 webView.setInitialScale(scale);
330 }
331 }
John Reckd8c74522011-06-14 08:45:00 -0700332 mTabControl.loadSnapshotTabs();
333 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700334 } else {
Michael Kolbc831b632011-05-11 09:30:34 -0700335 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
Patrick Scott7d50a932011-02-04 09:27:26 -0500336 mUi.needsRestoreAllTabs());
Michael Kolb1bf23132010-11-19 12:55:12 -0800337 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700338 // TabControl.restoreState() will create a new tab even if
339 // restoring the state fails.
340 setActiveTab(mTabControl.getCurrentTab());
John Reckdb22ec42011-06-29 11:31:24 -0700341 // Handle the intent
342 mIntentHandler.onNewIntent(intent);
Michael Kolb8233fac2010-10-26 16:08:53 -0700343 }
344 // clear up the thumbnail directory, which is no longer used;
345 // ideally this should only be run once after an upgrade from
346 // a previous version of the browser
347 new ClearThumbnails().execute(mTabControl.getThumbnailDir()
348 .listFiles());
349 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700350 String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb8233fac2010-10-26 16:08:53 -0700351 if (jsFlags.trim().length() != 0) {
352 getCurrentWebView().setJsFlags(jsFlags);
353 }
John Reck439c9a52010-12-14 10:04:39 -0800354 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
355 bookmarksOrHistoryPicker(false);
356 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700357 }
358
359 void setWebViewFactory(WebViewFactory factory) {
360 mFactory = factory;
361 }
362
Michael Kolb1514bb72010-11-22 09:11:48 -0800363 @Override
364 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700365 return mFactory;
366 }
367
368 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800369 public void onSetWebView(Tab tab, WebView view) {
370 mUi.onSetWebView(tab, view);
371 }
372
373 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800374 public void createSubWindow(Tab tab) {
375 endActionMode();
376 WebView mainView = tab.getWebView();
377 WebView subView = mFactory.createWebView((mainView == null)
378 ? false
379 : mainView.isPrivateBrowsingEnabled());
380 mUi.createSubWindow(tab, subView);
381 }
382
383 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700384 public Activity getActivity() {
385 return mActivity;
386 }
387
388 void setUi(UI ui) {
389 mUi = ui;
390 }
391
392 BrowserSettings getSettings() {
393 return mSettings;
394 }
395
396 IntentHandler getIntentHandler() {
397 return mIntentHandler;
398 }
399
400 @Override
401 public UI getUi() {
402 return mUi;
403 }
404
405 int getMaxTabs() {
406 return mActivity.getResources().getInteger(R.integer.max_tabs);
407 }
408
409 @Override
410 public TabControl getTabControl() {
411 return mTabControl;
412 }
413
Michael Kolb1bf23132010-11-19 12:55:12 -0800414 @Override
415 public List<Tab> getTabs() {
416 return mTabControl.getTabs();
417 }
418
Michael Kolb8233fac2010-10-26 16:08:53 -0700419 // Open the icon database and retain all the icons for visited sites.
Ben Murdoch9446b932010-11-25 16:20:14 +0000420 // This is done on a background thread so as not to stall startup.
Michael Kolb8233fac2010-10-26 16:08:53 -0700421 private void retainIconsOnStartup() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000422 // WebIconDatabase needs to be retrieved on the UI thread so that if
423 // it has not been created successfully yet the Handler is started on the
424 // UI thread.
425 new RetainIconsOnStartupTask(WebIconDatabase.getInstance()).execute();
426 }
427
428 private class RetainIconsOnStartupTask extends AsyncTask<Void, Void, Void> {
429 private WebIconDatabase mDb;
430
431 public RetainIconsOnStartupTask(WebIconDatabase db) {
432 mDb = db;
433 }
434
John Recka00cbbd2010-12-16 12:38:19 -0800435 @Override
Ben Murdoch9446b932010-11-25 16:20:14 +0000436 protected Void doInBackground(Void... unused) {
437 mDb.open(mActivity.getDir("icons", 0).getPath());
438 Cursor c = null;
439 try {
440 c = Browser.getAllBookmarks(mActivity.getContentResolver());
441 if (c.moveToFirst()) {
442 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
443 do {
444 String url = c.getString(urlIndex);
445 mDb.retainIconForPageUrl(url);
446 } while (c.moveToNext());
447 }
448 } catch (IllegalStateException e) {
449 Log.e(LOGTAG, "retainIconsOnStartup", e);
450 } finally {
451 if (c != null) c.close();
Michael Kolb8233fac2010-10-26 16:08:53 -0700452 }
Ben Murdoch9446b932010-11-25 16:20:14 +0000453
454 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700455 }
456 }
457
458 private void startHandler() {
459 mHandler = new Handler() {
460
461 @Override
462 public void handleMessage(Message msg) {
463 switch (msg.what) {
464 case OPEN_BOOKMARKS:
465 bookmarksOrHistoryPicker(false);
466 break;
467 case FOCUS_NODE_HREF:
468 {
469 String url = (String) msg.getData().get("url");
470 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500471 String src = (String) msg.getData().get("src");
472 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700473 if (TextUtils.isEmpty(url)) {
474 break;
475 }
476 HashMap focusNodeMap = (HashMap) msg.obj;
477 WebView view = (WebView) focusNodeMap.get("webview");
478 // Only apply the action if the top window did not change.
479 if (getCurrentTopWebView() != view) {
480 break;
481 }
482 switch (msg.arg1) {
483 case R.id.open_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700484 loadUrlFromContext(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700485 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500486 case R.id.view_image_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700487 loadUrlFromContext(src);
Cary Clark043c2d62010-12-15 11:19:39 -0500488 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500489 case R.id.open_newtab_context_menu_id:
490 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -0700491 openTab(url, parent,
492 !mSettings.openInBackground(), true);
Leon Scroggins026f2542010-11-22 13:26:12 -0500493 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700494 case R.id.copy_link_context_menu_id:
495 copy(url);
496 break;
497 case R.id.save_link_context_menu_id:
498 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500499 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000500 mActivity, url, null, null, null,
501 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700502 break;
503 }
504 break;
505 }
506
507 case LOAD_URL:
John Reck26b18322011-06-21 13:08:58 -0700508 loadUrlFromContext((String) msg.obj);
Michael Kolb8233fac2010-10-26 16:08:53 -0700509 break;
510
511 case STOP_LOAD:
512 stopLoading();
513 break;
514
515 case RELEASE_WAKELOCK:
516 if (mWakeLock.isHeld()) {
517 mWakeLock.release();
518 // if we reach here, Browser should be still in the
519 // background loading after WAKELOCK_TIMEOUT (5-min).
520 // To avoid burning the battery, stop loading.
521 mTabControl.stopAllLoading();
522 }
523 break;
524
525 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800526 Tab tab = (Tab) msg.obj;
527 if (tab != null) {
528 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700529 }
530 break;
531 }
532 }
533 };
534
535 }
536
Martijn Coenenb2f93552011-06-14 10:48:35 +0200537
538 public Tab getCurrentTab() {
539 return mTabControl.getCurrentTab();
540 }
541
Michael Kolbba99c5d2010-11-29 14:57:41 -0800542 @Override
543 public void shareCurrentPage() {
544 shareCurrentPage(mTabControl.getCurrentTab());
545 }
546
547 private void shareCurrentPage(Tab tab) {
548 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800549 sharePage(mActivity, tab.getTitle(),
550 tab.getUrl(), tab.getFavicon(),
551 createScreenshot(tab.getWebView(),
552 getDesiredThumbnailWidth(mActivity),
553 getDesiredThumbnailHeight(mActivity)));
554 }
555 }
556
Michael Kolb8233fac2010-10-26 16:08:53 -0700557 /**
558 * Share a page, providing the title, url, favicon, and a screenshot. Uses
559 * an {@link Intent} to launch the Activity chooser.
560 * @param c Context used to launch a new Activity.
561 * @param title Title of the page. Stored in the Intent with
562 * {@link Intent#EXTRA_SUBJECT}
563 * @param url URL of the page. Stored in the Intent with
564 * {@link Intent#EXTRA_TEXT}
565 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
566 * with {@link Browser#EXTRA_SHARE_FAVICON}
567 * @param screenshot Bitmap of a screenshot of the page. Stored in the
568 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
569 */
570 static final void sharePage(Context c, String title, String url,
571 Bitmap favicon, Bitmap screenshot) {
572 Intent send = new Intent(Intent.ACTION_SEND);
573 send.setType("text/plain");
574 send.putExtra(Intent.EXTRA_TEXT, url);
575 send.putExtra(Intent.EXTRA_SUBJECT, title);
576 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
577 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
578 try {
579 c.startActivity(Intent.createChooser(send, c.getString(
580 R.string.choosertitle_sharevia)));
581 } catch(android.content.ActivityNotFoundException ex) {
582 // if no app handles it, do nothing
583 }
584 }
585
586 private void copy(CharSequence text) {
587 ClipboardManager cm = (ClipboardManager) mActivity
588 .getSystemService(Context.CLIPBOARD_SERVICE);
589 cm.setText(text);
590 }
591
592 // lifecycle
593
594 protected void onConfgurationChanged(Configuration config) {
595 mConfigChanged = true;
596 if (mPageDialogsHandler != null) {
597 mPageDialogsHandler.onConfigurationChanged(config);
598 }
599 mUi.onConfigurationChanged(config);
600 }
601
602 @Override
603 public void handleNewIntent(Intent intent) {
604 mIntentHandler.onNewIntent(intent);
605 }
606
607 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800608 if (mUi.isCustomViewShowing()) {
609 hideCustomView();
610 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700611 if (mActivityPaused) {
612 Log.e(LOGTAG, "BrowserActivity is already paused.");
613 return;
614 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700615 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800616 Tab tab = mTabControl.getCurrentTab();
617 if (tab != null) {
618 tab.pause();
619 if (!pauseWebViewTimers(tab)) {
620 mWakeLock.acquire();
621 mHandler.sendMessageDelayed(mHandler
622 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
623 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700624 }
625 mUi.onPause();
626 mNetworkHandler.onPause();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200627 mNfcHandler.onPause();
Michael Kolb8233fac2010-10-26 16:08:53 -0700628
629 WebView.disablePlatformNotifications();
John Reck378a4102011-06-09 16:23:01 -0700630 mCrashRecoveryHandler.backupState();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200631
Michael Kolb8233fac2010-10-26 16:08:53 -0700632 }
633
John Reckaed9c542011-05-27 16:08:53 -0700634 void onSaveInstanceState(Bundle outState, boolean saveImages) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700635 // the default implementation requires each view to have an id. As the
636 // browser handles the state itself and it doesn't use id for the views,
637 // don't call the default implementation. Otherwise it will trigger the
638 // warning like this, "couldn't save which view has focus because the
639 // focused view XXX has no id".
640
641 // Save all the tabs
John Reckaed9c542011-05-27 16:08:53 -0700642 mTabControl.saveState(outState, saveImages);
John Reck24f18262011-06-17 14:47:20 -0700643 if (!outState.isEmpty()) {
644 // Save time so that we know how old incognito tabs (if any) are.
645 outState.putSerializable("lastActiveDate", Calendar.getInstance());
646 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700647 }
648
649 void onResume() {
650 if (!mActivityPaused) {
651 Log.e(LOGTAG, "BrowserActivity is already resumed.");
652 return;
653 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700654 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800655 Tab current = mTabControl.getCurrentTab();
656 if (current != null) {
657 current.resume();
658 resumeWebViewTimers(current);
659 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700660 if (mWakeLock.isHeld()) {
661 mHandler.removeMessages(RELEASE_WAKELOCK);
662 mWakeLock.release();
663 }
Martijn Coenenb2f93552011-06-14 10:48:35 +0200664
Michael Kolb8233fac2010-10-26 16:08:53 -0700665 mUi.onResume();
666 mNetworkHandler.onResume();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200667 mNfcHandler.onResume();
Michael Kolb8233fac2010-10-26 16:08:53 -0700668 WebView.enablePlatformNotifications();
669 }
670
Michael Kolb70976932010-11-30 11:34:01 -0800671 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800672 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800673 * @param tab guaranteed non-null
674 */
675 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700676 boolean inLoad = tab.inPageLoad();
677 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
678 CookieSyncManager.getInstance().startSync();
679 WebView w = tab.getWebView();
680 if (w != null) {
681 w.resumeTimers();
682 }
683 }
684 }
685
Michael Kolb70976932010-11-30 11:34:01 -0800686 /**
687 * Pause all WebView timers using the WebView of the given tab
688 * @param tab
689 * @return true if the timers are paused or tab is null
690 */
691 private boolean pauseWebViewTimers(Tab tab) {
692 if (tab == null) {
693 return true;
694 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700695 CookieSyncManager.getInstance().stopSync();
696 WebView w = getCurrentWebView();
697 if (w != null) {
698 w.pauseTimers();
699 }
700 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700701 }
Michael Kolb70976932010-11-30 11:34:01 -0800702 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700703 }
704
705 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800706 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700707 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
708 mUploadHandler = null;
709 }
710 if (mTabControl == null) return;
711 mUi.onDestroy();
712 // Remove the current tab and sub window
713 Tab t = mTabControl.getCurrentTab();
714 if (t != null) {
715 dismissSubWindow(t);
716 removeTab(t);
717 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500718 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700719 // Destroy all the tabs
720 mTabControl.destroy();
721 WebIconDatabase.getInstance().close();
722 // Stop watching the default geolocation permissions
723 mSystemAllowGeolocationOrigins.stop();
724 mSystemAllowGeolocationOrigins = null;
725 }
726
727 protected boolean isActivityPaused() {
728 return mActivityPaused;
729 }
730
731 protected void onLowMemory() {
732 mTabControl.freeMemory();
733 }
734
735 @Override
736 public boolean shouldShowErrorConsole() {
737 return mShouldShowErrorConsole;
738 }
739
740 protected void setShouldShowErrorConsole(boolean show) {
741 if (show == mShouldShowErrorConsole) {
742 // Nothing to do.
743 return;
744 }
745 mShouldShowErrorConsole = show;
746 Tab t = mTabControl.getCurrentTab();
747 if (t == null) {
748 // There is no current tab so we cannot toggle the error console
749 return;
750 }
751 mUi.setShouldShowErrorConsole(t, show);
752 }
753
754 @Override
755 public void stopLoading() {
756 mLoadStopped = true;
757 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700758 WebView w = getCurrentTopWebView();
759 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700760 mUi.onPageStopped(tab);
761 }
762
763 boolean didUserStopLoading() {
764 return mLoadStopped;
765 }
766
767 // WebViewController
768
769 @Override
John Reck324d4402011-01-11 16:56:42 -0800770 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700771
772 // We've started to load a new page. If there was a pending message
773 // to save a screenshot then we will now take the new page and save
774 // an incorrect screenshot. Therefore, remove any pending thumbnail
775 // messages from the queue.
776 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800777 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700778
779 // reset sync timer to avoid sync starts during loading a page
780 CookieSyncManager.getInstance().resetSync();
781
782 if (!mNetworkHandler.isNetworkUp()) {
783 view.setNetworkAvailable(false);
784 }
785
786 // when BrowserActivity just starts, onPageStarted may be called before
787 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
788 // to start the timer. As we won't switch tabs while an activity is in
789 // pause state, we can ensure calling resume and pause in pair.
790 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800791 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700792 }
793 mLoadStopped = false;
794 if (!mNetworkHandler.isNetworkUp()) {
795 mNetworkHandler.createAndShowNetworkDialog();
796 }
797 endActionMode();
798
John Reck30c714c2010-12-16 17:30:34 -0800799 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700800
John Reck324d4402011-01-11 16:56:42 -0800801 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700802 // update the bookmark database for favicon
803 maybeUpdateFavicon(tab, null, url, favicon);
804
805 Performance.tracePageStart(url);
806
807 // Performance probe
808 if (false) {
809 Performance.onPageStarted();
810 }
811
812 }
813
814 @Override
John Reck324d4402011-01-11 16:56:42 -0800815 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800816 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800817 if (!tab.isPrivateBrowsingEnabled()
John Reckd8c74522011-06-14 08:45:00 -0700818 && !TextUtils.isEmpty(tab.getUrl())
819 && !tab.isSnapshot()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700820 if (tab.inForeground() && !didUserStopLoading()
821 || !tab.inForeground()) {
822 // Only update the bookmark screenshot if the user did not
823 // cancel the load early.
824 mHandler.sendMessageDelayed(mHandler.obtainMessage(
John Reck34ef2672011-02-10 11:30:55 -0800825 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
Michael Kolb8233fac2010-10-26 16:08:53 -0700826 500);
827 }
828 }
829 // pause the WebView timer and release the wake lock if it is finished
830 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800831 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700832 if (mWakeLock.isHeld()) {
833 mHandler.removeMessages(RELEASE_WAKELOCK);
834 mWakeLock.release();
835 }
836 }
Martijn Coenenb2f93552011-06-14 10:48:35 +0200837
Michael Kolb8233fac2010-10-26 16:08:53 -0700838 // Performance probe
839 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800840 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700841 }
842
843 Performance.tracePageFinished();
844 }
845
846 @Override
John Reck30c714c2010-12-16 17:30:34 -0800847 public void onProgressChanged(Tab tab) {
848 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700849
850 if (newProgress == 100) {
851 CookieSyncManager.getInstance().sync();
852 // onProgressChanged() may continue to be called after the main
853 // frame has finished loading, as any remaining sub frames continue
854 // to load. We'll only get called once though with newProgress as
855 // 100 when everything is loaded. (onPageFinished is called once
856 // when the main frame completes loading regardless of the state of
857 // any sub frames so calls to onProgressChanges may continue after
858 // onPageFinished has executed)
859 if (mInLoad) {
860 mInLoad = false;
861 updateInLoadMenuItems(mCachedMenu);
862 }
863 } else {
864 if (!mInLoad) {
865 // onPageFinished may have already been called but a subframe is
866 // still loading and updating the progress. Reset mInLoad and
867 // update the menu items.
868 mInLoad = true;
869 updateInLoadMenuItems(mCachedMenu);
870 }
871 }
John Reck30c714c2010-12-16 17:30:34 -0800872 mUi.onProgressChanged(tab);
873 }
874
875 @Override
876 public void onUpdatedLockIcon(Tab tab) {
877 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700878 }
879
880 @Override
881 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800882 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800883 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800884 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700885 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
886 return;
887 }
888 // Update the title in the history database if not in private browsing mode
889 if (!tab.isPrivateBrowsingEnabled()) {
John Reck0ebd3ac2010-12-09 11:14:04 -0800890 mDataController.updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700891 }
892 }
893
894 @Override
895 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800896 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700897 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
898 }
899
900 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800901 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
902 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700903 }
904
905 @Override
906 public boolean shouldOverrideKeyEvent(KeyEvent event) {
907 if (mMenuIsDown) {
908 // only check shortcut key when MENU is held
909 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
910 event);
911 } else {
912 return false;
913 }
914 }
915
916 @Override
917 public void onUnhandledKeyEvent(KeyEvent event) {
918 if (!isActivityPaused()) {
919 if (event.getAction() == KeyEvent.ACTION_DOWN) {
920 mActivity.onKeyDown(event.getKeyCode(), event);
921 } else {
922 mActivity.onKeyUp(event.getKeyCode(), event);
923 }
924 }
925 }
926
927 @Override
John Reck324d4402011-01-11 16:56:42 -0800928 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700929 // Don't save anything in private browsing mode
930 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800931 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700932
John Reck324d4402011-01-11 16:56:42 -0800933 if (TextUtils.isEmpty(url)
934 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700935 return;
936 }
John Reck0ebd3ac2010-12-09 11:14:04 -0800937 mDataController.updateVisitedHistory(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700938 WebIconDatabase.getInstance().retainIconForPageUrl(url);
John Reck847b5322011-04-14 17:02:18 -0700939 if (!mActivityPaused) {
940 // Since we clear the state in onPause, don't backup the current
941 // state if we are already paused
942 mCrashRecoveryHandler.backupState();
943 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700944 }
945
946 @Override
947 public void getVisitedHistory(final ValueCallback<String[]> callback) {
948 AsyncTask<Void, Void, String[]> task =
949 new AsyncTask<Void, Void, String[]>() {
950 @Override
951 public String[] doInBackground(Void... unused) {
952 return Browser.getVisitedHistory(mActivity.getContentResolver());
953 }
954 @Override
955 public void onPostExecute(String[] result) {
956 callback.onReceiveValue(result);
957 }
958 };
959 task.execute();
960 }
961
962 @Override
963 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
964 final HttpAuthHandler handler, final String host,
965 final String realm) {
966 String username = null;
967 String password = null;
968
969 boolean reuseHttpAuthUsernamePassword
970 = handler.useHttpAuthUsernamePassword();
971
972 if (reuseHttpAuthUsernamePassword && view != null) {
973 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
974 if (credentials != null && credentials.length == 2) {
975 username = credentials[0];
976 password = credentials[1];
977 }
978 }
979
980 if (username != null && password != null) {
981 handler.proceed(username, password);
982 } else {
983 if (tab.inForeground()) {
984 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
985 } else {
986 handler.cancel();
987 }
988 }
989 }
990
991 @Override
992 public void onDownloadStart(Tab tab, String url, String userAgent,
993 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000994 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -0500995 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000996 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
997 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700998 // This Tab was opened for the sole purpose of downloading a
999 // file. Remove it.
1000 if (tab == mTabControl.getCurrentTab()) {
1001 // In this case, the Tab is still on top.
1002 goBackOnePageOrQuit();
1003 } else {
1004 // In this case, it is not.
1005 closeTab(tab);
1006 }
1007 }
1008 }
1009
1010 @Override
1011 public Bitmap getDefaultVideoPoster() {
1012 return mUi.getDefaultVideoPoster();
1013 }
1014
1015 @Override
1016 public View getVideoLoadingProgressView() {
1017 return mUi.getVideoLoadingProgressView();
1018 }
1019
1020 @Override
1021 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1022 SslError error) {
1023 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1024 }
1025
Patrick Scott92066772011-03-10 08:46:27 -05001026 @Override
1027 public void showAutoLogin(Tab tab) {
1028 assert tab.inForeground();
1029 // Update the title bar to show the auto-login request.
1030 mUi.showAutoLogin(tab);
1031 }
1032
1033 @Override
1034 public void hideAutoLogin(Tab tab) {
1035 assert tab.inForeground();
1036 mUi.hideAutoLogin(tab);
1037 }
1038
Michael Kolb8233fac2010-10-26 16:08:53 -07001039 // helper method
1040
1041 /*
1042 * Update the favorites icon if the private browsing isn't enabled and the
1043 * icon is valid.
1044 */
1045 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1046 final String url, Bitmap favicon) {
1047 if (favicon == null) {
1048 return;
1049 }
1050 if (!tab.isPrivateBrowsingEnabled()) {
1051 Bookmarks.updateFavicon(mActivity
1052 .getContentResolver(), originalUrl, url, favicon);
1053 }
1054 }
1055
Leon Scroggins4cd97792010-12-03 15:31:56 -05001056 @Override
1057 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001058 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001059 mUi.bookmarkedStatusHasChanged(tab);
1060 }
1061
Michael Kolb8233fac2010-10-26 16:08:53 -07001062 // end WebViewController
1063
1064 protected void pageUp() {
1065 getCurrentTopWebView().pageUp(false);
1066 }
1067
1068 protected void pageDown() {
1069 getCurrentTopWebView().pageDown(false);
1070 }
1071
1072 // callback from phone title bar
1073 public void editUrl() {
1074 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001075 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001076 }
1077
Michael Kolbcfa3af52010-12-14 10:36:11 -08001078 public void startVoiceSearch() {
1079 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1080 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1081 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1082 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1083 mActivity.getComponentName().flattenToString());
1084 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001085 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001086 mActivity.startActivity(intent);
1087 }
1088
Michael Kolb11d19782011-03-20 10:17:40 -07001089 @Override
1090 public void activateVoiceSearchMode(String title, List<String> results) {
1091 mUi.showVoiceTitleBar(title, results);
Michael Kolb8233fac2010-10-26 16:08:53 -07001092 }
1093
1094 public void revertVoiceSearchMode(Tab tab) {
1095 mUi.revertVoiceTitleBar(tab);
1096 }
1097
Michael Kolb736990c2011-03-20 10:01:20 -07001098 public boolean supportsVoiceSearch() {
John Reck35e9dd62011-04-25 09:01:54 -07001099 SearchEngine searchEngine = getSettings().getSearchEngine();
Michael Kolb736990c2011-03-20 10:01:20 -07001100 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1101 }
1102
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001103 public void showCustomView(Tab tab, View view, int requestedOrientation,
Michael Kolb8233fac2010-10-26 16:08:53 -07001104 WebChromeClient.CustomViewCallback callback) {
1105 if (tab.inForeground()) {
1106 if (mUi.isCustomViewShowing()) {
1107 callback.onCustomViewHidden();
1108 return;
1109 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001110 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001111 // Save the menu state and set it to empty while the custom
1112 // view is showing.
1113 mOldMenuState = mMenuState;
1114 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001115 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001116 }
1117 }
1118
1119 @Override
1120 public void hideCustomView() {
1121 if (mUi.isCustomViewShowing()) {
1122 mUi.onHideCustomView();
1123 // Reset the old menu state.
1124 mMenuState = mOldMenuState;
1125 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001126 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001127 }
1128 }
1129
1130 protected void onActivityResult(int requestCode, int resultCode,
1131 Intent intent) {
1132 if (getCurrentTopWebView() == null) return;
1133 switch (requestCode) {
1134 case PREFERENCES_PAGE:
1135 if (resultCode == Activity.RESULT_OK && intent != null) {
1136 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001137 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001138 mTabControl.removeParentChildRelationShips();
1139 }
1140 }
1141 break;
1142 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001143 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001144 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001145 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001146 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001147 case AUTOFILL_SETUP:
1148 // Determine whether a profile was actually set up or not
1149 // and if so, send the message back to the WebTextView to
1150 // fill the form with the new profile.
1151 if (getSettings().getAutoFillProfile() != null) {
1152 mAutoFillSetupMessage.sendToTarget();
1153 mAutoFillSetupMessage = null;
1154 }
1155 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001156 default:
1157 break;
1158 }
1159 getCurrentTopWebView().requestFocus();
1160 }
1161
1162 /**
1163 * Open the Go page.
1164 * @param startWithHistory If true, open starting on the history tab.
1165 * Otherwise, start with the bookmarks tab.
1166 */
1167 @Override
1168 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1169 if (mTabControl.getCurrentWebView() == null) {
1170 return;
1171 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001172 // clear action mode
1173 if (isInCustomActionMode()) {
1174 endActionMode();
1175 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001176 Bundle extras = new Bundle();
1177 // Disable opening in a new window if we have maxed out the windows
1178 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1179 !mTabControl.canCreateNewTab());
1180 mUi.showComboView(startWithHistory, extras);
1181 }
1182
1183 // combo view callbacks
1184
1185 /**
1186 * callback from ComboPage when clear history is requested
1187 */
1188 public void onRemoveParentChildRelationships() {
1189 mTabControl.removeParentChildRelationShips();
1190 }
1191
1192 /**
1193 * callback from ComboPage when bookmark/history selection
1194 */
1195 @Override
1196 public void onUrlSelected(String url, boolean newTab) {
1197 removeComboView();
1198 if (!TextUtils.isEmpty(url)) {
1199 if (newTab) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07001200 final Tab parent = mTabControl.getCurrentTab();
1201 openTab(url,
1202 (parent != null) && parent.isPrivateBrowsingEnabled(),
1203 !mSettings.openInBackground(),
1204 true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001205 } else {
1206 final Tab currentTab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07001207 loadUrl(currentTab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07001208 }
1209 }
1210 }
1211
1212 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07001213 * dismiss the ComboPage
1214 */
1215 @Override
1216 public void removeComboView() {
1217 mUi.hideComboView();
1218 }
1219
1220 // active tabs page handling
1221
1222 protected void showActiveTabsPage() {
1223 mMenuState = EMPTY_MENU;
1224 mUi.showActiveTabsPage();
1225 }
1226
1227 /**
1228 * Remove the active tabs page.
1229 * @param needToAttach If true, the active tabs page did not attach a tab
1230 * to the content view, so we need to do that here.
1231 */
1232 @Override
1233 public void removeActiveTabsPage(boolean needToAttach) {
1234 mMenuState = R.id.MAIN_MENU;
1235 mUi.removeActiveTabsPage();
1236 if (needToAttach) {
1237 setActiveTab(mTabControl.getCurrentTab());
1238 }
1239 getCurrentTopWebView().requestFocus();
1240 }
1241
1242 // key handling
1243 protected void onBackKey() {
1244 if (!mUi.onBackKey()) {
1245 WebView subwindow = mTabControl.getCurrentSubWindow();
1246 if (subwindow != null) {
1247 if (subwindow.canGoBack()) {
1248 subwindow.goBack();
1249 } else {
1250 dismissSubWindow(mTabControl.getCurrentTab());
1251 }
1252 } else {
1253 goBackOnePageOrQuit();
1254 }
1255 }
1256 }
1257
Michael Kolb4bd767d2011-05-27 11:33:55 -07001258 protected boolean onMenuKey() {
1259 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001260 }
1261
Michael Kolb8233fac2010-10-26 16:08:53 -07001262 // menu handling and state
1263 // TODO: maybe put into separate handler
1264
1265 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckb3417f02011-01-14 11:01:05 -08001266 if (mOptionsMenuHandler != null) {
1267 return mOptionsMenuHandler.onCreateOptionsMenu(menu);
1268 }
1269
John Reckd73c5a22010-12-22 10:22:50 -08001270 if (mMenuState == EMPTY_MENU) {
1271 return false;
1272 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001273 MenuInflater inflater = mActivity.getMenuInflater();
1274 inflater.inflate(R.menu.browser, menu);
1275 updateInLoadMenuItems(menu);
1276 // hold on to the menu reference here; it is used by the page callbacks
1277 // to update the menu based on loading state
1278 mCachedMenu = menu;
1279 return true;
1280 }
1281
1282 protected void onCreateContextMenu(ContextMenu menu, View v,
1283 ContextMenuInfo menuInfo) {
1284 if (v instanceof TitleBarBase) {
1285 return;
1286 }
1287 if (!(v instanceof WebView)) {
1288 return;
1289 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001290 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001291 WebView.HitTestResult result = webview.getHitTestResult();
1292 if (result == null) {
1293 return;
1294 }
1295
1296 int type = result.getType();
1297 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1298 Log.w(LOGTAG,
1299 "We should not show context menu when nothing is touched");
1300 return;
1301 }
1302 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1303 // let TextView handles context menu
1304 return;
1305 }
1306
1307 // Note, http://b/issue?id=1106666 is requesting that
1308 // an inflated menu can be used again. This is not available
1309 // yet, so inflate each time (yuk!)
1310 MenuInflater inflater = mActivity.getMenuInflater();
1311 inflater.inflate(R.menu.browsercontext, menu);
1312
1313 // Show the correct menu group
1314 final String extra = result.getExtra();
1315 menu.setGroupVisible(R.id.PHONE_MENU,
1316 type == WebView.HitTestResult.PHONE_TYPE);
1317 menu.setGroupVisible(R.id.EMAIL_MENU,
1318 type == WebView.HitTestResult.EMAIL_TYPE);
1319 menu.setGroupVisible(R.id.GEO_MENU,
1320 type == WebView.HitTestResult.GEO_TYPE);
1321 menu.setGroupVisible(R.id.IMAGE_MENU,
1322 type == WebView.HitTestResult.IMAGE_TYPE
1323 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1324 menu.setGroupVisible(R.id.ANCHOR_MENU,
1325 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1326 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001327 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1328 || type == WebView.HitTestResult.PHONE_TYPE
1329 || type == WebView.HitTestResult.EMAIL_TYPE
1330 || type == WebView.HitTestResult.GEO_TYPE;
1331 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1332 if (hitText) {
1333 menu.findItem(R.id.select_text_menu_id)
1334 .setOnMenuItemClickListener(new SelectText(webview));
1335 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001336 // Setup custom handling depending on the type
1337 switch (type) {
1338 case WebView.HitTestResult.PHONE_TYPE:
1339 menu.setHeaderTitle(Uri.decode(extra));
1340 menu.findItem(R.id.dial_context_menu_id).setIntent(
1341 new Intent(Intent.ACTION_VIEW, Uri
1342 .parse(WebView.SCHEME_TEL + extra)));
1343 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1344 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1345 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1346 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1347 addIntent);
1348 menu.findItem(R.id.copy_phone_context_menu_id)
1349 .setOnMenuItemClickListener(
1350 new Copy(extra));
1351 break;
1352
1353 case WebView.HitTestResult.EMAIL_TYPE:
1354 menu.setHeaderTitle(extra);
1355 menu.findItem(R.id.email_context_menu_id).setIntent(
1356 new Intent(Intent.ACTION_VIEW, Uri
1357 .parse(WebView.SCHEME_MAILTO + extra)));
1358 menu.findItem(R.id.copy_mail_context_menu_id)
1359 .setOnMenuItemClickListener(
1360 new Copy(extra));
1361 break;
1362
1363 case WebView.HitTestResult.GEO_TYPE:
1364 menu.setHeaderTitle(extra);
1365 menu.findItem(R.id.map_context_menu_id).setIntent(
1366 new Intent(Intent.ACTION_VIEW, Uri
1367 .parse(WebView.SCHEME_GEO
1368 + URLEncoder.encode(extra))));
1369 menu.findItem(R.id.copy_geo_context_menu_id)
1370 .setOnMenuItemClickListener(
1371 new Copy(extra));
1372 break;
1373
1374 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1375 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001376 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001377 // decide whether to show the open link in new tab option
1378 boolean showNewTab = mTabControl.canCreateNewTab();
1379 MenuItem newTabItem
1380 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001381 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001382 ? R.string.contextmenu_openlink_newwindow_background
1383 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001384 newTabItem.setVisible(showNewTab);
1385 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001386 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1387 newTabItem.setOnMenuItemClickListener(
1388 new MenuItem.OnMenuItemClickListener() {
1389 @Override
1390 public boolean onMenuItemClick(MenuItem item) {
1391 final HashMap<String, WebView> hrefMap =
1392 new HashMap<String, WebView>();
1393 hrefMap.put("webview", webview);
1394 final Message msg = mHandler.obtainMessage(
1395 FOCUS_NODE_HREF,
1396 R.id.open_newtab_context_menu_id,
1397 0, hrefMap);
1398 webview.requestFocusNodeHref(msg);
1399 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001400 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001401 });
1402 } else {
1403 newTabItem.setOnMenuItemClickListener(
1404 new MenuItem.OnMenuItemClickListener() {
1405 @Override
1406 public boolean onMenuItemClick(MenuItem item) {
1407 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001408 openTab(extra, parent,
1409 !mSettings.openInBackground(),
1410 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001411 return true;
1412 }
1413 });
1414 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001415 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001416 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1417 break;
1418 }
1419 // otherwise fall through to handle image part
1420 case WebView.HitTestResult.IMAGE_TYPE:
1421 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1422 menu.setHeaderTitle(extra);
1423 }
1424 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1425 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1426 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001427 setOnMenuItemClickListener(
1428 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001429 menu.findItem(R.id.set_wallpaper_context_menu_id).
1430 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1431 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001432 break;
1433
1434 default:
1435 Log.w(LOGTAG, "We should not get here.");
1436 break;
1437 }
1438 //update the ui
1439 mUi.onContextMenuCreated(menu);
1440 }
1441
1442 /**
1443 * As the menu can be open when loading state changes
1444 * we must manually update the state of the stop/reload menu
1445 * item
1446 */
1447 private void updateInLoadMenuItems(Menu menu) {
1448 if (menu == null) {
1449 return;
1450 }
1451 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1452 MenuItem src = mInLoad ?
1453 menu.findItem(R.id.stop_menu_id):
1454 menu.findItem(R.id.reload_menu_id);
1455 if (src != null) {
1456 dest.setIcon(src.getIcon());
1457 dest.setTitle(src.getTitle());
1458 }
1459 }
1460
John Reckb3417f02011-01-14 11:01:05 -08001461 boolean onPrepareOptionsMenu(Menu menu) {
1462 if (mOptionsMenuHandler != null) {
1463 return mOptionsMenuHandler.onPrepareOptionsMenu(menu);
1464 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001465 // Note: setVisible will decide whether an item is visible; while
1466 // setEnabled() will decide whether an item is enabled, which also means
1467 // whether the matching shortcut key will function.
1468 switch (mMenuState) {
1469 case EMPTY_MENU:
1470 if (mCurrentMenuState != mMenuState) {
1471 menu.setGroupVisible(R.id.MAIN_MENU, false);
1472 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1473 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1474 }
1475 break;
1476 default:
1477 if (mCurrentMenuState != mMenuState) {
1478 menu.setGroupVisible(R.id.MAIN_MENU, true);
1479 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1480 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1481 }
1482 final WebView w = getCurrentTopWebView();
1483 boolean canGoBack = false;
1484 boolean canGoForward = false;
1485 boolean isHome = false;
1486 if (w != null) {
1487 canGoBack = w.canGoBack();
1488 canGoForward = w.canGoForward();
1489 isHome = mSettings.getHomePage().equals(w.getUrl());
1490 }
1491 final MenuItem back = menu.findItem(R.id.back_menu_id);
1492 back.setEnabled(canGoBack);
1493
1494 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1495 home.setEnabled(!isHome);
1496
1497 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1498 forward.setEnabled(canGoForward);
1499
1500 // decide whether to show the share link option
1501 PackageManager pm = mActivity.getPackageManager();
1502 Intent send = new Intent(Intent.ACTION_SEND);
1503 send.setType("text/plain");
1504 ResolveInfo ri = pm.resolveActivity(send,
1505 PackageManager.MATCH_DEFAULT_ONLY);
1506 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1507
John Reck35e9dd62011-04-25 09:01:54 -07001508 boolean isNavDump = mSettings.enableNavDump();
Michael Kolb8233fac2010-10-26 16:08:53 -07001509 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1510 nav.setVisible(isNavDump);
1511 nav.setEnabled(isNavDump);
1512
John Reck35e9dd62011-04-25 09:01:54 -07001513 boolean showDebugSettings = mSettings.isDebugEnabled();
Michael Kolb8233fac2010-10-26 16:08:53 -07001514 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1515 counter.setVisible(showDebugSettings);
1516 counter.setEnabled(showDebugSettings);
1517
John Reckb3417f02011-01-14 11:01:05 -08001518 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1519 newtab.setEnabled(getTabControl().canCreateNewTab());
Michael Kolb8233fac2010-10-26 16:08:53 -07001520
Leon Scroggins81983762011-02-11 15:17:36 -05001521 MenuItem archive = menu.findItem(R.id.save_webarchive_menu_id);
John Reck51d8bad2011-02-28 15:47:47 -08001522 Tab tab = getTabControl().getCurrentTab();
1523 String url = tab != null ? tab.getUrl() : null;
1524 archive.setVisible(!TextUtils.isEmpty(url)
1525 && !url.endsWith(".webarchivexml"));
Michael Kolb8233fac2010-10-26 16:08:53 -07001526 break;
1527 }
1528 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001529 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001530 }
1531
1532 public boolean onOptionsItemSelected(MenuItem item) {
John Reckb3417f02011-01-14 11:01:05 -08001533 if (mOptionsMenuHandler != null &&
1534 mOptionsMenuHandler.onOptionsItemSelected(item)) {
1535 return true;
1536 }
1537
Michael Kolb8233fac2010-10-26 16:08:53 -07001538 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1539 // menu remains active, so ensure comboview is dismissed
1540 // if main menu option is selected
1541 removeComboView();
1542 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001543 if (null == getCurrentTopWebView()) {
1544 return false;
1545 }
1546 if (mMenuIsDown) {
1547 // The shortcut action consumes the MENU. Even if it is still down,
1548 // it won't trigger the next shortcut action. In the case of the
1549 // shortcut action triggering a new activity, like Bookmarks, we
1550 // won't get onKeyUp for MENU. So it is important to reset it here.
1551 mMenuIsDown = false;
1552 }
1553 switch (item.getItemId()) {
1554 // -- Main menu
1555 case R.id.new_tab_menu_id:
1556 openTabToHomePage();
1557 break;
1558
1559 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001560 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001561 break;
1562
1563 case R.id.goto_menu_id:
1564 editUrl();
1565 break;
1566
1567 case R.id.bookmarks_menu_id:
1568 bookmarksOrHistoryPicker(false);
1569 break;
1570
1571 case R.id.active_tabs_menu_id:
1572 showActiveTabsPage();
1573 break;
1574
1575 case R.id.add_bookmark_menu_id:
John Reck3ffc5ca2011-06-10 15:56:06 -07001576 bookmarkCurrentPage(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001577 break;
1578
1579 case R.id.stop_reload_menu_id:
1580 if (mInLoad) {
1581 stopLoading();
1582 } else {
1583 getCurrentTopWebView().reload();
1584 }
1585 break;
1586
1587 case R.id.back_menu_id:
1588 getCurrentTopWebView().goBack();
1589 break;
1590
1591 case R.id.forward_menu_id:
1592 getCurrentTopWebView().goForward();
1593 break;
1594
1595 case R.id.close_menu_id:
1596 // Close the subwindow if it exists.
1597 if (mTabControl.getCurrentSubWindow() != null) {
1598 dismissSubWindow(mTabControl.getCurrentTab());
1599 break;
1600 }
1601 closeCurrentTab();
1602 break;
1603
1604 case R.id.homepage_menu_id:
1605 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07001606 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07001607 break;
1608
1609 case R.id.preferences_menu_id:
1610 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1611 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1612 getCurrentTopWebView().getUrl());
1613 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1614 break;
1615
1616 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001617 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001618 break;
1619
John Reckf33b1632011-06-04 20:00:23 -07001620 case R.id.freeze_tab_menu_id:
1621 // TODO: Show error messages
John Reck541f55a2011-06-07 16:34:43 -07001622 Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07001623 if (source == null) break;
John Reckd8c74522011-06-14 08:45:00 -07001624 final ContentResolver cr = mActivity.getContentResolver();
1625 final ContentValues values = source.createSnapshotValues();
1626 new AsyncTask<Tab, Void, Long>() {
1627 @Override
1628 protected Long doInBackground(Tab... params) {
1629 Tab t = params[0];
1630 if (values == null) {
1631 return t.isSnapshot()
1632 ? ((SnapshotTab)t).getSnapshotId()
1633 : -1;
1634 }
1635 Uri result = cr.insert(Snapshots.CONTENT_URI, values);
1636 long id = ContentUris.parseId(result);
1637 return id;
1638 }
1639
1640 protected void onPostExecute(Long id) {
1641 if (id > 0) {
1642 createNewSnapshotTab(id, true);
1643 }
1644 };
1645 }.execute(source);
John Reckf33b1632011-06-04 20:00:23 -07001646 break;
1647
Leon Scrogginsac993842011-02-02 12:54:07 -05001648 case R.id.save_webarchive_menu_id:
1649 String state = Environment.getExternalStorageState();
1650 if (!Environment.MEDIA_MOUNTED.equals(state)) {
1651 Log.e(LOGTAG, "External storage not mounted");
1652 Toast.makeText(mActivity, R.string.webarchive_failed,
1653 Toast.LENGTH_SHORT).show();
1654 break;
1655 }
1656 final String directory = Environment.getExternalStoragePublicDirectory(
1657 Environment.DIRECTORY_DOWNLOADS) + File.separator;
1658 File dir = new File(directory);
1659 if (!dir.exists() && !dir.mkdirs()) {
1660 Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
1661 Toast.makeText(mActivity, R.string.webarchive_failed,
1662 Toast.LENGTH_SHORT).show();
1663 break;
1664 }
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001665 final WebView topWebView = getCurrentTopWebView();
Leon Scrogginsac993842011-02-02 12:54:07 -05001666 final String title = topWebView.getTitle();
John Reck51d8bad2011-02-28 15:47:47 -08001667 final String url = topWebView.getUrl();
Leon Scrogginsac993842011-02-02 12:54:07 -05001668 topWebView.saveWebArchive(directory, true,
1669 new ValueCallback<String>() {
1670 @Override
1671 public void onReceiveValue(final String value) {
1672 if (value != null) {
1673 File file = new File(value);
1674 final long length = file.length();
1675 if (file.exists() && length > 0) {
Leon Scroggins1cb96552011-02-11 14:22:57 -05001676 Toast.makeText(mActivity, R.string.webarchive_saved,
1677 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001678 final DownloadManager manager = (DownloadManager) mActivity
1679 .getSystemService(Context.DOWNLOAD_SERVICE);
1680 new Thread("Add WebArchive to download manager") {
1681 @Override
1682 public void run() {
Vasu Noria9e30a72011-03-07 11:37:34 -08001683 manager.addCompletedDownload(
1684 null == title ? value : title,
Leon Scrogginsac993842011-02-02 12:54:07 -05001685 value, true, "application/x-webarchive-xml",
1686 value, length, true);
1687 }
1688 }.start();
1689 return;
1690 }
1691 }
John Reck51d8bad2011-02-28 15:47:47 -08001692 DownloadHandler.onDownloadStartNoStream(mActivity,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001693 url, null, null, null, topWebView.isPrivateBrowsingEnabled());
Leon Scrogginsac993842011-02-02 12:54:07 -05001694 }
1695 });
1696 break;
1697
Michael Kolb8233fac2010-10-26 16:08:53 -07001698 case R.id.page_info_menu_id:
Huahui Wuae0c0412011-06-28 10:17:05 -07001699 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001700 break;
1701
1702 case R.id.classic_history_menu_id:
1703 bookmarksOrHistoryPicker(true);
1704 break;
1705
1706 case R.id.title_bar_share_page_url:
1707 case R.id.share_page_menu_id:
1708 Tab currentTab = mTabControl.getCurrentTab();
1709 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001710 return false;
1711 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001712 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001713 break;
1714
1715 case R.id.dump_nav_menu_id:
1716 getCurrentTopWebView().debugDump();
1717 break;
1718
1719 case R.id.dump_counters_menu_id:
1720 getCurrentTopWebView().dumpV8Counters();
1721 break;
1722
1723 case R.id.zoom_in_menu_id:
1724 getCurrentTopWebView().zoomIn();
1725 break;
1726
1727 case R.id.zoom_out_menu_id:
1728 getCurrentTopWebView().zoomOut();
1729 break;
1730
1731 case R.id.view_downloads_menu_id:
1732 viewDownloads();
1733 break;
1734
1735 case R.id.window_one_menu_id:
1736 case R.id.window_two_menu_id:
1737 case R.id.window_three_menu_id:
1738 case R.id.window_four_menu_id:
1739 case R.id.window_five_menu_id:
1740 case R.id.window_six_menu_id:
1741 case R.id.window_seven_menu_id:
1742 case R.id.window_eight_menu_id:
1743 {
1744 int menuid = item.getItemId();
1745 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1746 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1747 Tab desiredTab = mTabControl.getTab(id);
1748 if (desiredTab != null &&
1749 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001750 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001751 }
1752 break;
1753 }
1754 }
1755 }
1756 break;
1757
1758 default:
1759 return false;
1760 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001761 return true;
1762 }
1763
1764 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001765 // Let the History and Bookmark fragments handle menus they created.
1766 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1767 return false;
1768 }
1769
Michael Kolb8233fac2010-10-26 16:08:53 -07001770 int id = item.getItemId();
1771 boolean result = true;
1772 switch (id) {
1773 // For the context menu from the title bar
1774 case R.id.title_bar_copy_page_url:
1775 Tab currentTab = mTabControl.getCurrentTab();
1776 if (null == currentTab) {
1777 result = false;
1778 break;
1779 }
1780 WebView mainView = currentTab.getWebView();
1781 if (null == mainView) {
1782 result = false;
1783 break;
1784 }
1785 copy(mainView.getUrl());
1786 break;
1787 // -- Browser context menu
1788 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001789 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001790 case R.id.copy_link_context_menu_id:
1791 final WebView webView = getCurrentTopWebView();
1792 if (null == webView) {
1793 result = false;
1794 break;
1795 }
1796 final HashMap<String, WebView> hrefMap =
1797 new HashMap<String, WebView>();
1798 hrefMap.put("webview", webView);
1799 final Message msg = mHandler.obtainMessage(
1800 FOCUS_NODE_HREF, id, 0, hrefMap);
1801 webView.requestFocusNodeHref(msg);
1802 break;
1803
1804 default:
1805 // For other context menus
1806 result = onOptionsItemSelected(item);
1807 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001808 return result;
1809 }
1810
1811 /**
1812 * support programmatically opening the context menu
1813 */
1814 public void openContextMenu(View view) {
1815 mActivity.openContextMenu(view);
1816 }
1817
1818 /**
1819 * programmatically open the options menu
1820 */
1821 public void openOptionsMenu() {
1822 mActivity.openOptionsMenu();
1823 }
1824
1825 public boolean onMenuOpened(int featureId, Menu menu) {
1826 if (mOptionsMenuOpen) {
1827 if (mConfigChanged) {
1828 // We do not need to make any changes to the state of the
1829 // title bar, since the only thing that happened was a
1830 // change in orientation
1831 mConfigChanged = false;
1832 } else {
1833 if (!mExtendedMenuOpen) {
1834 mExtendedMenuOpen = true;
1835 mUi.onExtendedMenuOpened();
1836 } else {
1837 // Switching the menu back to icon view, so show the
1838 // title bar once again.
1839 mExtendedMenuOpen = false;
1840 mUi.onExtendedMenuClosed(mInLoad);
Michael Kolb8233fac2010-10-26 16:08:53 -07001841 }
1842 }
1843 } else {
1844 // The options menu is closed, so open it, and show the title
1845 mOptionsMenuOpen = true;
1846 mConfigChanged = false;
1847 mExtendedMenuOpen = false;
1848 mUi.onOptionsMenuOpened();
1849 }
1850 return true;
1851 }
1852
1853 public void onOptionsMenuClosed(Menu menu) {
1854 mOptionsMenuOpen = false;
1855 mUi.onOptionsMenuClosed(mInLoad);
1856 }
1857
1858 public void onContextMenuClosed(Menu menu) {
1859 mUi.onContextMenuClosed(menu, mInLoad);
1860 }
1861
1862 // Helper method for getting the top window.
1863 @Override
1864 public WebView getCurrentTopWebView() {
1865 return mTabControl.getCurrentTopWebView();
1866 }
1867
1868 @Override
1869 public WebView getCurrentWebView() {
1870 return mTabControl.getCurrentWebView();
1871 }
1872
1873 /*
1874 * This method is called as a result of the user selecting the options
1875 * menu to see the download window. It shows the download window on top of
1876 * the current window.
1877 */
1878 void viewDownloads() {
1879 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1880 mActivity.startActivity(intent);
1881 }
1882
1883 // action mode
1884
1885 void onActionModeStarted(ActionMode mode) {
1886 mUi.onActionModeStarted(mode);
1887 mActionMode = mode;
1888 }
1889
1890 /*
1891 * True if a custom ActionMode (i.e. find or select) is in use.
1892 */
1893 @Override
1894 public boolean isInCustomActionMode() {
1895 return mActionMode != null;
1896 }
1897
1898 /*
1899 * End the current ActionMode.
1900 */
1901 @Override
1902 public void endActionMode() {
1903 if (mActionMode != null) {
1904 mActionMode.finish();
1905 }
1906 }
1907
1908 /*
1909 * Called by find and select when they are finished. Replace title bars
1910 * as necessary.
1911 */
1912 public void onActionModeFinished(ActionMode mode) {
1913 if (!isInCustomActionMode()) return;
1914 mUi.onActionModeFinished(mInLoad);
1915 mActionMode = null;
1916 }
1917
1918 boolean isInLoad() {
1919 return mInLoad;
1920 }
1921
1922 // bookmark handling
1923
1924 /**
1925 * add the current page as a bookmark to the given folder id
1926 * @param folderId use -1 for the default folder
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001927 * @param canBeAnEdit If true, check to see whether the site is already
1928 * bookmarked, and if it is, edit that bookmark. If false, and
1929 * the site is already bookmarked, do not attempt to edit the
1930 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001931 */
1932 @Override
John Reck3ffc5ca2011-06-10 15:56:06 -07001933 public void bookmarkCurrentPage(boolean canBeAnEdit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001934 Intent i = new Intent(mActivity,
1935 AddBookmarkPage.class);
1936 WebView w = getCurrentTopWebView();
1937 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1938 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1939 String touchIconUrl = w.getTouchIconUrl();
1940 if (touchIconUrl != null) {
1941 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1942 WebSettings settings = w.getSettings();
1943 if (settings != null) {
1944 i.putExtra(AddBookmarkPage.USER_AGENT,
1945 settings.getUserAgentString());
1946 }
1947 }
1948 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1949 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1950 getDesiredThumbnailHeight(mActivity)));
1951 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001952 if (canBeAnEdit) {
1953 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1954 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001955 // Put the dialog at the upper right of the screen, covering the
1956 // star on the title bar.
1957 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1958 mActivity.startActivity(i);
1959 }
1960
1961 // file chooser
1962 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1963 mUploadHandler = new UploadHandler(this);
1964 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1965 }
1966
1967 // thumbnails
1968
1969 /**
1970 * Return the desired width for thumbnail screenshots, which are stored in
1971 * the database, and used on the bookmarks screen.
1972 * @param context Context for finding out the density of the screen.
1973 * @return desired width for thumbnail screenshot.
1974 */
1975 static int getDesiredThumbnailWidth(Context context) {
1976 return context.getResources().getDimensionPixelOffset(
1977 R.dimen.bookmarkThumbnailWidth);
1978 }
1979
1980 /**
1981 * Return the desired height for thumbnail screenshots, which are stored in
1982 * the database, and used on the bookmarks screen.
1983 * @param context Context for finding out the density of the screen.
1984 * @return desired height for thumbnail screenshot.
1985 */
1986 static int getDesiredThumbnailHeight(Context context) {
1987 return context.getResources().getDimensionPixelOffset(
1988 R.dimen.bookmarkThumbnailHeight);
1989 }
1990
Michael Kolb1acef692011-03-08 14:12:06 -08001991 static Bitmap createScreenshot(Tab tab, int width, int height) {
1992 if ((tab != null) && (tab.getWebView() != null)) {
1993 return createScreenshot(tab.getWebView(), width, height);
1994 }
1995 return null;
1996 }
1997
Michael Kolb8233fac2010-10-26 16:08:53 -07001998 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001999 // We render to a bitmap 2x the desired size so that we can then
2000 // re-scale it with filtering since canvas.scale doesn't filter
2001 // This helps reduce aliasing at the cost of being slightly blurry
2002 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07002003 Picture thumbnail = view.capturePicture();
2004 if (thumbnail == null) {
2005 return null;
2006 }
John Reck5c6ac2f2011-01-05 10:18:03 -08002007 width *= filter_scale;
2008 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07002009 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
2010 Canvas canvas = new Canvas(bm);
2011 // May need to tweak these values to determine what is the
2012 // best scale factor
2013 int thumbnailWidth = thumbnail.getWidth();
2014 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08002015 float scaleFactor = 1.0f;
Michael Kolbeb95db42011-03-03 10:38:40 -08002016 if (thumbnailWidth > 0 && thumbnailHeight > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08002017 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07002018 } else {
2019 return null;
2020 }
John Reckfe49ab42010-11-16 17:09:37 -08002021
Michael Kolbeb95db42011-03-03 10:38:40 -08002022 float scaleFactorY = (float) height / (float)thumbnailHeight;
2023 if (scaleFactorY > scaleFactor) {
2024 // The picture is narrower than the requested AR
2025 // Center the thumnail and crop the sides
2026 scaleFactor = scaleFactorY;
John Reckfe49ab42010-11-16 17:09:37 -08002027 float wx = (thumbnailWidth * scaleFactor) - width;
2028 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07002029 }
2030
John Reckfe49ab42010-11-16 17:09:37 -08002031 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07002032
2033 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08002034 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
2035 height / filter_scale, true);
2036 bm.recycle();
2037 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07002038 }
2039
John Reck34ef2672011-02-10 11:30:55 -08002040 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002041 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07002042 // FIXME: Would like to make sure there is actually something to
2043 // draw, but the API for that (WebViewCore.pictureReady()) is not
2044 // currently accessible here.
2045
John Reck34ef2672011-02-10 11:30:55 -08002046 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08002047 if (view == null) {
2048 // Tab was destroyed
2049 return;
2050 }
John Reck34ef2672011-02-10 11:30:55 -08002051 final String url = tab.getUrl();
2052 final String originalUrl = view.getOriginalUrl();
2053
2054 if (TextUtils.isEmpty(url)) {
2055 return;
2056 }
2057
2058 // Only update thumbnails for web urls (http(s)://), not for
2059 // about:, javascript:, data:, etc...
2060 // Unless it is a bookmarked site, then always update
2061 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2062 return;
2063 }
2064
Michael Kolb8233fac2010-10-26 16:08:53 -07002065 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2066 getDesiredThumbnailHeight(mActivity));
2067 if (bm == null) {
2068 return;
2069 }
2070
2071 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002072 new AsyncTask<Void, Void, Void>() {
2073 @Override
2074 protected Void doInBackground(Void... unused) {
2075 Cursor cursor = null;
2076 try {
2077 // TODO: Clean this up
2078 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2079 if (cursor != null && cursor.moveToFirst()) {
2080 final ByteArrayOutputStream os =
2081 new ByteArrayOutputStream();
2082 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002083
John Reck34ef2672011-02-10 11:30:55 -08002084 ContentValues values = new ContentValues();
2085 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002086
John Reck34ef2672011-02-10 11:30:55 -08002087 do {
John Reck617fd832011-02-16 14:35:59 -08002088 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002089 cr.update(Images.CONTENT_URI, values, null, null);
2090 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002091 }
John Reck34ef2672011-02-10 11:30:55 -08002092 } catch (IllegalStateException e) {
2093 // Ignore
2094 } finally {
2095 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002096 }
John Reck34ef2672011-02-10 11:30:55 -08002097 return null;
2098 }
2099 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002100 }
2101
2102 private class Copy implements OnMenuItemClickListener {
2103 private CharSequence mText;
2104
2105 public boolean onMenuItemClick(MenuItem item) {
2106 copy(mText);
2107 return true;
2108 }
2109
2110 public Copy(CharSequence toCopy) {
2111 mText = toCopy;
2112 }
2113 }
2114
Leon Scroggins63c02662010-11-18 15:16:27 -05002115 private static class Download implements OnMenuItemClickListener {
2116 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002117 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002118 private boolean mPrivateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002119
2120 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002121 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002122 null, null, mPrivateBrowsing);
Michael Kolb8233fac2010-10-26 16:08:53 -07002123 return true;
2124 }
2125
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002126 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002127 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002128 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002129 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002130 }
2131 }
2132
Cary Clark8974d282010-11-22 10:46:05 -05002133 private static class SelectText implements OnMenuItemClickListener {
2134 private WebView mWebView;
2135
2136 public boolean onMenuItemClick(MenuItem item) {
2137 if (mWebView != null) {
2138 return mWebView.selectText();
2139 }
2140 return false;
2141 }
2142
2143 public SelectText(WebView webView) {
2144 mWebView = webView;
2145 }
2146
2147 }
2148
Michael Kolb8233fac2010-10-26 16:08:53 -07002149 /********************** TODO: UI stuff *****************************/
2150
2151 // these methods have been copied, they still need to be cleaned up
2152
2153 /****************** tabs ***************************************************/
2154
2155 // basic tab interactions:
2156
2157 // it is assumed that tabcontrol already knows about the tab
2158 protected void addTab(Tab tab) {
2159 mUi.addTab(tab);
2160 }
2161
2162 protected void removeTab(Tab tab) {
2163 mUi.removeTab(tab);
2164 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002165 mCrashRecoveryHandler.backupState();
John Reckd8c74522011-06-14 08:45:00 -07002166 if (tab.isSnapshot()) {
2167 SnapshotTab st = (SnapshotTab) tab;
2168 final Uri uri = ContentUris.withAppendedId(
2169 Snapshots.CONTENT_URI, st.getSnapshotId());
2170 final ContentResolver cr = mActivity.getContentResolver();
2171 new Thread() {
2172 @Override
2173 public void run() {
2174 cr.delete(uri, null, null);
2175 }
2176 }.start();
2177 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002178 }
2179
Michael Kolbf2055602011-04-09 17:20:03 -07002180 @Override
2181 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002182 // monkey protection against delayed start
2183 if (tab != null) {
2184 mTabControl.setCurrentTab(tab);
2185 // the tab is guaranteed to have a webview after setCurrentTab
2186 mUi.setActiveTab(tab);
2187 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002188 }
2189
2190 protected void closeEmptyChildTab() {
2191 Tab current = mTabControl.getCurrentTab();
2192 if (current != null
2193 && current.getWebView().copyBackForwardList().getSize() == 0) {
Michael Kolbc831b632011-05-11 09:30:34 -07002194 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002195 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002196 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002197 closeTab(current);
2198 }
2199 }
2200 }
2201
John Reck26b18322011-06-21 13:08:58 -07002202 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002203 // Dismiss the subwindow if applicable.
2204 dismissSubWindow(appTab);
2205 // Since we might kill the WebView, remove it from the
2206 // content view first.
2207 mUi.detachTab(appTab);
2208 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002209 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002210 // TODO: analyze why the remove and add are necessary
2211 mUi.attachTab(appTab);
2212 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002213 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002214 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002215 } else {
2216 // If the tab was the current tab, we have to attach
2217 // it to the view system again.
2218 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002219 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002220 }
2221 }
2222
2223 // Remove the sub window if it exists. Also called by TabControl when the
2224 // user clicks the 'X' to dismiss a sub window.
2225 public void dismissSubWindow(Tab tab) {
2226 removeSubWindow(tab);
2227 // dismiss the subwindow. This will destroy the WebView.
2228 tab.dismissSubWindow();
2229 getCurrentTopWebView().requestFocus();
2230 }
2231
2232 @Override
2233 public void removeSubWindow(Tab t) {
2234 if (t.getSubWebView() != null) {
2235 mUi.removeSubWindow(t.getSubViewContainer());
2236 }
2237 }
2238
2239 @Override
2240 public void attachSubWindow(Tab tab) {
2241 if (tab.getSubWebView() != null) {
2242 mUi.attachSubWindow(tab.getSubViewContainer());
2243 getCurrentTopWebView().requestFocus();
2244 }
2245 }
2246
Michael Kolb7bcafde2011-05-09 13:55:59 -07002247 // open a non inconito tab with the given url data
2248 // and set as active tab
2249 public Tab openTab(UrlData urlData) {
2250 Tab tab = createNewTab(false, true, true);
2251 if ((tab != null) && !urlData.isEmpty()) {
2252 loadUrlDataIn(tab, urlData);
2253 }
2254 return tab;
2255 }
2256
Michael Kolb843510f2010-12-09 10:51:49 -08002257 @Override
2258 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002259 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002260 }
2261
Michael Kolb8233fac2010-10-26 16:08:53 -07002262 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002263 public Tab openIncognitoTab() {
2264 return openTab(INCOGNITO_URI, true, true, false);
2265 }
2266
2267 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002268 public Tab openTab(String url, boolean incognito, boolean setActive,
2269 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002270 return openTab(url, incognito, setActive, useCurrent, null);
2271 }
2272
2273 @Override
2274 public Tab openTab(String url, Tab parent, boolean setActive,
2275 boolean useCurrent) {
2276 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2277 setActive, useCurrent, parent);
2278 }
2279
2280 public Tab openTab(String url, boolean incognito, boolean setActive,
2281 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002282 Tab tab = createNewTab(incognito, setActive, useCurrent);
2283 if (tab != null) {
John Reck5949c662011-05-27 09:52:29 -07002284 if (parent != null && parent != tab) {
2285 parent.addChildTab(tab);
2286 }
Michael Kolb519d2282011-05-09 17:03:19 -07002287 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002288 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002289 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002290 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002291 return tab;
2292 }
2293
2294 // this method will attempt to create a new tab
2295 // incognito: private browsing tab
2296 // setActive: ste tab as current tab
2297 // useCurrent: if no new tab can be created, return current tab
2298 private Tab createNewTab(boolean incognito, boolean setActive,
2299 boolean useCurrent) {
2300 Tab tab = null;
2301 if (mTabControl.canCreateNewTab()) {
2302 tab = mTabControl.createNewTab(incognito);
2303 addTab(tab);
2304 if (setActive) {
2305 setActiveTab(tab);
2306 }
2307 } else {
2308 if (useCurrent) {
2309 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002310 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002311 } else {
2312 mUi.showMaxTabsWarning();
2313 }
2314 }
2315 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002316 }
2317
John Reckd8c74522011-06-14 08:45:00 -07002318 private SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2319 SnapshotTab tab = mTabControl.createSnapshotTab(snapshotId);
2320 addTab(tab);
2321 if (setActive) {
2322 setActiveTab(tab);
2323 }
2324 return tab;
2325 }
2326
Michael Kolb8233fac2010-10-26 16:08:53 -07002327 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002328 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002329 * @return boolean True if we successfully switched to a different tab. If
2330 * the indexth tab is null, or if that tab is the same as
2331 * the current one, return false.
2332 */
2333 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002334 public boolean switchToTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002335 // hide combo view if open
2336 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002337 Tab currentTab = mTabControl.getCurrentTab();
2338 if (tab == null || tab == currentTab) {
2339 return false;
2340 }
2341 setActiveTab(tab);
2342 return true;
2343 }
2344
2345 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002346 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002347 // hide combo view if open
2348 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002349 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002350 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002351 return;
2352 }
Michael Kolbc831b632011-05-11 09:30:34 -07002353 final Tab current = mTabControl.getCurrentTab();
2354 final int pos = mTabControl.getCurrentPosition();
2355 Tab newTab = current.getParent();
2356 if (newTab == null) {
2357 newTab = mTabControl.getTab(pos + 1);
2358 if (newTab == null) {
2359 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002360 }
2361 }
Michael Kolbc831b632011-05-11 09:30:34 -07002362 if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002363 // Close window
2364 closeTab(current);
2365 }
2366 }
2367
2368 /**
2369 * Close the tab, remove its associated title bar, and adjust mTabControl's
2370 * current tab to a valid value.
2371 */
2372 @Override
2373 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002374 // hide combo view if open
2375 removeComboView();
Michael Kolb2d59c322011-01-25 13:18:55 -08002376 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002377 }
2378
Michael Kolb8233fac2010-10-26 16:08:53 -07002379 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07002380 protected void loadUrlFromContext(String url) {
2381 Tab tab = getCurrentTab();
2382 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002383 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07002384 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002385 url = UrlUtils.smartUrlFilter(url);
2386 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07002387 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07002388 }
2389 }
2390 }
2391
2392 /**
2393 * Load the URL into the given WebView and update the title bar
2394 * to reflect the new load. Call this instead of WebView.loadUrl
2395 * directly.
2396 * @param view The WebView used to load url.
2397 * @param url The URL to load.
2398 */
John Reck26b18322011-06-21 13:08:58 -07002399 protected void loadUrl(Tab tab, String url) {
2400 loadUrl(tab, url, null);
2401 }
2402
2403 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
2404 if (tab != null) {
2405 dismissSubWindow(tab);
2406 tab.loadUrl(url, headers);
2407 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002408 }
2409
2410 /**
2411 * Load UrlData into a Tab and update the title bar to reflect the new
2412 * load. Call this instead of UrlData.loadIn directly.
2413 * @param t The Tab used to load.
2414 * @param data The UrlData being loaded.
2415 */
2416 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07002417 if (data != null) {
2418 if (data.mVoiceIntent != null) {
2419 t.activateVoiceSearchMode(data.mVoiceIntent);
2420 } else {
2421 loadUrl(t, data.mUrl, data.mHeaders);
2422 }
2423 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002424 }
2425
John Reck30c714c2010-12-16 17:30:34 -08002426 @Override
2427 public void onUserCanceledSsl(Tab tab) {
2428 WebView web = tab.getWebView();
2429 // TODO: Figure out the "right" behavior
2430 if (web.canGoBack()) {
2431 web.goBack();
2432 } else {
2433 web.loadUrl(mSettings.getHomePage());
2434 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002435 }
2436
2437 void goBackOnePageOrQuit() {
2438 Tab current = mTabControl.getCurrentTab();
2439 if (current == null) {
2440 /*
2441 * Instead of finishing the activity, simply push this to the back
2442 * of the stack and let ActivityManager to choose the foreground
2443 * activity. As BrowserActivity is singleTask, it will be always the
2444 * root of the task. So we can use either true or false for
2445 * moveTaskToBack().
2446 */
2447 mActivity.moveTaskToBack(true);
2448 return;
2449 }
2450 WebView w = current.getWebView();
2451 if (w.canGoBack()) {
2452 w.goBack();
2453 } else {
2454 // Check to see if we are closing a window that was created by
2455 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002456 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002457 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002458 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002459 // Now we close the other tab
2460 closeTab(current);
2461 } else {
Michael Kolb8233fac2010-10-26 16:08:53 -07002462 /*
2463 * Instead of finishing the activity, simply push this to the back
2464 * of the stack and let ActivityManager to choose the foreground
2465 * activity. As BrowserActivity is singleTask, it will be always the
2466 * root of the task. So we can use either true or false for
2467 * moveTaskToBack().
2468 */
2469 mActivity.moveTaskToBack(true);
2470 }
2471 }
2472 }
2473
2474 /**
2475 * Feed the previously stored results strings to the BrowserProvider so that
2476 * the SearchDialog will show them instead of the standard searches.
2477 * @param result String to show on the editable line of the SearchDialog.
2478 */
2479 @Override
2480 public void showVoiceSearchResults(String result) {
2481 ContentProviderClient client = mActivity.getContentResolver()
2482 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2483 ContentProvider prov = client.getLocalContentProvider();
2484 BrowserProvider bp = (BrowserProvider) prov;
2485 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2486 client.release();
2487
2488 Bundle bundle = createGoogleSearchSourceBundle(
2489 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2490 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2491 startSearch(result, false, bundle, false);
2492 }
2493
2494 private void startSearch(String initialQuery, boolean selectInitialQuery,
2495 Bundle appSearchData, boolean globalSearch) {
2496 if (appSearchData == null) {
2497 appSearchData = createGoogleSearchSourceBundle(
2498 GOOGLE_SEARCH_SOURCE_TYPE);
2499 }
2500
2501 SearchEngine searchEngine = mSettings.getSearchEngine();
2502 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2503 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2504 }
2505 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2506 globalSearch);
2507 }
2508
2509 private Bundle createGoogleSearchSourceBundle(String source) {
2510 Bundle bundle = new Bundle();
2511 bundle.putString(Search.SOURCE, source);
2512 return bundle;
2513 }
2514
2515 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002516 * helper method for key handler
2517 * returns the current tab if it can't advance
2518 */
Michael Kolbc831b632011-05-11 09:30:34 -07002519 private Tab getNextTab() {
2520 return mTabControl.getTab(Math.min(mTabControl.getTabCount() - 1,
2521 mTabControl.getCurrentPosition() + 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002522 }
2523
2524 /**
2525 * helper method for key handler
2526 * returns the current tab if it can't advance
2527 */
Michael Kolbc831b632011-05-11 09:30:34 -07002528 private Tab getPrevTab() {
2529 return mTabControl.getTab(Math.max(0,
2530 mTabControl.getCurrentPosition() - 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002531 }
2532
2533 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002534 * handle key events in browser
2535 *
2536 * @param keyCode
2537 * @param event
2538 * @return true if handled, false to pass to super
2539 */
2540 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002541 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002542 // Even if MENU is already held down, we need to call to super to open
2543 // the IME on long press.
Michael Kolb2814a362011-05-19 15:49:41 -07002544 if (KeyEvent.KEYCODE_MENU == keyCode) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002545 if (mOptionsMenuHandler != null) {
2546 return false;
2547 } else {
2548 event.startTracking();
2549 return true;
2550 }
Michael Kolb2814a362011-05-19 15:49:41 -07002551 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002552 if (!noModifiers
2553 && ((KeyEvent.KEYCODE_MENU == keyCode)
2554 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2555 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002556 mMenuIsDown = true;
2557 return false;
2558 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002559
Cary Clark8ff8c662010-12-29 15:03:05 -05002560 WebView webView = getCurrentTopWebView();
2561 if (webView == null) return false;
2562
Cary Clark160bbb92011-01-10 11:17:07 -05002563 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2564 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002565
Michael Kolb8233fac2010-10-26 16:08:53 -07002566 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002567 case KeyEvent.KEYCODE_TAB:
2568 if (event.isCtrlPressed()) {
2569 if (event.isShiftPressed()) {
2570 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002571 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002572 } else {
2573 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002574 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002575 }
2576 return true;
2577 }
2578 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002579 case KeyEvent.KEYCODE_SPACE:
2580 // WebView/WebTextView handle the keys in the KeyDown. As
2581 // the Activity's shortcut keys are only handled when WebView
2582 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002583 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002584 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002585 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002586 pageDown();
2587 }
2588 return true;
2589 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002590 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002591 event.startTracking();
2592 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002593 case KeyEvent.KEYCODE_DPAD_LEFT:
2594 if (ctrl) {
2595 webView.goBack();
2596 return true;
2597 }
2598 break;
2599 case KeyEvent.KEYCODE_DPAD_RIGHT:
2600 if (ctrl) {
2601 webView.goForward();
2602 return true;
2603 }
2604 break;
2605 case KeyEvent.KEYCODE_A:
2606 if (ctrl) {
2607 webView.selectAll();
2608 return true;
2609 }
2610 break;
Michael Kolba4183062011-01-16 10:43:21 -08002611// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002612 case KeyEvent.KEYCODE_C:
2613 if (ctrl) {
2614 webView.copySelection();
2615 return true;
2616 }
2617 break;
Michael Kolba4183062011-01-16 10:43:21 -08002618// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002619// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002620// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002621// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002622// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002623// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002624// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002625// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002626// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002627// case KeyEvent.KEYCODE_M: // unused
2628// case KeyEvent.KEYCODE_N: // in Chrome: new window
2629// case KeyEvent.KEYCODE_O: // in Chrome: open file
2630// case KeyEvent.KEYCODE_P: // in Chrome: print page
2631// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002632// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002633// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2634 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002635 // we can't use the ctrl/shift flags, they check for
2636 // exclusive use of a modifier
2637 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002638 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002639 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002640 } else {
2641 openTabToHomePage();
2642 }
2643 return true;
2644 }
2645 break;
2646// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2647// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb1a2eba42011-03-16 16:42:49 -07002648 case KeyEvent.KEYCODE_W: // in Chrome: close tab
2649 if (ctrl) {
2650 closeCurrentTab();
2651 return true;
2652 }
2653 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002654// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2655// case KeyEvent.KEYCODE_Y: // unused
2656// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002657 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002658 // it is a regular key and webview is not null
2659 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002660 }
2661
John Recke6bf4ab2011-02-24 15:48:05 -08002662 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2663 switch(keyCode) {
2664 case KeyEvent.KEYCODE_BACK:
2665 if (mUi.showsWeb()) {
2666 bookmarksOrHistoryPicker(true);
2667 return true;
2668 }
2669 break;
2670 }
2671 return false;
2672 }
2673
Michael Kolb8233fac2010-10-26 16:08:53 -07002674 boolean onKeyUp(int keyCode, KeyEvent event) {
Michael Kolb2814a362011-05-19 15:49:41 -07002675 if (KeyEvent.KEYCODE_MENU == keyCode) {
2676 mMenuIsDown = false;
2677 if (event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002678 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002679 }
2680 }
Cary Clark160bbb92011-01-10 11:17:07 -05002681 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002682 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002683 case KeyEvent.KEYCODE_BACK:
2684 if (event.isTracking() && !event.isCanceled()) {
2685 onBackKey();
2686 return true;
2687 }
2688 break;
2689 }
2690 return false;
2691 }
2692
2693 public boolean isMenuDown() {
2694 return mMenuIsDown;
2695 }
2696
Ben Murdoch8029a772010-11-16 11:58:21 +00002697 public void setupAutoFill(Message message) {
2698 // Open the settings activity at the AutoFill profile fragment so that
2699 // the user can create a new profile. When they return, we will dispatch
2700 // the message so that we can autofill the form using their new profile.
2701 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2702 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2703 AutoFillSettingsFragment.class.getName());
2704 mAutoFillSetupMessage = message;
2705 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2706 }
John Reckb3417f02011-01-14 11:01:05 -08002707
2708 @Override
2709 public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
2710 mOptionsMenuHandler = handler;
2711 }
2712
2713 @Override
2714 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
2715 if (mOptionsMenuHandler == handler) {
2716 mOptionsMenuHandler = null;
2717 }
2718 }
2719
Narayan Kamath5119edd2011-02-23 15:49:17 +00002720 @Override
2721 public void registerDropdownChangeListener(DropdownChangeListener d) {
2722 mUi.registerDropdownChangeListener(d);
2723 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002724}