blob: faee0c7d4d6d26ede4f70a86775268a98dea4d2c [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
John Reckf33b1632011-06-04 20:00:23 -070086import java.io.ByteArrayInputStream;
Michael Kolb8233fac2010-10-26 16:08:53 -070087import java.io.ByteArrayOutputStream;
88import java.io.File;
John Reckf33b1632011-06-04 20:00:23 -070089import java.io.IOException;
Michael Kolb8233fac2010-10-26 16:08:53 -070090import java.net.URLEncoder;
91import java.util.Calendar;
92import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -080093import java.util.List;
Michael Kolb8233fac2010-10-26 16:08:53 -070094
95/**
96 * Controller for browser
97 */
98public class Controller
99 implements WebViewController, UiController {
100
101 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800102 private static final String SEND_APP_ID_EXTRA =
103 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
Michael Kolba4261fd2011-05-05 11:27:37 -0700104 private static final String INCOGNITO_URI = "browser:incognito";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800105
Michael Kolb8233fac2010-10-26 16:08:53 -0700106
107 // public message ids
108 public final static int LOAD_URL = 1001;
109 public final static int STOP_LOAD = 1002;
110
111 // Message Ids
112 private static final int FOCUS_NODE_HREF = 102;
113 private static final int RELEASE_WAKELOCK = 107;
114
115 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
116
117 private static final int OPEN_BOOKMARKS = 201;
118
119 private static final int EMPTY_MENU = -1;
120
Michael Kolb8233fac2010-10-26 16:08:53 -0700121 // activity requestCode
122 final static int PREFERENCES_PAGE = 3;
123 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000124 final static int AUTOFILL_SETUP = 5;
125
Michael Kolb8233fac2010-10-26 16:08:53 -0700126 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
127
128 // As the ids are dynamically created, we can't guarantee that they will
129 // be in sequence, so this static array maps ids to a window number.
130 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
131 { R.id.window_one_menu_id, R.id.window_two_menu_id,
132 R.id.window_three_menu_id, R.id.window_four_menu_id,
133 R.id.window_five_menu_id, R.id.window_six_menu_id,
134 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
135
136 // "source" parameter for Google search through search key
137 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
138 // "source" parameter for Google search through simplily type
139 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
140
Guang Zhu9e78f512011-05-04 11:45:11 -0700141 // "no-crash-recovery" parameter in intetnt to suppress crash recovery
142 final static String NO_CRASH_RECOVERY = "no-crash-recovery";
143
Michael Kolb8233fac2010-10-26 16:08:53 -0700144 private Activity mActivity;
145 private UI mUi;
146 private TabControl mTabControl;
147 private BrowserSettings mSettings;
148 private WebViewFactory mFactory;
John Reckb3417f02011-01-14 11:01:05 -0800149 private OptionsMenuHandler mOptionsMenuHandler = null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700150
151 private WakeLock mWakeLock;
152
153 private UrlHandler mUrlHandler;
154 private UploadHandler mUploadHandler;
155 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700156 private PageDialogsHandler mPageDialogsHandler;
157 private NetworkStateHandler mNetworkHandler;
158
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);
236
237 PowerManager pm = (PowerManager) mActivity
238 .getSystemService(Context.POWER_SERVICE);
239 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
240
241 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500242 mBookmarksObserver = new ContentObserver(mHandler) {
243 @Override
244 public void onChange(boolean selfChange) {
245 int size = mTabControl.getTabCount();
246 for (int i = 0; i < size; i++) {
247 mTabControl.getTab(i).updateBookmarkedStatus();
248 }
249 }
250
251 };
252 browser.getContentResolver().registerContentObserver(
253 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700254
255 mNetworkHandler = new NetworkStateHandler(mActivity, this);
256 // Start watching the default geolocation permissions
257 mSystemAllowGeolocationOrigins =
258 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
259 mSystemAllowGeolocationOrigins.start();
260
261 retainIconsOnStartup();
262 }
263
Patrick Scott7d50a932011-02-04 09:27:26 -0500264 void start(final Bundle icicle, final Intent intent) {
Guang Zhu9e78f512011-05-04 11:45:11 -0700265 boolean noCrashRecovery = intent.getBooleanExtra(NO_CRASH_RECOVERY, false);
266 if (icicle != null || noCrashRecovery) {
John Reck847b5322011-04-14 17:02:18 -0700267 doStart(icicle, intent);
268 } else {
269 mCrashRecoveryHandler.startRecovery(intent);
270 }
271 }
272
273 void doStart(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700274 // Unless the last browser usage was within 24 hours, destroy any
275 // remaining incognito tabs.
276
277 Calendar lastActiveDate = icicle != null ?
278 (Calendar) icicle.getSerializable("lastActiveDate") : null;
279 Calendar today = Calendar.getInstance();
280 Calendar yesterday = Calendar.getInstance();
281 yesterday.add(Calendar.DATE, -1);
282
Patrick Scott7d50a932011-02-04 09:27:26 -0500283 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700284 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800285 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700286
Patrick Scott7d50a932011-02-04 09:27:26 -0500287 // Find out if we will restore any state and remember the tab.
Michael Kolbc831b632011-05-11 09:30:34 -0700288 final long currentTabId =
Patrick Scott7d50a932011-02-04 09:27:26 -0500289 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000290
Michael Kolbc831b632011-05-11 09:30:34 -0700291 if (currentTabId == -1) {
Patrick Scott7d50a932011-02-04 09:27:26 -0500292 // Not able to restore so we go ahead and clear session cookies. We
293 // must do this before trying to login the user as we don't want to
294 // clear any session cookies set during login.
295 CookieManager.getInstance().removeSessionCookie();
296 }
297
Patrick Scottd43e75a2011-03-14 14:47:23 -0400298 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500299 new Runnable() {
300 @Override public void run() {
Michael Kolbc831b632011-05-11 09:30:34 -0700301 onPreloginFinished(icicle, intent, currentTabId, restoreIncognitoTabs);
Patrick Scott7d50a932011-02-04 09:27:26 -0500302 }
303 });
304 }
305
Michael Kolbc831b632011-05-11 09:30:34 -0700306 private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId,
Patrick Scott7d50a932011-02-04 09:27:26 -0500307 boolean restoreIncognitoTabs) {
Michael Kolbc831b632011-05-11 09:30:34 -0700308 if (currentTabId == -1) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700309 final Bundle extra = intent.getExtras();
310 // Create an initial tab.
311 // If the intent is ACTION_VIEW and data is not null, the Browser is
312 // invoked to view the content by another application. In this case,
313 // the tab will be close when exit.
314 UrlData urlData = mIntentHandler.getUrlDataFromIntent(intent);
Michael Kolb7bcafde2011-05-09 13:55:59 -0700315 Tab t = null;
316 if (urlData.isEmpty()) {
317 t = openTabToHomePage();
318 } else {
319 t = openTab(urlData);
320 }
321 if (t != null) {
322 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
323 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700324 WebView webView = t.getWebView();
325 if (extra != null) {
326 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
327 if (scale > 0 && scale <= 1000) {
328 webView.setInitialScale(scale);
329 }
330 }
John Reckd8c74522011-06-14 08:45:00 -0700331 mTabControl.loadSnapshotTabs();
332 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700333 } else {
Michael Kolbc831b632011-05-11 09:30:34 -0700334 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
Patrick Scott7d50a932011-02-04 09:27:26 -0500335 mUi.needsRestoreAllTabs());
Michael Kolb1bf23132010-11-19 12:55:12 -0800336 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700337 // TabControl.restoreState() will create a new tab even if
338 // restoring the state fails.
339 setActiveTab(mTabControl.getCurrentTab());
340 }
341 // clear up the thumbnail directory, which is no longer used;
342 // ideally this should only be run once after an upgrade from
343 // a previous version of the browser
344 new ClearThumbnails().execute(mTabControl.getThumbnailDir()
345 .listFiles());
346 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700347 String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb8233fac2010-10-26 16:08:53 -0700348 if (jsFlags.trim().length() != 0) {
349 getCurrentWebView().setJsFlags(jsFlags);
350 }
John Reck439c9a52010-12-14 10:04:39 -0800351 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
352 bookmarksOrHistoryPicker(false);
353 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700354 }
355
356 void setWebViewFactory(WebViewFactory factory) {
357 mFactory = factory;
358 }
359
Michael Kolb1514bb72010-11-22 09:11:48 -0800360 @Override
361 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700362 return mFactory;
363 }
364
365 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800366 public void onSetWebView(Tab tab, WebView view) {
367 mUi.onSetWebView(tab, view);
368 }
369
370 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800371 public void createSubWindow(Tab tab) {
372 endActionMode();
373 WebView mainView = tab.getWebView();
374 WebView subView = mFactory.createWebView((mainView == null)
375 ? false
376 : mainView.isPrivateBrowsingEnabled());
377 mUi.createSubWindow(tab, subView);
378 }
379
380 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700381 public Activity getActivity() {
382 return mActivity;
383 }
384
385 void setUi(UI ui) {
386 mUi = ui;
387 }
388
389 BrowserSettings getSettings() {
390 return mSettings;
391 }
392
393 IntentHandler getIntentHandler() {
394 return mIntentHandler;
395 }
396
397 @Override
398 public UI getUi() {
399 return mUi;
400 }
401
402 int getMaxTabs() {
403 return mActivity.getResources().getInteger(R.integer.max_tabs);
404 }
405
406 @Override
407 public TabControl getTabControl() {
408 return mTabControl;
409 }
410
Michael Kolb1bf23132010-11-19 12:55:12 -0800411 @Override
412 public List<Tab> getTabs() {
413 return mTabControl.getTabs();
414 }
415
Michael Kolb8233fac2010-10-26 16:08:53 -0700416 // Open the icon database and retain all the icons for visited sites.
Ben Murdoch9446b932010-11-25 16:20:14 +0000417 // This is done on a background thread so as not to stall startup.
Michael Kolb8233fac2010-10-26 16:08:53 -0700418 private void retainIconsOnStartup() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000419 // WebIconDatabase needs to be retrieved on the UI thread so that if
420 // it has not been created successfully yet the Handler is started on the
421 // UI thread.
422 new RetainIconsOnStartupTask(WebIconDatabase.getInstance()).execute();
423 }
424
425 private class RetainIconsOnStartupTask extends AsyncTask<Void, Void, Void> {
426 private WebIconDatabase mDb;
427
428 public RetainIconsOnStartupTask(WebIconDatabase db) {
429 mDb = db;
430 }
431
John Recka00cbbd2010-12-16 12:38:19 -0800432 @Override
Ben Murdoch9446b932010-11-25 16:20:14 +0000433 protected Void doInBackground(Void... unused) {
434 mDb.open(mActivity.getDir("icons", 0).getPath());
435 Cursor c = null;
436 try {
437 c = Browser.getAllBookmarks(mActivity.getContentResolver());
438 if (c.moveToFirst()) {
439 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
440 do {
441 String url = c.getString(urlIndex);
442 mDb.retainIconForPageUrl(url);
443 } while (c.moveToNext());
444 }
445 } catch (IllegalStateException e) {
446 Log.e(LOGTAG, "retainIconsOnStartup", e);
447 } finally {
448 if (c != null) c.close();
Michael Kolb8233fac2010-10-26 16:08:53 -0700449 }
Ben Murdoch9446b932010-11-25 16:20:14 +0000450
451 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700452 }
453 }
454
455 private void startHandler() {
456 mHandler = new Handler() {
457
458 @Override
459 public void handleMessage(Message msg) {
460 switch (msg.what) {
461 case OPEN_BOOKMARKS:
462 bookmarksOrHistoryPicker(false);
463 break;
464 case FOCUS_NODE_HREF:
465 {
466 String url = (String) msg.getData().get("url");
467 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500468 String src = (String) msg.getData().get("src");
469 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700470 if (TextUtils.isEmpty(url)) {
471 break;
472 }
473 HashMap focusNodeMap = (HashMap) msg.obj;
474 WebView view = (WebView) focusNodeMap.get("webview");
475 // Only apply the action if the top window did not change.
476 if (getCurrentTopWebView() != view) {
477 break;
478 }
479 switch (msg.arg1) {
480 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -0700481 loadUrlFromContext(getCurrentTopWebView(), url);
482 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500483 case R.id.view_image_context_menu_id:
484 loadUrlFromContext(getCurrentTopWebView(), src);
485 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500486 case R.id.open_newtab_context_menu_id:
487 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -0700488 openTab(url, parent,
489 !mSettings.openInBackground(), true);
Leon Scroggins026f2542010-11-22 13:26:12 -0500490 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700491 case R.id.copy_link_context_menu_id:
492 copy(url);
493 break;
494 case R.id.save_link_context_menu_id:
495 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500496 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000497 mActivity, url, null, null, null,
498 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700499 break;
500 }
501 break;
502 }
503
504 case LOAD_URL:
505 loadUrlFromContext(getCurrentTopWebView(), (String) msg.obj);
506 break;
507
508 case STOP_LOAD:
509 stopLoading();
510 break;
511
512 case RELEASE_WAKELOCK:
513 if (mWakeLock.isHeld()) {
514 mWakeLock.release();
515 // if we reach here, Browser should be still in the
516 // background loading after WAKELOCK_TIMEOUT (5-min).
517 // To avoid burning the battery, stop loading.
518 mTabControl.stopAllLoading();
519 }
520 break;
521
522 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800523 Tab tab = (Tab) msg.obj;
524 if (tab != null) {
525 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700526 }
527 break;
528 }
529 }
530 };
531
532 }
533
Michael Kolbba99c5d2010-11-29 14:57:41 -0800534 @Override
535 public void shareCurrentPage() {
536 shareCurrentPage(mTabControl.getCurrentTab());
537 }
538
539 private void shareCurrentPage(Tab tab) {
540 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800541 sharePage(mActivity, tab.getTitle(),
542 tab.getUrl(), tab.getFavicon(),
543 createScreenshot(tab.getWebView(),
544 getDesiredThumbnailWidth(mActivity),
545 getDesiredThumbnailHeight(mActivity)));
546 }
547 }
548
Michael Kolb8233fac2010-10-26 16:08:53 -0700549 /**
550 * Share a page, providing the title, url, favicon, and a screenshot. Uses
551 * an {@link Intent} to launch the Activity chooser.
552 * @param c Context used to launch a new Activity.
553 * @param title Title of the page. Stored in the Intent with
554 * {@link Intent#EXTRA_SUBJECT}
555 * @param url URL of the page. Stored in the Intent with
556 * {@link Intent#EXTRA_TEXT}
557 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
558 * with {@link Browser#EXTRA_SHARE_FAVICON}
559 * @param screenshot Bitmap of a screenshot of the page. Stored in the
560 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
561 */
562 static final void sharePage(Context c, String title, String url,
563 Bitmap favicon, Bitmap screenshot) {
564 Intent send = new Intent(Intent.ACTION_SEND);
565 send.setType("text/plain");
566 send.putExtra(Intent.EXTRA_TEXT, url);
567 send.putExtra(Intent.EXTRA_SUBJECT, title);
568 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
569 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
570 try {
571 c.startActivity(Intent.createChooser(send, c.getString(
572 R.string.choosertitle_sharevia)));
573 } catch(android.content.ActivityNotFoundException ex) {
574 // if no app handles it, do nothing
575 }
576 }
577
578 private void copy(CharSequence text) {
579 ClipboardManager cm = (ClipboardManager) mActivity
580 .getSystemService(Context.CLIPBOARD_SERVICE);
581 cm.setText(text);
582 }
583
584 // lifecycle
585
586 protected void onConfgurationChanged(Configuration config) {
587 mConfigChanged = true;
588 if (mPageDialogsHandler != null) {
589 mPageDialogsHandler.onConfigurationChanged(config);
590 }
591 mUi.onConfigurationChanged(config);
592 }
593
594 @Override
595 public void handleNewIntent(Intent intent) {
596 mIntentHandler.onNewIntent(intent);
597 }
598
599 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800600 if (mUi.isCustomViewShowing()) {
601 hideCustomView();
602 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700603 if (mActivityPaused) {
604 Log.e(LOGTAG, "BrowserActivity is already paused.");
605 return;
606 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700607 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800608 Tab tab = mTabControl.getCurrentTab();
609 if (tab != null) {
610 tab.pause();
611 if (!pauseWebViewTimers(tab)) {
612 mWakeLock.acquire();
613 mHandler.sendMessageDelayed(mHandler
614 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
615 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700616 }
617 mUi.onPause();
618 mNetworkHandler.onPause();
619
620 WebView.disablePlatformNotifications();
John Reck378a4102011-06-09 16:23:01 -0700621 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -0700622 }
623
John Reckaed9c542011-05-27 16:08:53 -0700624 void onSaveInstanceState(Bundle outState, boolean saveImages) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700625 // the default implementation requires each view to have an id. As the
626 // browser handles the state itself and it doesn't use id for the views,
627 // don't call the default implementation. Otherwise it will trigger the
628 // warning like this, "couldn't save which view has focus because the
629 // focused view XXX has no id".
630
631 // Save all the tabs
John Reckaed9c542011-05-27 16:08:53 -0700632 mTabControl.saveState(outState, saveImages);
Michael Kolb8233fac2010-10-26 16:08:53 -0700633 // Save time so that we know how old incognito tabs (if any) are.
634 outState.putSerializable("lastActiveDate", Calendar.getInstance());
635 }
636
637 void onResume() {
638 if (!mActivityPaused) {
639 Log.e(LOGTAG, "BrowserActivity is already resumed.");
640 return;
641 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700642 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800643 Tab current = mTabControl.getCurrentTab();
644 if (current != null) {
645 current.resume();
646 resumeWebViewTimers(current);
647 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700648 if (mWakeLock.isHeld()) {
649 mHandler.removeMessages(RELEASE_WAKELOCK);
650 mWakeLock.release();
651 }
652 mUi.onResume();
653 mNetworkHandler.onResume();
654 WebView.enablePlatformNotifications();
655 }
656
Michael Kolb70976932010-11-30 11:34:01 -0800657 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800658 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800659 * @param tab guaranteed non-null
660 */
661 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700662 boolean inLoad = tab.inPageLoad();
663 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
664 CookieSyncManager.getInstance().startSync();
665 WebView w = tab.getWebView();
666 if (w != null) {
667 w.resumeTimers();
668 }
669 }
670 }
671
Michael Kolb70976932010-11-30 11:34:01 -0800672 /**
673 * Pause all WebView timers using the WebView of the given tab
674 * @param tab
675 * @return true if the timers are paused or tab is null
676 */
677 private boolean pauseWebViewTimers(Tab tab) {
678 if (tab == null) {
679 return true;
680 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700681 CookieSyncManager.getInstance().stopSync();
682 WebView w = getCurrentWebView();
683 if (w != null) {
684 w.pauseTimers();
685 }
686 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700687 }
Michael Kolb70976932010-11-30 11:34:01 -0800688 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700689 }
690
691 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800692 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700693 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
694 mUploadHandler = null;
695 }
696 if (mTabControl == null) return;
697 mUi.onDestroy();
698 // Remove the current tab and sub window
699 Tab t = mTabControl.getCurrentTab();
700 if (t != null) {
701 dismissSubWindow(t);
702 removeTab(t);
703 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500704 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700705 // Destroy all the tabs
706 mTabControl.destroy();
707 WebIconDatabase.getInstance().close();
708 // Stop watching the default geolocation permissions
709 mSystemAllowGeolocationOrigins.stop();
710 mSystemAllowGeolocationOrigins = null;
711 }
712
713 protected boolean isActivityPaused() {
714 return mActivityPaused;
715 }
716
717 protected void onLowMemory() {
718 mTabControl.freeMemory();
719 }
720
721 @Override
722 public boolean shouldShowErrorConsole() {
723 return mShouldShowErrorConsole;
724 }
725
726 protected void setShouldShowErrorConsole(boolean show) {
727 if (show == mShouldShowErrorConsole) {
728 // Nothing to do.
729 return;
730 }
731 mShouldShowErrorConsole = show;
732 Tab t = mTabControl.getCurrentTab();
733 if (t == null) {
734 // There is no current tab so we cannot toggle the error console
735 return;
736 }
737 mUi.setShouldShowErrorConsole(t, show);
738 }
739
740 @Override
741 public void stopLoading() {
742 mLoadStopped = true;
743 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700744 WebView w = getCurrentTopWebView();
745 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700746 mUi.onPageStopped(tab);
747 }
748
749 boolean didUserStopLoading() {
750 return mLoadStopped;
751 }
752
753 // WebViewController
754
755 @Override
John Reck324d4402011-01-11 16:56:42 -0800756 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700757
758 // We've started to load a new page. If there was a pending message
759 // to save a screenshot then we will now take the new page and save
760 // an incorrect screenshot. Therefore, remove any pending thumbnail
761 // messages from the queue.
762 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800763 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700764
765 // reset sync timer to avoid sync starts during loading a page
766 CookieSyncManager.getInstance().resetSync();
767
768 if (!mNetworkHandler.isNetworkUp()) {
769 view.setNetworkAvailable(false);
770 }
771
772 // when BrowserActivity just starts, onPageStarted may be called before
773 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
774 // to start the timer. As we won't switch tabs while an activity is in
775 // pause state, we can ensure calling resume and pause in pair.
776 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800777 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700778 }
779 mLoadStopped = false;
780 if (!mNetworkHandler.isNetworkUp()) {
781 mNetworkHandler.createAndShowNetworkDialog();
782 }
783 endActionMode();
784
John Reck30c714c2010-12-16 17:30:34 -0800785 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700786
John Reck324d4402011-01-11 16:56:42 -0800787 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700788 // update the bookmark database for favicon
789 maybeUpdateFavicon(tab, null, url, favicon);
790
791 Performance.tracePageStart(url);
792
793 // Performance probe
794 if (false) {
795 Performance.onPageStarted();
796 }
797
798 }
799
800 @Override
John Reck324d4402011-01-11 16:56:42 -0800801 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800802 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800803 if (!tab.isPrivateBrowsingEnabled()
John Reckd8c74522011-06-14 08:45:00 -0700804 && !TextUtils.isEmpty(tab.getUrl())
805 && !tab.isSnapshot()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700806 if (tab.inForeground() && !didUserStopLoading()
807 || !tab.inForeground()) {
808 // Only update the bookmark screenshot if the user did not
809 // cancel the load early.
810 mHandler.sendMessageDelayed(mHandler.obtainMessage(
John Reck34ef2672011-02-10 11:30:55 -0800811 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
Michael Kolb8233fac2010-10-26 16:08:53 -0700812 500);
813 }
814 }
815 // pause the WebView timer and release the wake lock if it is finished
816 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800817 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700818 if (mWakeLock.isHeld()) {
819 mHandler.removeMessages(RELEASE_WAKELOCK);
820 mWakeLock.release();
821 }
822 }
823 // Performance probe
824 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800825 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700826 }
827
828 Performance.tracePageFinished();
829 }
830
831 @Override
John Reck30c714c2010-12-16 17:30:34 -0800832 public void onProgressChanged(Tab tab) {
833 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700834
835 if (newProgress == 100) {
836 CookieSyncManager.getInstance().sync();
837 // onProgressChanged() may continue to be called after the main
838 // frame has finished loading, as any remaining sub frames continue
839 // to load. We'll only get called once though with newProgress as
840 // 100 when everything is loaded. (onPageFinished is called once
841 // when the main frame completes loading regardless of the state of
842 // any sub frames so calls to onProgressChanges may continue after
843 // onPageFinished has executed)
844 if (mInLoad) {
845 mInLoad = false;
846 updateInLoadMenuItems(mCachedMenu);
847 }
848 } else {
849 if (!mInLoad) {
850 // onPageFinished may have already been called but a subframe is
851 // still loading and updating the progress. Reset mInLoad and
852 // update the menu items.
853 mInLoad = true;
854 updateInLoadMenuItems(mCachedMenu);
855 }
856 }
John Reck30c714c2010-12-16 17:30:34 -0800857 mUi.onProgressChanged(tab);
858 }
859
860 @Override
861 public void onUpdatedLockIcon(Tab tab) {
862 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700863 }
864
865 @Override
866 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800867 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800868 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800869 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700870 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
871 return;
872 }
873 // Update the title in the history database if not in private browsing mode
874 if (!tab.isPrivateBrowsingEnabled()) {
John Reck0ebd3ac2010-12-09 11:14:04 -0800875 mDataController.updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700876 }
877 }
878
879 @Override
880 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800881 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700882 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
883 }
884
885 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800886 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
887 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700888 }
889
890 @Override
891 public boolean shouldOverrideKeyEvent(KeyEvent event) {
892 if (mMenuIsDown) {
893 // only check shortcut key when MENU is held
894 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
895 event);
896 } else {
897 return false;
898 }
899 }
900
901 @Override
902 public void onUnhandledKeyEvent(KeyEvent event) {
903 if (!isActivityPaused()) {
904 if (event.getAction() == KeyEvent.ACTION_DOWN) {
905 mActivity.onKeyDown(event.getKeyCode(), event);
906 } else {
907 mActivity.onKeyUp(event.getKeyCode(), event);
908 }
909 }
910 }
911
912 @Override
John Reck324d4402011-01-11 16:56:42 -0800913 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700914 // Don't save anything in private browsing mode
915 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800916 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700917
John Reck324d4402011-01-11 16:56:42 -0800918 if (TextUtils.isEmpty(url)
919 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700920 return;
921 }
John Reck0ebd3ac2010-12-09 11:14:04 -0800922 mDataController.updateVisitedHistory(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700923 WebIconDatabase.getInstance().retainIconForPageUrl(url);
John Reck847b5322011-04-14 17:02:18 -0700924 if (!mActivityPaused) {
925 // Since we clear the state in onPause, don't backup the current
926 // state if we are already paused
927 mCrashRecoveryHandler.backupState();
928 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700929 }
930
931 @Override
932 public void getVisitedHistory(final ValueCallback<String[]> callback) {
933 AsyncTask<Void, Void, String[]> task =
934 new AsyncTask<Void, Void, String[]>() {
935 @Override
936 public String[] doInBackground(Void... unused) {
937 return Browser.getVisitedHistory(mActivity.getContentResolver());
938 }
939 @Override
940 public void onPostExecute(String[] result) {
941 callback.onReceiveValue(result);
942 }
943 };
944 task.execute();
945 }
946
947 @Override
948 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
949 final HttpAuthHandler handler, final String host,
950 final String realm) {
951 String username = null;
952 String password = null;
953
954 boolean reuseHttpAuthUsernamePassword
955 = handler.useHttpAuthUsernamePassword();
956
957 if (reuseHttpAuthUsernamePassword && view != null) {
958 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
959 if (credentials != null && credentials.length == 2) {
960 username = credentials[0];
961 password = credentials[1];
962 }
963 }
964
965 if (username != null && password != null) {
966 handler.proceed(username, password);
967 } else {
968 if (tab.inForeground()) {
969 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
970 } else {
971 handler.cancel();
972 }
973 }
974 }
975
976 @Override
977 public void onDownloadStart(Tab tab, String url, String userAgent,
978 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000979 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -0500980 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000981 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
982 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700983 // This Tab was opened for the sole purpose of downloading a
984 // file. Remove it.
985 if (tab == mTabControl.getCurrentTab()) {
986 // In this case, the Tab is still on top.
987 goBackOnePageOrQuit();
988 } else {
989 // In this case, it is not.
990 closeTab(tab);
991 }
992 }
993 }
994
995 @Override
996 public Bitmap getDefaultVideoPoster() {
997 return mUi.getDefaultVideoPoster();
998 }
999
1000 @Override
1001 public View getVideoLoadingProgressView() {
1002 return mUi.getVideoLoadingProgressView();
1003 }
1004
1005 @Override
1006 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1007 SslError error) {
1008 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1009 }
1010
Patrick Scott92066772011-03-10 08:46:27 -05001011 @Override
1012 public void showAutoLogin(Tab tab) {
1013 assert tab.inForeground();
1014 // Update the title bar to show the auto-login request.
1015 mUi.showAutoLogin(tab);
1016 }
1017
1018 @Override
1019 public void hideAutoLogin(Tab tab) {
1020 assert tab.inForeground();
1021 mUi.hideAutoLogin(tab);
1022 }
1023
Michael Kolb8233fac2010-10-26 16:08:53 -07001024 // helper method
1025
1026 /*
1027 * Update the favorites icon if the private browsing isn't enabled and the
1028 * icon is valid.
1029 */
1030 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1031 final String url, Bitmap favicon) {
1032 if (favicon == null) {
1033 return;
1034 }
1035 if (!tab.isPrivateBrowsingEnabled()) {
1036 Bookmarks.updateFavicon(mActivity
1037 .getContentResolver(), originalUrl, url, favicon);
1038 }
1039 }
1040
Leon Scroggins4cd97792010-12-03 15:31:56 -05001041 @Override
1042 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001043 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001044 mUi.bookmarkedStatusHasChanged(tab);
1045 }
1046
Michael Kolb8233fac2010-10-26 16:08:53 -07001047 // end WebViewController
1048
1049 protected void pageUp() {
1050 getCurrentTopWebView().pageUp(false);
1051 }
1052
1053 protected void pageDown() {
1054 getCurrentTopWebView().pageDown(false);
1055 }
1056
1057 // callback from phone title bar
1058 public void editUrl() {
1059 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001060 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001061 }
1062
Michael Kolbcfa3af52010-12-14 10:36:11 -08001063 public void startVoiceSearch() {
1064 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1065 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1066 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1067 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1068 mActivity.getComponentName().flattenToString());
1069 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001070 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001071 mActivity.startActivity(intent);
1072 }
1073
Michael Kolb11d19782011-03-20 10:17:40 -07001074 @Override
1075 public void activateVoiceSearchMode(String title, List<String> results) {
1076 mUi.showVoiceTitleBar(title, results);
Michael Kolb8233fac2010-10-26 16:08:53 -07001077 }
1078
1079 public void revertVoiceSearchMode(Tab tab) {
1080 mUi.revertVoiceTitleBar(tab);
1081 }
1082
Michael Kolb736990c2011-03-20 10:01:20 -07001083 public boolean supportsVoiceSearch() {
John Reck35e9dd62011-04-25 09:01:54 -07001084 SearchEngine searchEngine = getSettings().getSearchEngine();
Michael Kolb736990c2011-03-20 10:01:20 -07001085 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1086 }
1087
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001088 public void showCustomView(Tab tab, View view, int requestedOrientation,
Michael Kolb8233fac2010-10-26 16:08:53 -07001089 WebChromeClient.CustomViewCallback callback) {
1090 if (tab.inForeground()) {
1091 if (mUi.isCustomViewShowing()) {
1092 callback.onCustomViewHidden();
1093 return;
1094 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001095 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001096 // Save the menu state and set it to empty while the custom
1097 // view is showing.
1098 mOldMenuState = mMenuState;
1099 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001100 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001101 }
1102 }
1103
1104 @Override
1105 public void hideCustomView() {
1106 if (mUi.isCustomViewShowing()) {
1107 mUi.onHideCustomView();
1108 // Reset the old menu state.
1109 mMenuState = mOldMenuState;
1110 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001111 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001112 }
1113 }
1114
1115 protected void onActivityResult(int requestCode, int resultCode,
1116 Intent intent) {
1117 if (getCurrentTopWebView() == null) return;
1118 switch (requestCode) {
1119 case PREFERENCES_PAGE:
1120 if (resultCode == Activity.RESULT_OK && intent != null) {
1121 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001122 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001123 mTabControl.removeParentChildRelationShips();
1124 }
1125 }
1126 break;
1127 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001128 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001129 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001130 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001131 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001132 case AUTOFILL_SETUP:
1133 // Determine whether a profile was actually set up or not
1134 // and if so, send the message back to the WebTextView to
1135 // fill the form with the new profile.
1136 if (getSettings().getAutoFillProfile() != null) {
1137 mAutoFillSetupMessage.sendToTarget();
1138 mAutoFillSetupMessage = null;
1139 }
1140 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001141 default:
1142 break;
1143 }
1144 getCurrentTopWebView().requestFocus();
1145 }
1146
1147 /**
1148 * Open the Go page.
1149 * @param startWithHistory If true, open starting on the history tab.
1150 * Otherwise, start with the bookmarks tab.
1151 */
1152 @Override
1153 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1154 if (mTabControl.getCurrentWebView() == null) {
1155 return;
1156 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001157 // clear action mode
1158 if (isInCustomActionMode()) {
1159 endActionMode();
1160 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001161 Bundle extras = new Bundle();
1162 // Disable opening in a new window if we have maxed out the windows
1163 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1164 !mTabControl.canCreateNewTab());
1165 mUi.showComboView(startWithHistory, extras);
1166 }
1167
1168 // combo view callbacks
1169
1170 /**
1171 * callback from ComboPage when clear history is requested
1172 */
1173 public void onRemoveParentChildRelationships() {
1174 mTabControl.removeParentChildRelationShips();
1175 }
1176
1177 /**
1178 * callback from ComboPage when bookmark/history selection
1179 */
1180 @Override
1181 public void onUrlSelected(String url, boolean newTab) {
1182 removeComboView();
1183 if (!TextUtils.isEmpty(url)) {
1184 if (newTab) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07001185 final Tab parent = mTabControl.getCurrentTab();
1186 openTab(url,
1187 (parent != null) && parent.isPrivateBrowsingEnabled(),
1188 !mSettings.openInBackground(),
1189 true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001190 } else {
1191 final Tab currentTab = mTabControl.getCurrentTab();
1192 dismissSubWindow(currentTab);
1193 loadUrl(getCurrentTopWebView(), url);
1194 }
1195 }
1196 }
1197
1198 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07001199 * dismiss the ComboPage
1200 */
1201 @Override
1202 public void removeComboView() {
1203 mUi.hideComboView();
1204 }
1205
1206 // active tabs page handling
1207
1208 protected void showActiveTabsPage() {
1209 mMenuState = EMPTY_MENU;
1210 mUi.showActiveTabsPage();
1211 }
1212
1213 /**
1214 * Remove the active tabs page.
1215 * @param needToAttach If true, the active tabs page did not attach a tab
1216 * to the content view, so we need to do that here.
1217 */
1218 @Override
1219 public void removeActiveTabsPage(boolean needToAttach) {
1220 mMenuState = R.id.MAIN_MENU;
1221 mUi.removeActiveTabsPage();
1222 if (needToAttach) {
1223 setActiveTab(mTabControl.getCurrentTab());
1224 }
1225 getCurrentTopWebView().requestFocus();
1226 }
1227
1228 // key handling
1229 protected void onBackKey() {
1230 if (!mUi.onBackKey()) {
1231 WebView subwindow = mTabControl.getCurrentSubWindow();
1232 if (subwindow != null) {
1233 if (subwindow.canGoBack()) {
1234 subwindow.goBack();
1235 } else {
1236 dismissSubWindow(mTabControl.getCurrentTab());
1237 }
1238 } else {
1239 goBackOnePageOrQuit();
1240 }
1241 }
1242 }
1243
Michael Kolb4bd767d2011-05-27 11:33:55 -07001244 protected boolean onMenuKey() {
1245 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001246 }
1247
Michael Kolb8233fac2010-10-26 16:08:53 -07001248 // menu handling and state
1249 // TODO: maybe put into separate handler
1250
1251 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckb3417f02011-01-14 11:01:05 -08001252 if (mOptionsMenuHandler != null) {
1253 return mOptionsMenuHandler.onCreateOptionsMenu(menu);
1254 }
1255
John Reckd73c5a22010-12-22 10:22:50 -08001256 if (mMenuState == EMPTY_MENU) {
1257 return false;
1258 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001259 MenuInflater inflater = mActivity.getMenuInflater();
1260 inflater.inflate(R.menu.browser, menu);
1261 updateInLoadMenuItems(menu);
1262 // hold on to the menu reference here; it is used by the page callbacks
1263 // to update the menu based on loading state
1264 mCachedMenu = menu;
1265 return true;
1266 }
1267
1268 protected void onCreateContextMenu(ContextMenu menu, View v,
1269 ContextMenuInfo menuInfo) {
1270 if (v instanceof TitleBarBase) {
1271 return;
1272 }
1273 if (!(v instanceof WebView)) {
1274 return;
1275 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001276 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001277 WebView.HitTestResult result = webview.getHitTestResult();
1278 if (result == null) {
1279 return;
1280 }
1281
1282 int type = result.getType();
1283 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1284 Log.w(LOGTAG,
1285 "We should not show context menu when nothing is touched");
1286 return;
1287 }
1288 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1289 // let TextView handles context menu
1290 return;
1291 }
1292
1293 // Note, http://b/issue?id=1106666 is requesting that
1294 // an inflated menu can be used again. This is not available
1295 // yet, so inflate each time (yuk!)
1296 MenuInflater inflater = mActivity.getMenuInflater();
1297 inflater.inflate(R.menu.browsercontext, menu);
1298
1299 // Show the correct menu group
1300 final String extra = result.getExtra();
1301 menu.setGroupVisible(R.id.PHONE_MENU,
1302 type == WebView.HitTestResult.PHONE_TYPE);
1303 menu.setGroupVisible(R.id.EMAIL_MENU,
1304 type == WebView.HitTestResult.EMAIL_TYPE);
1305 menu.setGroupVisible(R.id.GEO_MENU,
1306 type == WebView.HitTestResult.GEO_TYPE);
1307 menu.setGroupVisible(R.id.IMAGE_MENU,
1308 type == WebView.HitTestResult.IMAGE_TYPE
1309 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1310 menu.setGroupVisible(R.id.ANCHOR_MENU,
1311 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1312 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001313 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1314 || type == WebView.HitTestResult.PHONE_TYPE
1315 || type == WebView.HitTestResult.EMAIL_TYPE
1316 || type == WebView.HitTestResult.GEO_TYPE;
1317 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1318 if (hitText) {
1319 menu.findItem(R.id.select_text_menu_id)
1320 .setOnMenuItemClickListener(new SelectText(webview));
1321 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001322 // Setup custom handling depending on the type
1323 switch (type) {
1324 case WebView.HitTestResult.PHONE_TYPE:
1325 menu.setHeaderTitle(Uri.decode(extra));
1326 menu.findItem(R.id.dial_context_menu_id).setIntent(
1327 new Intent(Intent.ACTION_VIEW, Uri
1328 .parse(WebView.SCHEME_TEL + extra)));
1329 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1330 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1331 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1332 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1333 addIntent);
1334 menu.findItem(R.id.copy_phone_context_menu_id)
1335 .setOnMenuItemClickListener(
1336 new Copy(extra));
1337 break;
1338
1339 case WebView.HitTestResult.EMAIL_TYPE:
1340 menu.setHeaderTitle(extra);
1341 menu.findItem(R.id.email_context_menu_id).setIntent(
1342 new Intent(Intent.ACTION_VIEW, Uri
1343 .parse(WebView.SCHEME_MAILTO + extra)));
1344 menu.findItem(R.id.copy_mail_context_menu_id)
1345 .setOnMenuItemClickListener(
1346 new Copy(extra));
1347 break;
1348
1349 case WebView.HitTestResult.GEO_TYPE:
1350 menu.setHeaderTitle(extra);
1351 menu.findItem(R.id.map_context_menu_id).setIntent(
1352 new Intent(Intent.ACTION_VIEW, Uri
1353 .parse(WebView.SCHEME_GEO
1354 + URLEncoder.encode(extra))));
1355 menu.findItem(R.id.copy_geo_context_menu_id)
1356 .setOnMenuItemClickListener(
1357 new Copy(extra));
1358 break;
1359
1360 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1361 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001362 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001363 // decide whether to show the open link in new tab option
1364 boolean showNewTab = mTabControl.canCreateNewTab();
1365 MenuItem newTabItem
1366 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001367 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001368 ? R.string.contextmenu_openlink_newwindow_background
1369 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001370 newTabItem.setVisible(showNewTab);
1371 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001372 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1373 newTabItem.setOnMenuItemClickListener(
1374 new MenuItem.OnMenuItemClickListener() {
1375 @Override
1376 public boolean onMenuItemClick(MenuItem item) {
1377 final HashMap<String, WebView> hrefMap =
1378 new HashMap<String, WebView>();
1379 hrefMap.put("webview", webview);
1380 final Message msg = mHandler.obtainMessage(
1381 FOCUS_NODE_HREF,
1382 R.id.open_newtab_context_menu_id,
1383 0, hrefMap);
1384 webview.requestFocusNodeHref(msg);
1385 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001386 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001387 });
1388 } else {
1389 newTabItem.setOnMenuItemClickListener(
1390 new MenuItem.OnMenuItemClickListener() {
1391 @Override
1392 public boolean onMenuItemClick(MenuItem item) {
1393 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001394 openTab(extra, parent,
1395 !mSettings.openInBackground(),
1396 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001397 return true;
1398 }
1399 });
1400 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001401 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001402 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1403 break;
1404 }
1405 // otherwise fall through to handle image part
1406 case WebView.HitTestResult.IMAGE_TYPE:
1407 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1408 menu.setHeaderTitle(extra);
1409 }
1410 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1411 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1412 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001413 setOnMenuItemClickListener(
1414 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001415 menu.findItem(R.id.set_wallpaper_context_menu_id).
1416 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1417 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001418 break;
1419
1420 default:
1421 Log.w(LOGTAG, "We should not get here.");
1422 break;
1423 }
1424 //update the ui
1425 mUi.onContextMenuCreated(menu);
1426 }
1427
1428 /**
1429 * As the menu can be open when loading state changes
1430 * we must manually update the state of the stop/reload menu
1431 * item
1432 */
1433 private void updateInLoadMenuItems(Menu menu) {
1434 if (menu == null) {
1435 return;
1436 }
1437 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1438 MenuItem src = mInLoad ?
1439 menu.findItem(R.id.stop_menu_id):
1440 menu.findItem(R.id.reload_menu_id);
1441 if (src != null) {
1442 dest.setIcon(src.getIcon());
1443 dest.setTitle(src.getTitle());
1444 }
1445 }
1446
John Reckb3417f02011-01-14 11:01:05 -08001447 boolean onPrepareOptionsMenu(Menu menu) {
1448 if (mOptionsMenuHandler != null) {
1449 return mOptionsMenuHandler.onPrepareOptionsMenu(menu);
1450 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001451 // Note: setVisible will decide whether an item is visible; while
1452 // setEnabled() will decide whether an item is enabled, which also means
1453 // whether the matching shortcut key will function.
1454 switch (mMenuState) {
1455 case EMPTY_MENU:
1456 if (mCurrentMenuState != mMenuState) {
1457 menu.setGroupVisible(R.id.MAIN_MENU, false);
1458 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1459 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1460 }
1461 break;
1462 default:
1463 if (mCurrentMenuState != mMenuState) {
1464 menu.setGroupVisible(R.id.MAIN_MENU, true);
1465 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1466 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1467 }
1468 final WebView w = getCurrentTopWebView();
1469 boolean canGoBack = false;
1470 boolean canGoForward = false;
1471 boolean isHome = false;
1472 if (w != null) {
1473 canGoBack = w.canGoBack();
1474 canGoForward = w.canGoForward();
1475 isHome = mSettings.getHomePage().equals(w.getUrl());
1476 }
1477 final MenuItem back = menu.findItem(R.id.back_menu_id);
1478 back.setEnabled(canGoBack);
1479
1480 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1481 home.setEnabled(!isHome);
1482
1483 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1484 forward.setEnabled(canGoForward);
1485
1486 // decide whether to show the share link option
1487 PackageManager pm = mActivity.getPackageManager();
1488 Intent send = new Intent(Intent.ACTION_SEND);
1489 send.setType("text/plain");
1490 ResolveInfo ri = pm.resolveActivity(send,
1491 PackageManager.MATCH_DEFAULT_ONLY);
1492 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1493
John Reck35e9dd62011-04-25 09:01:54 -07001494 boolean isNavDump = mSettings.enableNavDump();
Michael Kolb8233fac2010-10-26 16:08:53 -07001495 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1496 nav.setVisible(isNavDump);
1497 nav.setEnabled(isNavDump);
1498
John Reck35e9dd62011-04-25 09:01:54 -07001499 boolean showDebugSettings = mSettings.isDebugEnabled();
Michael Kolb8233fac2010-10-26 16:08:53 -07001500 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1501 counter.setVisible(showDebugSettings);
1502 counter.setEnabled(showDebugSettings);
1503
John Reckb3417f02011-01-14 11:01:05 -08001504 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1505 newtab.setEnabled(getTabControl().canCreateNewTab());
Michael Kolb8233fac2010-10-26 16:08:53 -07001506
Leon Scroggins81983762011-02-11 15:17:36 -05001507 MenuItem archive = menu.findItem(R.id.save_webarchive_menu_id);
John Reck51d8bad2011-02-28 15:47:47 -08001508 Tab tab = getTabControl().getCurrentTab();
1509 String url = tab != null ? tab.getUrl() : null;
1510 archive.setVisible(!TextUtils.isEmpty(url)
1511 && !url.endsWith(".webarchivexml"));
Michael Kolb8233fac2010-10-26 16:08:53 -07001512 break;
1513 }
1514 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001515 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001516 }
1517
1518 public boolean onOptionsItemSelected(MenuItem item) {
John Reckb3417f02011-01-14 11:01:05 -08001519 if (mOptionsMenuHandler != null &&
1520 mOptionsMenuHandler.onOptionsItemSelected(item)) {
1521 return true;
1522 }
1523
Michael Kolb8233fac2010-10-26 16:08:53 -07001524 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1525 // menu remains active, so ensure comboview is dismissed
1526 // if main menu option is selected
1527 removeComboView();
1528 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001529 if (null == getCurrentTopWebView()) {
1530 return false;
1531 }
1532 if (mMenuIsDown) {
1533 // The shortcut action consumes the MENU. Even if it is still down,
1534 // it won't trigger the next shortcut action. In the case of the
1535 // shortcut action triggering a new activity, like Bookmarks, we
1536 // won't get onKeyUp for MENU. So it is important to reset it here.
1537 mMenuIsDown = false;
1538 }
1539 switch (item.getItemId()) {
1540 // -- Main menu
1541 case R.id.new_tab_menu_id:
1542 openTabToHomePage();
1543 break;
1544
1545 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001546 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001547 break;
1548
1549 case R.id.goto_menu_id:
1550 editUrl();
1551 break;
1552
1553 case R.id.bookmarks_menu_id:
1554 bookmarksOrHistoryPicker(false);
1555 break;
1556
1557 case R.id.active_tabs_menu_id:
1558 showActiveTabsPage();
1559 break;
1560
1561 case R.id.add_bookmark_menu_id:
John Reck3ffc5ca2011-06-10 15:56:06 -07001562 bookmarkCurrentPage(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001563 break;
1564
1565 case R.id.stop_reload_menu_id:
1566 if (mInLoad) {
1567 stopLoading();
1568 } else {
1569 getCurrentTopWebView().reload();
1570 }
1571 break;
1572
1573 case R.id.back_menu_id:
1574 getCurrentTopWebView().goBack();
1575 break;
1576
1577 case R.id.forward_menu_id:
1578 getCurrentTopWebView().goForward();
1579 break;
1580
1581 case R.id.close_menu_id:
1582 // Close the subwindow if it exists.
1583 if (mTabControl.getCurrentSubWindow() != null) {
1584 dismissSubWindow(mTabControl.getCurrentTab());
1585 break;
1586 }
1587 closeCurrentTab();
1588 break;
1589
1590 case R.id.homepage_menu_id:
1591 Tab current = mTabControl.getCurrentTab();
1592 if (current != null) {
1593 dismissSubWindow(current);
1594 loadUrl(current.getWebView(), mSettings.getHomePage());
1595 }
1596 break;
1597
1598 case R.id.preferences_menu_id:
1599 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1600 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1601 getCurrentTopWebView().getUrl());
1602 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1603 break;
1604
1605 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001606 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001607 break;
1608
John Reckf33b1632011-06-04 20:00:23 -07001609 case R.id.freeze_tab_menu_id:
1610 // TODO: Show error messages
John Reck541f55a2011-06-07 16:34:43 -07001611 Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07001612 if (source == null) break;
John Reckd8c74522011-06-14 08:45:00 -07001613 final ContentResolver cr = mActivity.getContentResolver();
1614 final ContentValues values = source.createSnapshotValues();
1615 new AsyncTask<Tab, Void, Long>() {
1616 @Override
1617 protected Long doInBackground(Tab... params) {
1618 Tab t = params[0];
1619 if (values == null) {
1620 return t.isSnapshot()
1621 ? ((SnapshotTab)t).getSnapshotId()
1622 : -1;
1623 }
1624 Uri result = cr.insert(Snapshots.CONTENT_URI, values);
1625 long id = ContentUris.parseId(result);
1626 return id;
1627 }
1628
1629 protected void onPostExecute(Long id) {
1630 if (id > 0) {
1631 createNewSnapshotTab(id, true);
1632 }
1633 };
1634 }.execute(source);
John Reckf33b1632011-06-04 20:00:23 -07001635 break;
1636
Leon Scrogginsac993842011-02-02 12:54:07 -05001637 case R.id.save_webarchive_menu_id:
1638 String state = Environment.getExternalStorageState();
1639 if (!Environment.MEDIA_MOUNTED.equals(state)) {
1640 Log.e(LOGTAG, "External storage not mounted");
1641 Toast.makeText(mActivity, R.string.webarchive_failed,
1642 Toast.LENGTH_SHORT).show();
1643 break;
1644 }
1645 final String directory = Environment.getExternalStoragePublicDirectory(
1646 Environment.DIRECTORY_DOWNLOADS) + File.separator;
1647 File dir = new File(directory);
1648 if (!dir.exists() && !dir.mkdirs()) {
1649 Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
1650 Toast.makeText(mActivity, R.string.webarchive_failed,
1651 Toast.LENGTH_SHORT).show();
1652 break;
1653 }
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001654 final WebView topWebView = getCurrentTopWebView();
Leon Scrogginsac993842011-02-02 12:54:07 -05001655 final String title = topWebView.getTitle();
John Reck51d8bad2011-02-28 15:47:47 -08001656 final String url = topWebView.getUrl();
Leon Scrogginsac993842011-02-02 12:54:07 -05001657 topWebView.saveWebArchive(directory, true,
1658 new ValueCallback<String>() {
1659 @Override
1660 public void onReceiveValue(final String value) {
1661 if (value != null) {
1662 File file = new File(value);
1663 final long length = file.length();
1664 if (file.exists() && length > 0) {
Leon Scroggins1cb96552011-02-11 14:22:57 -05001665 Toast.makeText(mActivity, R.string.webarchive_saved,
1666 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001667 final DownloadManager manager = (DownloadManager) mActivity
1668 .getSystemService(Context.DOWNLOAD_SERVICE);
1669 new Thread("Add WebArchive to download manager") {
1670 @Override
1671 public void run() {
Vasu Noria9e30a72011-03-07 11:37:34 -08001672 manager.addCompletedDownload(
1673 null == title ? value : title,
Leon Scrogginsac993842011-02-02 12:54:07 -05001674 value, true, "application/x-webarchive-xml",
1675 value, length, true);
1676 }
1677 }.start();
1678 return;
1679 }
1680 }
John Reck51d8bad2011-02-28 15:47:47 -08001681 DownloadHandler.onDownloadStartNoStream(mActivity,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001682 url, null, null, null, topWebView.isPrivateBrowsingEnabled());
Leon Scrogginsac993842011-02-02 12:54:07 -05001683 }
1684 });
1685 break;
1686
Michael Kolb8233fac2010-10-26 16:08:53 -07001687 case R.id.page_info_menu_id:
1688 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1689 false);
1690 break;
1691
1692 case R.id.classic_history_menu_id:
1693 bookmarksOrHistoryPicker(true);
1694 break;
1695
1696 case R.id.title_bar_share_page_url:
1697 case R.id.share_page_menu_id:
1698 Tab currentTab = mTabControl.getCurrentTab();
1699 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001700 return false;
1701 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001702 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001703 break;
1704
1705 case R.id.dump_nav_menu_id:
1706 getCurrentTopWebView().debugDump();
1707 break;
1708
1709 case R.id.dump_counters_menu_id:
1710 getCurrentTopWebView().dumpV8Counters();
1711 break;
1712
1713 case R.id.zoom_in_menu_id:
1714 getCurrentTopWebView().zoomIn();
1715 break;
1716
1717 case R.id.zoom_out_menu_id:
1718 getCurrentTopWebView().zoomOut();
1719 break;
1720
1721 case R.id.view_downloads_menu_id:
1722 viewDownloads();
1723 break;
1724
1725 case R.id.window_one_menu_id:
1726 case R.id.window_two_menu_id:
1727 case R.id.window_three_menu_id:
1728 case R.id.window_four_menu_id:
1729 case R.id.window_five_menu_id:
1730 case R.id.window_six_menu_id:
1731 case R.id.window_seven_menu_id:
1732 case R.id.window_eight_menu_id:
1733 {
1734 int menuid = item.getItemId();
1735 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1736 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1737 Tab desiredTab = mTabControl.getTab(id);
1738 if (desiredTab != null &&
1739 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001740 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001741 }
1742 break;
1743 }
1744 }
1745 }
1746 break;
1747
1748 default:
1749 return false;
1750 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001751 return true;
1752 }
1753
1754 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001755 // Let the History and Bookmark fragments handle menus they created.
1756 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1757 return false;
1758 }
1759
Michael Kolb8233fac2010-10-26 16:08:53 -07001760 int id = item.getItemId();
1761 boolean result = true;
1762 switch (id) {
1763 // For the context menu from the title bar
1764 case R.id.title_bar_copy_page_url:
1765 Tab currentTab = mTabControl.getCurrentTab();
1766 if (null == currentTab) {
1767 result = false;
1768 break;
1769 }
1770 WebView mainView = currentTab.getWebView();
1771 if (null == mainView) {
1772 result = false;
1773 break;
1774 }
1775 copy(mainView.getUrl());
1776 break;
1777 // -- Browser context menu
1778 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001779 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001780 case R.id.copy_link_context_menu_id:
1781 final WebView webView = getCurrentTopWebView();
1782 if (null == webView) {
1783 result = false;
1784 break;
1785 }
1786 final HashMap<String, WebView> hrefMap =
1787 new HashMap<String, WebView>();
1788 hrefMap.put("webview", webView);
1789 final Message msg = mHandler.obtainMessage(
1790 FOCUS_NODE_HREF, id, 0, hrefMap);
1791 webView.requestFocusNodeHref(msg);
1792 break;
1793
1794 default:
1795 // For other context menus
1796 result = onOptionsItemSelected(item);
1797 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001798 return result;
1799 }
1800
1801 /**
1802 * support programmatically opening the context menu
1803 */
1804 public void openContextMenu(View view) {
1805 mActivity.openContextMenu(view);
1806 }
1807
1808 /**
1809 * programmatically open the options menu
1810 */
1811 public void openOptionsMenu() {
1812 mActivity.openOptionsMenu();
1813 }
1814
1815 public boolean onMenuOpened(int featureId, Menu menu) {
1816 if (mOptionsMenuOpen) {
1817 if (mConfigChanged) {
1818 // We do not need to make any changes to the state of the
1819 // title bar, since the only thing that happened was a
1820 // change in orientation
1821 mConfigChanged = false;
1822 } else {
1823 if (!mExtendedMenuOpen) {
1824 mExtendedMenuOpen = true;
1825 mUi.onExtendedMenuOpened();
1826 } else {
1827 // Switching the menu back to icon view, so show the
1828 // title bar once again.
1829 mExtendedMenuOpen = false;
1830 mUi.onExtendedMenuClosed(mInLoad);
Michael Kolb8233fac2010-10-26 16:08:53 -07001831 }
1832 }
1833 } else {
1834 // The options menu is closed, so open it, and show the title
1835 mOptionsMenuOpen = true;
1836 mConfigChanged = false;
1837 mExtendedMenuOpen = false;
1838 mUi.onOptionsMenuOpened();
1839 }
1840 return true;
1841 }
1842
1843 public void onOptionsMenuClosed(Menu menu) {
1844 mOptionsMenuOpen = false;
1845 mUi.onOptionsMenuClosed(mInLoad);
1846 }
1847
1848 public void onContextMenuClosed(Menu menu) {
1849 mUi.onContextMenuClosed(menu, mInLoad);
1850 }
1851
1852 // Helper method for getting the top window.
1853 @Override
1854 public WebView getCurrentTopWebView() {
1855 return mTabControl.getCurrentTopWebView();
1856 }
1857
1858 @Override
1859 public WebView getCurrentWebView() {
1860 return mTabControl.getCurrentWebView();
1861 }
1862
1863 /*
1864 * This method is called as a result of the user selecting the options
1865 * menu to see the download window. It shows the download window on top of
1866 * the current window.
1867 */
1868 void viewDownloads() {
1869 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1870 mActivity.startActivity(intent);
1871 }
1872
1873 // action mode
1874
1875 void onActionModeStarted(ActionMode mode) {
1876 mUi.onActionModeStarted(mode);
1877 mActionMode = mode;
1878 }
1879
1880 /*
1881 * True if a custom ActionMode (i.e. find or select) is in use.
1882 */
1883 @Override
1884 public boolean isInCustomActionMode() {
1885 return mActionMode != null;
1886 }
1887
1888 /*
1889 * End the current ActionMode.
1890 */
1891 @Override
1892 public void endActionMode() {
1893 if (mActionMode != null) {
1894 mActionMode.finish();
1895 }
1896 }
1897
1898 /*
1899 * Called by find and select when they are finished. Replace title bars
1900 * as necessary.
1901 */
1902 public void onActionModeFinished(ActionMode mode) {
1903 if (!isInCustomActionMode()) return;
1904 mUi.onActionModeFinished(mInLoad);
1905 mActionMode = null;
1906 }
1907
1908 boolean isInLoad() {
1909 return mInLoad;
1910 }
1911
1912 // bookmark handling
1913
1914 /**
1915 * add the current page as a bookmark to the given folder id
1916 * @param folderId use -1 for the default folder
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001917 * @param canBeAnEdit If true, check to see whether the site is already
1918 * bookmarked, and if it is, edit that bookmark. If false, and
1919 * the site is already bookmarked, do not attempt to edit the
1920 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001921 */
1922 @Override
John Reck3ffc5ca2011-06-10 15:56:06 -07001923 public void bookmarkCurrentPage(boolean canBeAnEdit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001924 Intent i = new Intent(mActivity,
1925 AddBookmarkPage.class);
1926 WebView w = getCurrentTopWebView();
1927 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1928 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1929 String touchIconUrl = w.getTouchIconUrl();
1930 if (touchIconUrl != null) {
1931 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1932 WebSettings settings = w.getSettings();
1933 if (settings != null) {
1934 i.putExtra(AddBookmarkPage.USER_AGENT,
1935 settings.getUserAgentString());
1936 }
1937 }
1938 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1939 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1940 getDesiredThumbnailHeight(mActivity)));
1941 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001942 if (canBeAnEdit) {
1943 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1944 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001945 // Put the dialog at the upper right of the screen, covering the
1946 // star on the title bar.
1947 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1948 mActivity.startActivity(i);
1949 }
1950
1951 // file chooser
1952 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1953 mUploadHandler = new UploadHandler(this);
1954 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1955 }
1956
1957 // thumbnails
1958
1959 /**
1960 * Return the desired width for thumbnail screenshots, which are stored in
1961 * the database, and used on the bookmarks screen.
1962 * @param context Context for finding out the density of the screen.
1963 * @return desired width for thumbnail screenshot.
1964 */
1965 static int getDesiredThumbnailWidth(Context context) {
1966 return context.getResources().getDimensionPixelOffset(
1967 R.dimen.bookmarkThumbnailWidth);
1968 }
1969
1970 /**
1971 * Return the desired height 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 height for thumbnail screenshot.
1975 */
1976 static int getDesiredThumbnailHeight(Context context) {
1977 return context.getResources().getDimensionPixelOffset(
1978 R.dimen.bookmarkThumbnailHeight);
1979 }
1980
Michael Kolb1acef692011-03-08 14:12:06 -08001981 static Bitmap createScreenshot(Tab tab, int width, int height) {
1982 if ((tab != null) && (tab.getWebView() != null)) {
1983 return createScreenshot(tab.getWebView(), width, height);
1984 }
1985 return null;
1986 }
1987
Michael Kolb8233fac2010-10-26 16:08:53 -07001988 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001989 // We render to a bitmap 2x the desired size so that we can then
1990 // re-scale it with filtering since canvas.scale doesn't filter
1991 // This helps reduce aliasing at the cost of being slightly blurry
1992 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001993 Picture thumbnail = view.capturePicture();
1994 if (thumbnail == null) {
1995 return null;
1996 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001997 width *= filter_scale;
1998 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001999 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
2000 Canvas canvas = new Canvas(bm);
2001 // May need to tweak these values to determine what is the
2002 // best scale factor
2003 int thumbnailWidth = thumbnail.getWidth();
2004 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08002005 float scaleFactor = 1.0f;
Michael Kolbeb95db42011-03-03 10:38:40 -08002006 if (thumbnailWidth > 0 && thumbnailHeight > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08002007 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07002008 } else {
2009 return null;
2010 }
John Reckfe49ab42010-11-16 17:09:37 -08002011
Michael Kolbeb95db42011-03-03 10:38:40 -08002012 float scaleFactorY = (float) height / (float)thumbnailHeight;
2013 if (scaleFactorY > scaleFactor) {
2014 // The picture is narrower than the requested AR
2015 // Center the thumnail and crop the sides
2016 scaleFactor = scaleFactorY;
John Reckfe49ab42010-11-16 17:09:37 -08002017 float wx = (thumbnailWidth * scaleFactor) - width;
2018 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07002019 }
2020
John Reckfe49ab42010-11-16 17:09:37 -08002021 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07002022
2023 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08002024 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
2025 height / filter_scale, true);
2026 bm.recycle();
2027 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07002028 }
2029
John Reck34ef2672011-02-10 11:30:55 -08002030 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002031 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07002032 // FIXME: Would like to make sure there is actually something to
2033 // draw, but the API for that (WebViewCore.pictureReady()) is not
2034 // currently accessible here.
2035
John Reck34ef2672011-02-10 11:30:55 -08002036 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08002037 if (view == null) {
2038 // Tab was destroyed
2039 return;
2040 }
John Reck34ef2672011-02-10 11:30:55 -08002041 final String url = tab.getUrl();
2042 final String originalUrl = view.getOriginalUrl();
2043
2044 if (TextUtils.isEmpty(url)) {
2045 return;
2046 }
2047
2048 // Only update thumbnails for web urls (http(s)://), not for
2049 // about:, javascript:, data:, etc...
2050 // Unless it is a bookmarked site, then always update
2051 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2052 return;
2053 }
2054
Michael Kolb8233fac2010-10-26 16:08:53 -07002055 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2056 getDesiredThumbnailHeight(mActivity));
2057 if (bm == null) {
2058 return;
2059 }
2060
2061 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002062 new AsyncTask<Void, Void, Void>() {
2063 @Override
2064 protected Void doInBackground(Void... unused) {
2065 Cursor cursor = null;
2066 try {
2067 // TODO: Clean this up
2068 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2069 if (cursor != null && cursor.moveToFirst()) {
2070 final ByteArrayOutputStream os =
2071 new ByteArrayOutputStream();
2072 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002073
John Reck34ef2672011-02-10 11:30:55 -08002074 ContentValues values = new ContentValues();
2075 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002076
John Reck34ef2672011-02-10 11:30:55 -08002077 do {
John Reck617fd832011-02-16 14:35:59 -08002078 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002079 cr.update(Images.CONTENT_URI, values, null, null);
2080 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002081 }
John Reck34ef2672011-02-10 11:30:55 -08002082 } catch (IllegalStateException e) {
2083 // Ignore
2084 } finally {
2085 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002086 }
John Reck34ef2672011-02-10 11:30:55 -08002087 return null;
2088 }
2089 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002090 }
2091
2092 private class Copy implements OnMenuItemClickListener {
2093 private CharSequence mText;
2094
2095 public boolean onMenuItemClick(MenuItem item) {
2096 copy(mText);
2097 return true;
2098 }
2099
2100 public Copy(CharSequence toCopy) {
2101 mText = toCopy;
2102 }
2103 }
2104
Leon Scroggins63c02662010-11-18 15:16:27 -05002105 private static class Download implements OnMenuItemClickListener {
2106 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002107 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002108 private boolean mPrivateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002109
2110 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002111 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002112 null, null, mPrivateBrowsing);
Michael Kolb8233fac2010-10-26 16:08:53 -07002113 return true;
2114 }
2115
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002116 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002117 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002118 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002119 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002120 }
2121 }
2122
Cary Clark8974d282010-11-22 10:46:05 -05002123 private static class SelectText implements OnMenuItemClickListener {
2124 private WebView mWebView;
2125
2126 public boolean onMenuItemClick(MenuItem item) {
2127 if (mWebView != null) {
2128 return mWebView.selectText();
2129 }
2130 return false;
2131 }
2132
2133 public SelectText(WebView webView) {
2134 mWebView = webView;
2135 }
2136
2137 }
2138
Michael Kolb8233fac2010-10-26 16:08:53 -07002139 /********************** TODO: UI stuff *****************************/
2140
2141 // these methods have been copied, they still need to be cleaned up
2142
2143 /****************** tabs ***************************************************/
2144
2145 // basic tab interactions:
2146
2147 // it is assumed that tabcontrol already knows about the tab
2148 protected void addTab(Tab tab) {
2149 mUi.addTab(tab);
2150 }
2151
2152 protected void removeTab(Tab tab) {
2153 mUi.removeTab(tab);
2154 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002155 mCrashRecoveryHandler.backupState();
John Reckd8c74522011-06-14 08:45:00 -07002156 if (tab.isSnapshot()) {
2157 SnapshotTab st = (SnapshotTab) tab;
2158 final Uri uri = ContentUris.withAppendedId(
2159 Snapshots.CONTENT_URI, st.getSnapshotId());
2160 final ContentResolver cr = mActivity.getContentResolver();
2161 new Thread() {
2162 @Override
2163 public void run() {
2164 cr.delete(uri, null, null);
2165 }
2166 }.start();
2167 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002168 }
2169
Michael Kolbf2055602011-04-09 17:20:03 -07002170 @Override
2171 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002172 // monkey protection against delayed start
2173 if (tab != null) {
2174 mTabControl.setCurrentTab(tab);
2175 // the tab is guaranteed to have a webview after setCurrentTab
2176 mUi.setActiveTab(tab);
2177 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002178 }
2179
2180 protected void closeEmptyChildTab() {
2181 Tab current = mTabControl.getCurrentTab();
2182 if (current != null
2183 && current.getWebView().copyBackForwardList().getSize() == 0) {
Michael Kolbc831b632011-05-11 09:30:34 -07002184 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002185 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002186 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002187 closeTab(current);
2188 }
2189 }
2190 }
2191
2192 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002193 // Dismiss the subwindow if applicable.
2194 dismissSubWindow(appTab);
2195 // Since we might kill the WebView, remove it from the
2196 // content view first.
2197 mUi.detachTab(appTab);
2198 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002199 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002200 // TODO: analyze why the remove and add are necessary
2201 mUi.attachTab(appTab);
2202 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002203 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002204 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002205 } else {
2206 // If the tab was the current tab, we have to attach
2207 // it to the view system again.
2208 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002209 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002210 }
2211 }
2212
2213 // Remove the sub window if it exists. Also called by TabControl when the
2214 // user clicks the 'X' to dismiss a sub window.
2215 public void dismissSubWindow(Tab tab) {
2216 removeSubWindow(tab);
2217 // dismiss the subwindow. This will destroy the WebView.
2218 tab.dismissSubWindow();
2219 getCurrentTopWebView().requestFocus();
2220 }
2221
2222 @Override
2223 public void removeSubWindow(Tab t) {
2224 if (t.getSubWebView() != null) {
2225 mUi.removeSubWindow(t.getSubViewContainer());
2226 }
2227 }
2228
2229 @Override
2230 public void attachSubWindow(Tab tab) {
2231 if (tab.getSubWebView() != null) {
2232 mUi.attachSubWindow(tab.getSubViewContainer());
2233 getCurrentTopWebView().requestFocus();
2234 }
2235 }
2236
Michael Kolb7bcafde2011-05-09 13:55:59 -07002237 // open a non inconito tab with the given url data
2238 // and set as active tab
2239 public Tab openTab(UrlData urlData) {
2240 Tab tab = createNewTab(false, true, true);
2241 if ((tab != null) && !urlData.isEmpty()) {
2242 loadUrlDataIn(tab, urlData);
2243 }
2244 return tab;
2245 }
2246
Michael Kolb843510f2010-12-09 10:51:49 -08002247 @Override
2248 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002249 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002250 }
2251
Michael Kolb8233fac2010-10-26 16:08:53 -07002252 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002253 public Tab openIncognitoTab() {
2254 return openTab(INCOGNITO_URI, true, true, false);
2255 }
2256
2257 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002258 public Tab openTab(String url, boolean incognito, boolean setActive,
2259 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002260 return openTab(url, incognito, setActive, useCurrent, null);
2261 }
2262
2263 @Override
2264 public Tab openTab(String url, Tab parent, boolean setActive,
2265 boolean useCurrent) {
2266 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2267 setActive, useCurrent, parent);
2268 }
2269
2270 public Tab openTab(String url, boolean incognito, boolean setActive,
2271 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002272 Tab tab = createNewTab(incognito, setActive, useCurrent);
2273 if (tab != null) {
John Reck5949c662011-05-27 09:52:29 -07002274 if (parent != null && parent != tab) {
2275 parent.addChildTab(tab);
2276 }
Michael Kolba4261fd2011-05-05 11:27:37 -07002277 WebView w = tab.getWebView();
Michael Kolb519d2282011-05-09 17:03:19 -07002278 if (url != null) {
2279 loadUrl(w, url);
2280 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002281 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002282 return tab;
2283 }
2284
2285 // this method will attempt to create a new tab
2286 // incognito: private browsing tab
2287 // setActive: ste tab as current tab
2288 // useCurrent: if no new tab can be created, return current tab
2289 private Tab createNewTab(boolean incognito, boolean setActive,
2290 boolean useCurrent) {
2291 Tab tab = null;
2292 if (mTabControl.canCreateNewTab()) {
2293 tab = mTabControl.createNewTab(incognito);
2294 addTab(tab);
2295 if (setActive) {
2296 setActiveTab(tab);
2297 }
2298 } else {
2299 if (useCurrent) {
2300 tab = mTabControl.getCurrentTab();
2301 // Get rid of the subwindow if it exists
2302 dismissSubWindow(tab);
2303 } else {
2304 mUi.showMaxTabsWarning();
2305 }
2306 }
2307 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002308 }
2309
John Reckd8c74522011-06-14 08:45:00 -07002310 private SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2311 SnapshotTab tab = mTabControl.createSnapshotTab(snapshotId);
2312 addTab(tab);
2313 if (setActive) {
2314 setActiveTab(tab);
2315 }
2316 return tab;
2317 }
2318
Michael Kolb8233fac2010-10-26 16:08:53 -07002319 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002320 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002321 * @return boolean True if we successfully switched to a different tab. If
2322 * the indexth tab is null, or if that tab is the same as
2323 * the current one, return false.
2324 */
2325 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002326 public boolean switchToTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002327 // hide combo view if open
2328 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002329 Tab currentTab = mTabControl.getCurrentTab();
2330 if (tab == null || tab == currentTab) {
2331 return false;
2332 }
2333 setActiveTab(tab);
2334 return true;
2335 }
2336
2337 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002338 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002339 // hide combo view if open
2340 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002341 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002342 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002343 return;
2344 }
Michael Kolbc831b632011-05-11 09:30:34 -07002345 final Tab current = mTabControl.getCurrentTab();
2346 final int pos = mTabControl.getCurrentPosition();
2347 Tab newTab = current.getParent();
2348 if (newTab == null) {
2349 newTab = mTabControl.getTab(pos + 1);
2350 if (newTab == null) {
2351 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002352 }
2353 }
Michael Kolbc831b632011-05-11 09:30:34 -07002354 if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002355 // Close window
2356 closeTab(current);
2357 }
2358 }
2359
2360 /**
2361 * Close the tab, remove its associated title bar, and adjust mTabControl's
2362 * current tab to a valid value.
2363 */
2364 @Override
2365 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002366 // hide combo view if open
2367 removeComboView();
Michael Kolb2d59c322011-01-25 13:18:55 -08002368 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002369 }
2370
2371 /**************** TODO: Url loading clean up *******************************/
2372
2373 // Called when loading from context menu or LOAD_URL message
2374 protected void loadUrlFromContext(WebView view, String url) {
2375 // In case the user enters nothing.
2376 if (url != null && url.length() != 0 && view != null) {
2377 url = UrlUtils.smartUrlFilter(url);
2378 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2379 loadUrl(view, url);
2380 }
2381 }
2382 }
2383
2384 /**
2385 * Load the URL into the given WebView and update the title bar
2386 * to reflect the new load. Call this instead of WebView.loadUrl
2387 * directly.
2388 * @param view The WebView used to load url.
2389 * @param url The URL to load.
2390 */
2391 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002392 view.loadUrl(url);
2393 }
2394
2395 /**
2396 * Load UrlData into a Tab and update the title bar to reflect the new
2397 * load. Call this instead of UrlData.loadIn directly.
2398 * @param t The Tab used to load.
2399 * @param data The UrlData being loaded.
2400 */
2401 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002402 data.loadIn(t);
2403 }
2404
John Reck30c714c2010-12-16 17:30:34 -08002405 @Override
2406 public void onUserCanceledSsl(Tab tab) {
2407 WebView web = tab.getWebView();
2408 // TODO: Figure out the "right" behavior
2409 if (web.canGoBack()) {
2410 web.goBack();
2411 } else {
2412 web.loadUrl(mSettings.getHomePage());
2413 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002414 }
2415
2416 void goBackOnePageOrQuit() {
2417 Tab current = mTabControl.getCurrentTab();
2418 if (current == null) {
2419 /*
2420 * Instead of finishing the activity, simply push this to the back
2421 * of the stack and let ActivityManager to choose the foreground
2422 * activity. As BrowserActivity is singleTask, it will be always the
2423 * root of the task. So we can use either true or false for
2424 * moveTaskToBack().
2425 */
2426 mActivity.moveTaskToBack(true);
2427 return;
2428 }
2429 WebView w = current.getWebView();
2430 if (w.canGoBack()) {
2431 w.goBack();
2432 } else {
2433 // Check to see if we are closing a window that was created by
2434 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002435 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002436 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002437 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002438 // Now we close the other tab
2439 closeTab(current);
2440 } else {
Michael Kolb8233fac2010-10-26 16:08:53 -07002441 /*
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 }
2450 }
2451 }
2452
2453 /**
2454 * Feed the previously stored results strings to the BrowserProvider so that
2455 * the SearchDialog will show them instead of the standard searches.
2456 * @param result String to show on the editable line of the SearchDialog.
2457 */
2458 @Override
2459 public void showVoiceSearchResults(String result) {
2460 ContentProviderClient client = mActivity.getContentResolver()
2461 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2462 ContentProvider prov = client.getLocalContentProvider();
2463 BrowserProvider bp = (BrowserProvider) prov;
2464 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2465 client.release();
2466
2467 Bundle bundle = createGoogleSearchSourceBundle(
2468 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2469 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2470 startSearch(result, false, bundle, false);
2471 }
2472
2473 private void startSearch(String initialQuery, boolean selectInitialQuery,
2474 Bundle appSearchData, boolean globalSearch) {
2475 if (appSearchData == null) {
2476 appSearchData = createGoogleSearchSourceBundle(
2477 GOOGLE_SEARCH_SOURCE_TYPE);
2478 }
2479
2480 SearchEngine searchEngine = mSettings.getSearchEngine();
2481 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2482 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2483 }
2484 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2485 globalSearch);
2486 }
2487
2488 private Bundle createGoogleSearchSourceBundle(String source) {
2489 Bundle bundle = new Bundle();
2490 bundle.putString(Search.SOURCE, source);
2491 return bundle;
2492 }
2493
2494 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002495 * helper method for key handler
2496 * returns the current tab if it can't advance
2497 */
Michael Kolbc831b632011-05-11 09:30:34 -07002498 private Tab getNextTab() {
2499 return mTabControl.getTab(Math.min(mTabControl.getTabCount() - 1,
2500 mTabControl.getCurrentPosition() + 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002501 }
2502
2503 /**
2504 * helper method for key handler
2505 * returns the current tab if it can't advance
2506 */
Michael Kolbc831b632011-05-11 09:30:34 -07002507 private Tab getPrevTab() {
2508 return mTabControl.getTab(Math.max(0,
2509 mTabControl.getCurrentPosition() - 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002510 }
2511
2512 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002513 * handle key events in browser
2514 *
2515 * @param keyCode
2516 * @param event
2517 * @return true if handled, false to pass to super
2518 */
2519 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002520 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002521 // Even if MENU is already held down, we need to call to super to open
2522 // the IME on long press.
Michael Kolb2814a362011-05-19 15:49:41 -07002523 if (KeyEvent.KEYCODE_MENU == keyCode) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002524 if (mOptionsMenuHandler != null) {
2525 return false;
2526 } else {
2527 event.startTracking();
2528 return true;
2529 }
Michael Kolb2814a362011-05-19 15:49:41 -07002530 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002531 if (!noModifiers
2532 && ((KeyEvent.KEYCODE_MENU == keyCode)
2533 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2534 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002535 mMenuIsDown = true;
2536 return false;
2537 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002538
Cary Clark8ff8c662010-12-29 15:03:05 -05002539 WebView webView = getCurrentTopWebView();
2540 if (webView == null) return false;
2541
Cary Clark160bbb92011-01-10 11:17:07 -05002542 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2543 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002544
Michael Kolb8233fac2010-10-26 16:08:53 -07002545 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002546 case KeyEvent.KEYCODE_TAB:
2547 if (event.isCtrlPressed()) {
2548 if (event.isShiftPressed()) {
2549 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002550 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002551 } else {
2552 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002553 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002554 }
2555 return true;
2556 }
2557 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002558 case KeyEvent.KEYCODE_SPACE:
2559 // WebView/WebTextView handle the keys in the KeyDown. As
2560 // the Activity's shortcut keys are only handled when WebView
2561 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002562 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002563 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002564 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002565 pageDown();
2566 }
2567 return true;
2568 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002569 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002570 event.startTracking();
2571 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002572 case KeyEvent.KEYCODE_DPAD_LEFT:
2573 if (ctrl) {
2574 webView.goBack();
2575 return true;
2576 }
2577 break;
2578 case KeyEvent.KEYCODE_DPAD_RIGHT:
2579 if (ctrl) {
2580 webView.goForward();
2581 return true;
2582 }
2583 break;
2584 case KeyEvent.KEYCODE_A:
2585 if (ctrl) {
2586 webView.selectAll();
2587 return true;
2588 }
2589 break;
Michael Kolba4183062011-01-16 10:43:21 -08002590// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002591 case KeyEvent.KEYCODE_C:
2592 if (ctrl) {
2593 webView.copySelection();
2594 return true;
2595 }
2596 break;
Michael Kolba4183062011-01-16 10:43:21 -08002597// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002598// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002599// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002600// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002601// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002602// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002603// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002604// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002605// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002606// case KeyEvent.KEYCODE_M: // unused
2607// case KeyEvent.KEYCODE_N: // in Chrome: new window
2608// case KeyEvent.KEYCODE_O: // in Chrome: open file
2609// case KeyEvent.KEYCODE_P: // in Chrome: print page
2610// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002611// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002612// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2613 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002614 // we can't use the ctrl/shift flags, they check for
2615 // exclusive use of a modifier
2616 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002617 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002618 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002619 } else {
2620 openTabToHomePage();
2621 }
2622 return true;
2623 }
2624 break;
2625// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2626// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb1a2eba42011-03-16 16:42:49 -07002627 case KeyEvent.KEYCODE_W: // in Chrome: close tab
2628 if (ctrl) {
2629 closeCurrentTab();
2630 return true;
2631 }
2632 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002633// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2634// case KeyEvent.KEYCODE_Y: // unused
2635// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002636 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002637 // it is a regular key and webview is not null
2638 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002639 }
2640
John Recke6bf4ab2011-02-24 15:48:05 -08002641 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2642 switch(keyCode) {
2643 case KeyEvent.KEYCODE_BACK:
2644 if (mUi.showsWeb()) {
2645 bookmarksOrHistoryPicker(true);
2646 return true;
2647 }
2648 break;
2649 }
2650 return false;
2651 }
2652
Michael Kolb8233fac2010-10-26 16:08:53 -07002653 boolean onKeyUp(int keyCode, KeyEvent event) {
Michael Kolb2814a362011-05-19 15:49:41 -07002654 if (KeyEvent.KEYCODE_MENU == keyCode) {
2655 mMenuIsDown = false;
2656 if (event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002657 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002658 }
2659 }
Cary Clark160bbb92011-01-10 11:17:07 -05002660 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002661 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002662 case KeyEvent.KEYCODE_BACK:
2663 if (event.isTracking() && !event.isCanceled()) {
2664 onBackKey();
2665 return true;
2666 }
2667 break;
2668 }
2669 return false;
2670 }
2671
2672 public boolean isMenuDown() {
2673 return mMenuIsDown;
2674 }
2675
Ben Murdoch8029a772010-11-16 11:58:21 +00002676 public void setupAutoFill(Message message) {
2677 // Open the settings activity at the AutoFill profile fragment so that
2678 // the user can create a new profile. When they return, we will dispatch
2679 // the message so that we can autofill the form using their new profile.
2680 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2681 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2682 AutoFillSettingsFragment.class.getName());
2683 mAutoFillSetupMessage = message;
2684 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2685 }
John Reckb3417f02011-01-14 11:01:05 -08002686
2687 @Override
2688 public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
2689 mOptionsMenuHandler = handler;
2690 }
2691
2692 @Override
2693 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
2694 if (mOptionsMenuHandler == handler) {
2695 mOptionsMenuHandler = null;
2696 }
2697 }
2698
Narayan Kamath5119edd2011-02-23 15:49:17 +00002699 @Override
2700 public void registerDropdownChangeListener(DropdownChangeListener d) {
2701 mUi.registerDropdownChangeListener(d);
2702 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002703}