blob: 1f376d2589caf6349c709fd42e042d8b4c18dc5c [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:
1699 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1700 false);
1701 break;
1702
1703 case R.id.classic_history_menu_id:
1704 bookmarksOrHistoryPicker(true);
1705 break;
1706
1707 case R.id.title_bar_share_page_url:
1708 case R.id.share_page_menu_id:
1709 Tab currentTab = mTabControl.getCurrentTab();
1710 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001711 return false;
1712 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001713 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001714 break;
1715
1716 case R.id.dump_nav_menu_id:
1717 getCurrentTopWebView().debugDump();
1718 break;
1719
1720 case R.id.dump_counters_menu_id:
1721 getCurrentTopWebView().dumpV8Counters();
1722 break;
1723
1724 case R.id.zoom_in_menu_id:
1725 getCurrentTopWebView().zoomIn();
1726 break;
1727
1728 case R.id.zoom_out_menu_id:
1729 getCurrentTopWebView().zoomOut();
1730 break;
1731
1732 case R.id.view_downloads_menu_id:
1733 viewDownloads();
1734 break;
1735
1736 case R.id.window_one_menu_id:
1737 case R.id.window_two_menu_id:
1738 case R.id.window_three_menu_id:
1739 case R.id.window_four_menu_id:
1740 case R.id.window_five_menu_id:
1741 case R.id.window_six_menu_id:
1742 case R.id.window_seven_menu_id:
1743 case R.id.window_eight_menu_id:
1744 {
1745 int menuid = item.getItemId();
1746 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1747 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1748 Tab desiredTab = mTabControl.getTab(id);
1749 if (desiredTab != null &&
1750 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001751 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001752 }
1753 break;
1754 }
1755 }
1756 }
1757 break;
1758
1759 default:
1760 return false;
1761 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001762 return true;
1763 }
1764
1765 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001766 // Let the History and Bookmark fragments handle menus they created.
1767 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1768 return false;
1769 }
1770
Michael Kolb8233fac2010-10-26 16:08:53 -07001771 int id = item.getItemId();
1772 boolean result = true;
1773 switch (id) {
1774 // For the context menu from the title bar
1775 case R.id.title_bar_copy_page_url:
1776 Tab currentTab = mTabControl.getCurrentTab();
1777 if (null == currentTab) {
1778 result = false;
1779 break;
1780 }
1781 WebView mainView = currentTab.getWebView();
1782 if (null == mainView) {
1783 result = false;
1784 break;
1785 }
1786 copy(mainView.getUrl());
1787 break;
1788 // -- Browser context menu
1789 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001790 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001791 case R.id.copy_link_context_menu_id:
1792 final WebView webView = getCurrentTopWebView();
1793 if (null == webView) {
1794 result = false;
1795 break;
1796 }
1797 final HashMap<String, WebView> hrefMap =
1798 new HashMap<String, WebView>();
1799 hrefMap.put("webview", webView);
1800 final Message msg = mHandler.obtainMessage(
1801 FOCUS_NODE_HREF, id, 0, hrefMap);
1802 webView.requestFocusNodeHref(msg);
1803 break;
1804
1805 default:
1806 // For other context menus
1807 result = onOptionsItemSelected(item);
1808 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001809 return result;
1810 }
1811
1812 /**
1813 * support programmatically opening the context menu
1814 */
1815 public void openContextMenu(View view) {
1816 mActivity.openContextMenu(view);
1817 }
1818
1819 /**
1820 * programmatically open the options menu
1821 */
1822 public void openOptionsMenu() {
1823 mActivity.openOptionsMenu();
1824 }
1825
1826 public boolean onMenuOpened(int featureId, Menu menu) {
1827 if (mOptionsMenuOpen) {
1828 if (mConfigChanged) {
1829 // We do not need to make any changes to the state of the
1830 // title bar, since the only thing that happened was a
1831 // change in orientation
1832 mConfigChanged = false;
1833 } else {
1834 if (!mExtendedMenuOpen) {
1835 mExtendedMenuOpen = true;
1836 mUi.onExtendedMenuOpened();
1837 } else {
1838 // Switching the menu back to icon view, so show the
1839 // title bar once again.
1840 mExtendedMenuOpen = false;
1841 mUi.onExtendedMenuClosed(mInLoad);
Michael Kolb8233fac2010-10-26 16:08:53 -07001842 }
1843 }
1844 } else {
1845 // The options menu is closed, so open it, and show the title
1846 mOptionsMenuOpen = true;
1847 mConfigChanged = false;
1848 mExtendedMenuOpen = false;
1849 mUi.onOptionsMenuOpened();
1850 }
1851 return true;
1852 }
1853
1854 public void onOptionsMenuClosed(Menu menu) {
1855 mOptionsMenuOpen = false;
1856 mUi.onOptionsMenuClosed(mInLoad);
1857 }
1858
1859 public void onContextMenuClosed(Menu menu) {
1860 mUi.onContextMenuClosed(menu, mInLoad);
1861 }
1862
1863 // Helper method for getting the top window.
1864 @Override
1865 public WebView getCurrentTopWebView() {
1866 return mTabControl.getCurrentTopWebView();
1867 }
1868
1869 @Override
1870 public WebView getCurrentWebView() {
1871 return mTabControl.getCurrentWebView();
1872 }
1873
1874 /*
1875 * This method is called as a result of the user selecting the options
1876 * menu to see the download window. It shows the download window on top of
1877 * the current window.
1878 */
1879 void viewDownloads() {
1880 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1881 mActivity.startActivity(intent);
1882 }
1883
1884 // action mode
1885
1886 void onActionModeStarted(ActionMode mode) {
1887 mUi.onActionModeStarted(mode);
1888 mActionMode = mode;
1889 }
1890
1891 /*
1892 * True if a custom ActionMode (i.e. find or select) is in use.
1893 */
1894 @Override
1895 public boolean isInCustomActionMode() {
1896 return mActionMode != null;
1897 }
1898
1899 /*
1900 * End the current ActionMode.
1901 */
1902 @Override
1903 public void endActionMode() {
1904 if (mActionMode != null) {
1905 mActionMode.finish();
1906 }
1907 }
1908
1909 /*
1910 * Called by find and select when they are finished. Replace title bars
1911 * as necessary.
1912 */
1913 public void onActionModeFinished(ActionMode mode) {
1914 if (!isInCustomActionMode()) return;
1915 mUi.onActionModeFinished(mInLoad);
1916 mActionMode = null;
1917 }
1918
1919 boolean isInLoad() {
1920 return mInLoad;
1921 }
1922
1923 // bookmark handling
1924
1925 /**
1926 * add the current page as a bookmark to the given folder id
1927 * @param folderId use -1 for the default folder
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001928 * @param canBeAnEdit If true, check to see whether the site is already
1929 * bookmarked, and if it is, edit that bookmark. If false, and
1930 * the site is already bookmarked, do not attempt to edit the
1931 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001932 */
1933 @Override
John Reck3ffc5ca2011-06-10 15:56:06 -07001934 public void bookmarkCurrentPage(boolean canBeAnEdit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001935 Intent i = new Intent(mActivity,
1936 AddBookmarkPage.class);
1937 WebView w = getCurrentTopWebView();
1938 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1939 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1940 String touchIconUrl = w.getTouchIconUrl();
1941 if (touchIconUrl != null) {
1942 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1943 WebSettings settings = w.getSettings();
1944 if (settings != null) {
1945 i.putExtra(AddBookmarkPage.USER_AGENT,
1946 settings.getUserAgentString());
1947 }
1948 }
1949 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1950 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1951 getDesiredThumbnailHeight(mActivity)));
1952 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001953 if (canBeAnEdit) {
1954 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1955 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001956 // Put the dialog at the upper right of the screen, covering the
1957 // star on the title bar.
1958 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1959 mActivity.startActivity(i);
1960 }
1961
1962 // file chooser
1963 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1964 mUploadHandler = new UploadHandler(this);
1965 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1966 }
1967
1968 // thumbnails
1969
1970 /**
1971 * Return the desired width for thumbnail screenshots, which are stored in
1972 * the database, and used on the bookmarks screen.
1973 * @param context Context for finding out the density of the screen.
1974 * @return desired width for thumbnail screenshot.
1975 */
1976 static int getDesiredThumbnailWidth(Context context) {
1977 return context.getResources().getDimensionPixelOffset(
1978 R.dimen.bookmarkThumbnailWidth);
1979 }
1980
1981 /**
1982 * Return the desired height for thumbnail screenshots, which are stored in
1983 * the database, and used on the bookmarks screen.
1984 * @param context Context for finding out the density of the screen.
1985 * @return desired height for thumbnail screenshot.
1986 */
1987 static int getDesiredThumbnailHeight(Context context) {
1988 return context.getResources().getDimensionPixelOffset(
1989 R.dimen.bookmarkThumbnailHeight);
1990 }
1991
Michael Kolb1acef692011-03-08 14:12:06 -08001992 static Bitmap createScreenshot(Tab tab, int width, int height) {
1993 if ((tab != null) && (tab.getWebView() != null)) {
1994 return createScreenshot(tab.getWebView(), width, height);
1995 }
1996 return null;
1997 }
1998
Michael Kolb8233fac2010-10-26 16:08:53 -07001999 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08002000 // We render to a bitmap 2x the desired size so that we can then
2001 // re-scale it with filtering since canvas.scale doesn't filter
2002 // This helps reduce aliasing at the cost of being slightly blurry
2003 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07002004 Picture thumbnail = view.capturePicture();
2005 if (thumbnail == null) {
2006 return null;
2007 }
John Reck5c6ac2f2011-01-05 10:18:03 -08002008 width *= filter_scale;
2009 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07002010 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
2011 Canvas canvas = new Canvas(bm);
2012 // May need to tweak these values to determine what is the
2013 // best scale factor
2014 int thumbnailWidth = thumbnail.getWidth();
2015 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08002016 float scaleFactor = 1.0f;
Michael Kolbeb95db42011-03-03 10:38:40 -08002017 if (thumbnailWidth > 0 && thumbnailHeight > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08002018 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07002019 } else {
2020 return null;
2021 }
John Reckfe49ab42010-11-16 17:09:37 -08002022
Michael Kolbeb95db42011-03-03 10:38:40 -08002023 float scaleFactorY = (float) height / (float)thumbnailHeight;
2024 if (scaleFactorY > scaleFactor) {
2025 // The picture is narrower than the requested AR
2026 // Center the thumnail and crop the sides
2027 scaleFactor = scaleFactorY;
John Reckfe49ab42010-11-16 17:09:37 -08002028 float wx = (thumbnailWidth * scaleFactor) - width;
2029 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07002030 }
2031
John Reckfe49ab42010-11-16 17:09:37 -08002032 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07002033
2034 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08002035 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
2036 height / filter_scale, true);
2037 bm.recycle();
2038 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07002039 }
2040
John Reck34ef2672011-02-10 11:30:55 -08002041 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002042 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07002043 // FIXME: Would like to make sure there is actually something to
2044 // draw, but the API for that (WebViewCore.pictureReady()) is not
2045 // currently accessible here.
2046
John Reck34ef2672011-02-10 11:30:55 -08002047 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08002048 if (view == null) {
2049 // Tab was destroyed
2050 return;
2051 }
John Reck34ef2672011-02-10 11:30:55 -08002052 final String url = tab.getUrl();
2053 final String originalUrl = view.getOriginalUrl();
2054
2055 if (TextUtils.isEmpty(url)) {
2056 return;
2057 }
2058
2059 // Only update thumbnails for web urls (http(s)://), not for
2060 // about:, javascript:, data:, etc...
2061 // Unless it is a bookmarked site, then always update
2062 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2063 return;
2064 }
2065
Michael Kolb8233fac2010-10-26 16:08:53 -07002066 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2067 getDesiredThumbnailHeight(mActivity));
2068 if (bm == null) {
2069 return;
2070 }
2071
2072 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002073 new AsyncTask<Void, Void, Void>() {
2074 @Override
2075 protected Void doInBackground(Void... unused) {
2076 Cursor cursor = null;
2077 try {
2078 // TODO: Clean this up
2079 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2080 if (cursor != null && cursor.moveToFirst()) {
2081 final ByteArrayOutputStream os =
2082 new ByteArrayOutputStream();
2083 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002084
John Reck34ef2672011-02-10 11:30:55 -08002085 ContentValues values = new ContentValues();
2086 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002087
John Reck34ef2672011-02-10 11:30:55 -08002088 do {
John Reck617fd832011-02-16 14:35:59 -08002089 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002090 cr.update(Images.CONTENT_URI, values, null, null);
2091 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002092 }
John Reck34ef2672011-02-10 11:30:55 -08002093 } catch (IllegalStateException e) {
2094 // Ignore
2095 } finally {
2096 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002097 }
John Reck34ef2672011-02-10 11:30:55 -08002098 return null;
2099 }
2100 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002101 }
2102
2103 private class Copy implements OnMenuItemClickListener {
2104 private CharSequence mText;
2105
2106 public boolean onMenuItemClick(MenuItem item) {
2107 copy(mText);
2108 return true;
2109 }
2110
2111 public Copy(CharSequence toCopy) {
2112 mText = toCopy;
2113 }
2114 }
2115
Leon Scroggins63c02662010-11-18 15:16:27 -05002116 private static class Download implements OnMenuItemClickListener {
2117 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002118 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002119 private boolean mPrivateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002120
2121 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002122 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002123 null, null, mPrivateBrowsing);
Michael Kolb8233fac2010-10-26 16:08:53 -07002124 return true;
2125 }
2126
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002127 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002128 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002129 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002130 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002131 }
2132 }
2133
Cary Clark8974d282010-11-22 10:46:05 -05002134 private static class SelectText implements OnMenuItemClickListener {
2135 private WebView mWebView;
2136
2137 public boolean onMenuItemClick(MenuItem item) {
2138 if (mWebView != null) {
2139 return mWebView.selectText();
2140 }
2141 return false;
2142 }
2143
2144 public SelectText(WebView webView) {
2145 mWebView = webView;
2146 }
2147
2148 }
2149
Michael Kolb8233fac2010-10-26 16:08:53 -07002150 /********************** TODO: UI stuff *****************************/
2151
2152 // these methods have been copied, they still need to be cleaned up
2153
2154 /****************** tabs ***************************************************/
2155
2156 // basic tab interactions:
2157
2158 // it is assumed that tabcontrol already knows about the tab
2159 protected void addTab(Tab tab) {
2160 mUi.addTab(tab);
2161 }
2162
2163 protected void removeTab(Tab tab) {
2164 mUi.removeTab(tab);
2165 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002166 mCrashRecoveryHandler.backupState();
John Reckd8c74522011-06-14 08:45:00 -07002167 if (tab.isSnapshot()) {
2168 SnapshotTab st = (SnapshotTab) tab;
2169 final Uri uri = ContentUris.withAppendedId(
2170 Snapshots.CONTENT_URI, st.getSnapshotId());
2171 final ContentResolver cr = mActivity.getContentResolver();
2172 new Thread() {
2173 @Override
2174 public void run() {
2175 cr.delete(uri, null, null);
2176 }
2177 }.start();
2178 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002179 }
2180
Michael Kolbf2055602011-04-09 17:20:03 -07002181 @Override
2182 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002183 // monkey protection against delayed start
2184 if (tab != null) {
2185 mTabControl.setCurrentTab(tab);
2186 // the tab is guaranteed to have a webview after setCurrentTab
2187 mUi.setActiveTab(tab);
2188 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002189 }
2190
2191 protected void closeEmptyChildTab() {
2192 Tab current = mTabControl.getCurrentTab();
2193 if (current != null
2194 && current.getWebView().copyBackForwardList().getSize() == 0) {
Michael Kolbc831b632011-05-11 09:30:34 -07002195 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002196 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002197 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002198 closeTab(current);
2199 }
2200 }
2201 }
2202
John Reck26b18322011-06-21 13:08:58 -07002203 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002204 // Dismiss the subwindow if applicable.
2205 dismissSubWindow(appTab);
2206 // Since we might kill the WebView, remove it from the
2207 // content view first.
2208 mUi.detachTab(appTab);
2209 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002210 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002211 // TODO: analyze why the remove and add are necessary
2212 mUi.attachTab(appTab);
2213 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002214 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002215 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002216 } else {
2217 // If the tab was the current tab, we have to attach
2218 // it to the view system again.
2219 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002220 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002221 }
2222 }
2223
2224 // Remove the sub window if it exists. Also called by TabControl when the
2225 // user clicks the 'X' to dismiss a sub window.
2226 public void dismissSubWindow(Tab tab) {
2227 removeSubWindow(tab);
2228 // dismiss the subwindow. This will destroy the WebView.
2229 tab.dismissSubWindow();
2230 getCurrentTopWebView().requestFocus();
2231 }
2232
2233 @Override
2234 public void removeSubWindow(Tab t) {
2235 if (t.getSubWebView() != null) {
2236 mUi.removeSubWindow(t.getSubViewContainer());
2237 }
2238 }
2239
2240 @Override
2241 public void attachSubWindow(Tab tab) {
2242 if (tab.getSubWebView() != null) {
2243 mUi.attachSubWindow(tab.getSubViewContainer());
2244 getCurrentTopWebView().requestFocus();
2245 }
2246 }
2247
Michael Kolb7bcafde2011-05-09 13:55:59 -07002248 // open a non inconito tab with the given url data
2249 // and set as active tab
2250 public Tab openTab(UrlData urlData) {
2251 Tab tab = createNewTab(false, true, true);
2252 if ((tab != null) && !urlData.isEmpty()) {
2253 loadUrlDataIn(tab, urlData);
2254 }
2255 return tab;
2256 }
2257
Michael Kolb843510f2010-12-09 10:51:49 -08002258 @Override
2259 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002260 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002261 }
2262
Michael Kolb8233fac2010-10-26 16:08:53 -07002263 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002264 public Tab openIncognitoTab() {
2265 return openTab(INCOGNITO_URI, true, true, false);
2266 }
2267
2268 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002269 public Tab openTab(String url, boolean incognito, boolean setActive,
2270 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002271 return openTab(url, incognito, setActive, useCurrent, null);
2272 }
2273
2274 @Override
2275 public Tab openTab(String url, Tab parent, boolean setActive,
2276 boolean useCurrent) {
2277 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2278 setActive, useCurrent, parent);
2279 }
2280
2281 public Tab openTab(String url, boolean incognito, boolean setActive,
2282 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002283 Tab tab = createNewTab(incognito, setActive, useCurrent);
2284 if (tab != null) {
John Reck5949c662011-05-27 09:52:29 -07002285 if (parent != null && parent != tab) {
2286 parent.addChildTab(tab);
2287 }
Michael Kolb519d2282011-05-09 17:03:19 -07002288 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002289 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002290 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002291 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002292 return tab;
2293 }
2294
2295 // this method will attempt to create a new tab
2296 // incognito: private browsing tab
2297 // setActive: ste tab as current tab
2298 // useCurrent: if no new tab can be created, return current tab
2299 private Tab createNewTab(boolean incognito, boolean setActive,
2300 boolean useCurrent) {
2301 Tab tab = null;
2302 if (mTabControl.canCreateNewTab()) {
2303 tab = mTabControl.createNewTab(incognito);
2304 addTab(tab);
2305 if (setActive) {
2306 setActiveTab(tab);
2307 }
2308 } else {
2309 if (useCurrent) {
2310 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002311 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002312 } else {
2313 mUi.showMaxTabsWarning();
2314 }
2315 }
2316 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002317 }
2318
John Reckd8c74522011-06-14 08:45:00 -07002319 private SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2320 SnapshotTab tab = mTabControl.createSnapshotTab(snapshotId);
2321 addTab(tab);
2322 if (setActive) {
2323 setActiveTab(tab);
2324 }
2325 return tab;
2326 }
2327
Michael Kolb8233fac2010-10-26 16:08:53 -07002328 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002329 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002330 * @return boolean True if we successfully switched to a different tab. If
2331 * the indexth tab is null, or if that tab is the same as
2332 * the current one, return false.
2333 */
2334 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002335 public boolean switchToTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002336 // hide combo view if open
2337 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002338 Tab currentTab = mTabControl.getCurrentTab();
2339 if (tab == null || tab == currentTab) {
2340 return false;
2341 }
2342 setActiveTab(tab);
2343 return true;
2344 }
2345
2346 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002347 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002348 // hide combo view if open
2349 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002350 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002351 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002352 return;
2353 }
Michael Kolbc831b632011-05-11 09:30:34 -07002354 final Tab current = mTabControl.getCurrentTab();
2355 final int pos = mTabControl.getCurrentPosition();
2356 Tab newTab = current.getParent();
2357 if (newTab == null) {
2358 newTab = mTabControl.getTab(pos + 1);
2359 if (newTab == null) {
2360 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002361 }
2362 }
Michael Kolbc831b632011-05-11 09:30:34 -07002363 if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002364 // Close window
2365 closeTab(current);
2366 }
2367 }
2368
2369 /**
2370 * Close the tab, remove its associated title bar, and adjust mTabControl's
2371 * current tab to a valid value.
2372 */
2373 @Override
2374 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002375 // hide combo view if open
2376 removeComboView();
Michael Kolb2d59c322011-01-25 13:18:55 -08002377 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002378 }
2379
Michael Kolb8233fac2010-10-26 16:08:53 -07002380 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07002381 protected void loadUrlFromContext(String url) {
2382 Tab tab = getCurrentTab();
2383 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002384 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07002385 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002386 url = UrlUtils.smartUrlFilter(url);
2387 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07002388 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07002389 }
2390 }
2391 }
2392
2393 /**
2394 * Load the URL into the given WebView and update the title bar
2395 * to reflect the new load. Call this instead of WebView.loadUrl
2396 * directly.
2397 * @param view The WebView used to load url.
2398 * @param url The URL to load.
2399 */
John Reck26b18322011-06-21 13:08:58 -07002400 protected void loadUrl(Tab tab, String url) {
2401 loadUrl(tab, url, null);
2402 }
2403
2404 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
2405 if (tab != null) {
2406 dismissSubWindow(tab);
2407 tab.loadUrl(url, headers);
2408 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002409 }
2410
2411 /**
2412 * Load UrlData into a Tab and update the title bar to reflect the new
2413 * load. Call this instead of UrlData.loadIn directly.
2414 * @param t The Tab used to load.
2415 * @param data The UrlData being loaded.
2416 */
2417 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07002418 if (data != null) {
2419 if (data.mVoiceIntent != null) {
2420 t.activateVoiceSearchMode(data.mVoiceIntent);
2421 } else {
2422 loadUrl(t, data.mUrl, data.mHeaders);
2423 }
2424 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002425 }
2426
John Reck30c714c2010-12-16 17:30:34 -08002427 @Override
2428 public void onUserCanceledSsl(Tab tab) {
2429 WebView web = tab.getWebView();
2430 // TODO: Figure out the "right" behavior
2431 if (web.canGoBack()) {
2432 web.goBack();
2433 } else {
2434 web.loadUrl(mSettings.getHomePage());
2435 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002436 }
2437
2438 void goBackOnePageOrQuit() {
2439 Tab current = mTabControl.getCurrentTab();
2440 if (current == null) {
2441 /*
2442 * Instead of finishing the activity, simply push this to the back
2443 * of the stack and let ActivityManager to choose the foreground
2444 * activity. As BrowserActivity is singleTask, it will be always the
2445 * root of the task. So we can use either true or false for
2446 * moveTaskToBack().
2447 */
2448 mActivity.moveTaskToBack(true);
2449 return;
2450 }
2451 WebView w = current.getWebView();
2452 if (w.canGoBack()) {
2453 w.goBack();
2454 } else {
2455 // Check to see if we are closing a window that was created by
2456 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002457 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002458 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002459 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002460 // Now we close the other tab
2461 closeTab(current);
2462 } else {
Michael Kolb8233fac2010-10-26 16:08:53 -07002463 /*
2464 * Instead of finishing the activity, simply push this to the back
2465 * of the stack and let ActivityManager to choose the foreground
2466 * activity. As BrowserActivity is singleTask, it will be always the
2467 * root of the task. So we can use either true or false for
2468 * moveTaskToBack().
2469 */
2470 mActivity.moveTaskToBack(true);
2471 }
2472 }
2473 }
2474
2475 /**
2476 * Feed the previously stored results strings to the BrowserProvider so that
2477 * the SearchDialog will show them instead of the standard searches.
2478 * @param result String to show on the editable line of the SearchDialog.
2479 */
2480 @Override
2481 public void showVoiceSearchResults(String result) {
2482 ContentProviderClient client = mActivity.getContentResolver()
2483 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2484 ContentProvider prov = client.getLocalContentProvider();
2485 BrowserProvider bp = (BrowserProvider) prov;
2486 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2487 client.release();
2488
2489 Bundle bundle = createGoogleSearchSourceBundle(
2490 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2491 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2492 startSearch(result, false, bundle, false);
2493 }
2494
2495 private void startSearch(String initialQuery, boolean selectInitialQuery,
2496 Bundle appSearchData, boolean globalSearch) {
2497 if (appSearchData == null) {
2498 appSearchData = createGoogleSearchSourceBundle(
2499 GOOGLE_SEARCH_SOURCE_TYPE);
2500 }
2501
2502 SearchEngine searchEngine = mSettings.getSearchEngine();
2503 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2504 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2505 }
2506 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2507 globalSearch);
2508 }
2509
2510 private Bundle createGoogleSearchSourceBundle(String source) {
2511 Bundle bundle = new Bundle();
2512 bundle.putString(Search.SOURCE, source);
2513 return bundle;
2514 }
2515
2516 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002517 * helper method for key handler
2518 * returns the current tab if it can't advance
2519 */
Michael Kolbc831b632011-05-11 09:30:34 -07002520 private Tab getNextTab() {
2521 return mTabControl.getTab(Math.min(mTabControl.getTabCount() - 1,
2522 mTabControl.getCurrentPosition() + 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002523 }
2524
2525 /**
2526 * helper method for key handler
2527 * returns the current tab if it can't advance
2528 */
Michael Kolbc831b632011-05-11 09:30:34 -07002529 private Tab getPrevTab() {
2530 return mTabControl.getTab(Math.max(0,
2531 mTabControl.getCurrentPosition() - 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002532 }
2533
2534 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002535 * handle key events in browser
2536 *
2537 * @param keyCode
2538 * @param event
2539 * @return true if handled, false to pass to super
2540 */
2541 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002542 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002543 // Even if MENU is already held down, we need to call to super to open
2544 // the IME on long press.
Michael Kolb2814a362011-05-19 15:49:41 -07002545 if (KeyEvent.KEYCODE_MENU == keyCode) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002546 if (mOptionsMenuHandler != null) {
2547 return false;
2548 } else {
2549 event.startTracking();
2550 return true;
2551 }
Michael Kolb2814a362011-05-19 15:49:41 -07002552 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002553 if (!noModifiers
2554 && ((KeyEvent.KEYCODE_MENU == keyCode)
2555 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2556 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002557 mMenuIsDown = true;
2558 return false;
2559 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002560
Cary Clark8ff8c662010-12-29 15:03:05 -05002561 WebView webView = getCurrentTopWebView();
2562 if (webView == null) return false;
2563
Cary Clark160bbb92011-01-10 11:17:07 -05002564 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2565 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002566
Michael Kolb8233fac2010-10-26 16:08:53 -07002567 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002568 case KeyEvent.KEYCODE_TAB:
2569 if (event.isCtrlPressed()) {
2570 if (event.isShiftPressed()) {
2571 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002572 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002573 } else {
2574 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002575 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002576 }
2577 return true;
2578 }
2579 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002580 case KeyEvent.KEYCODE_SPACE:
2581 // WebView/WebTextView handle the keys in the KeyDown. As
2582 // the Activity's shortcut keys are only handled when WebView
2583 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002584 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002585 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002586 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002587 pageDown();
2588 }
2589 return true;
2590 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002591 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002592 event.startTracking();
2593 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002594 case KeyEvent.KEYCODE_DPAD_LEFT:
2595 if (ctrl) {
2596 webView.goBack();
2597 return true;
2598 }
2599 break;
2600 case KeyEvent.KEYCODE_DPAD_RIGHT:
2601 if (ctrl) {
2602 webView.goForward();
2603 return true;
2604 }
2605 break;
2606 case KeyEvent.KEYCODE_A:
2607 if (ctrl) {
2608 webView.selectAll();
2609 return true;
2610 }
2611 break;
Michael Kolba4183062011-01-16 10:43:21 -08002612// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002613 case KeyEvent.KEYCODE_C:
2614 if (ctrl) {
2615 webView.copySelection();
2616 return true;
2617 }
2618 break;
Michael Kolba4183062011-01-16 10:43:21 -08002619// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002620// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002621// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002622// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002623// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002624// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002625// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002626// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002627// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002628// case KeyEvent.KEYCODE_M: // unused
2629// case KeyEvent.KEYCODE_N: // in Chrome: new window
2630// case KeyEvent.KEYCODE_O: // in Chrome: open file
2631// case KeyEvent.KEYCODE_P: // in Chrome: print page
2632// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002633// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002634// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2635 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002636 // we can't use the ctrl/shift flags, they check for
2637 // exclusive use of a modifier
2638 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002639 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002640 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002641 } else {
2642 openTabToHomePage();
2643 }
2644 return true;
2645 }
2646 break;
2647// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2648// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb1a2eba42011-03-16 16:42:49 -07002649 case KeyEvent.KEYCODE_W: // in Chrome: close tab
2650 if (ctrl) {
2651 closeCurrentTab();
2652 return true;
2653 }
2654 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002655// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2656// case KeyEvent.KEYCODE_Y: // unused
2657// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002658 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002659 // it is a regular key and webview is not null
2660 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002661 }
2662
John Recke6bf4ab2011-02-24 15:48:05 -08002663 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2664 switch(keyCode) {
2665 case KeyEvent.KEYCODE_BACK:
2666 if (mUi.showsWeb()) {
2667 bookmarksOrHistoryPicker(true);
2668 return true;
2669 }
2670 break;
2671 }
2672 return false;
2673 }
2674
Michael Kolb8233fac2010-10-26 16:08:53 -07002675 boolean onKeyUp(int keyCode, KeyEvent event) {
Michael Kolb2814a362011-05-19 15:49:41 -07002676 if (KeyEvent.KEYCODE_MENU == keyCode) {
2677 mMenuIsDown = false;
2678 if (event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002679 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002680 }
2681 }
Cary Clark160bbb92011-01-10 11:17:07 -05002682 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002683 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002684 case KeyEvent.KEYCODE_BACK:
2685 if (event.isTracking() && !event.isCanceled()) {
2686 onBackKey();
2687 return true;
2688 }
2689 break;
2690 }
2691 return false;
2692 }
2693
2694 public boolean isMenuDown() {
2695 return mMenuIsDown;
2696 }
2697
Ben Murdoch8029a772010-11-16 11:58:21 +00002698 public void setupAutoFill(Message message) {
2699 // Open the settings activity at the AutoFill profile fragment so that
2700 // the user can create a new profile. When they return, we will dispatch
2701 // the message so that we can autofill the form using their new profile.
2702 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2703 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2704 AutoFillSettingsFragment.class.getName());
2705 mAutoFillSetupMessage = message;
2706 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2707 }
John Reckb3417f02011-01-14 11:01:05 -08002708
2709 @Override
2710 public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
2711 mOptionsMenuHandler = handler;
2712 }
2713
2714 @Override
2715 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
2716 if (mOptionsMenuHandler == handler) {
2717 mOptionsMenuHandler = null;
2718 }
2719 }
2720
Narayan Kamath5119edd2011-02-23 15:49:17 +00002721 @Override
2722 public void registerDropdownChangeListener(DropdownChangeListener d) {
2723 mUi.registerDropdownChangeListener(d);
2724 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002725}