blob: 6c6fe0bb355d9057b656176bb0f95f88ea24be68 [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
19import com.android.browser.IntentHandler.UrlData;
20import com.android.browser.search.SearchEngine;
21import com.android.common.Search;
22
23import android.app.Activity;
24import android.app.DownloadManager;
25import android.app.SearchManager;
26import android.content.ClipboardManager;
27import android.content.ContentProvider;
28import android.content.ContentProviderClient;
29import android.content.ContentResolver;
30import android.content.ContentValues;
31import android.content.Context;
32import android.content.Intent;
33import android.content.pm.PackageManager;
34import android.content.pm.ResolveInfo;
35import android.content.res.Configuration;
Leon Scroggins1961ed22010-12-07 15:22:21 -050036import android.database.ContentObserver;
Michael Kolb8233fac2010-10-26 16:08:53 -070037import android.database.Cursor;
38import android.database.sqlite.SQLiteDatabase;
Michael Kolb8233fac2010-10-26 16:08:53 -070039import android.graphics.Bitmap;
40import android.graphics.Canvas;
41import android.graphics.Picture;
42import android.net.Uri;
43import android.net.http.SslError;
44import android.os.AsyncTask;
45import android.os.Bundle;
46import android.os.Handler;
47import android.os.Message;
48import android.os.PowerManager;
49import android.os.PowerManager.WakeLock;
Ben Murdoch8029a772010-11-16 11:58:21 +000050import android.preference.PreferenceActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -070051import android.provider.Browser;
52import android.provider.BrowserContract;
Michael Kolb8233fac2010-10-26 16:08:53 -070053import android.provider.BrowserContract.Images;
54import android.provider.ContactsContract;
55import android.provider.ContactsContract.Intents.Insert;
Michael Kolbcfa3af52010-12-14 10:36:11 -080056import android.speech.RecognizerIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070057import android.speech.RecognizerResultsIntent;
58import android.text.TextUtils;
59import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080060import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070061import android.view.ActionMode;
62import android.view.ContextMenu;
63import android.view.ContextMenu.ContextMenuInfo;
64import android.view.Gravity;
65import android.view.KeyEvent;
66import android.view.LayoutInflater;
67import android.view.Menu;
68import android.view.MenuInflater;
69import android.view.MenuItem;
70import android.view.MenuItem.OnMenuItemClickListener;
71import android.view.View;
72import android.webkit.CookieManager;
73import android.webkit.CookieSyncManager;
74import android.webkit.HttpAuthHandler;
75import android.webkit.SslErrorHandler;
76import android.webkit.ValueCallback;
77import android.webkit.WebChromeClient;
78import android.webkit.WebIconDatabase;
79import android.webkit.WebSettings;
80import android.webkit.WebView;
81import android.widget.TextView;
82
83import java.io.ByteArrayOutputStream;
84import java.io.File;
85import java.net.URLEncoder;
86import java.util.Calendar;
87import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -080088import java.util.List;
Michael Kolb8233fac2010-10-26 16:08:53 -070089
90/**
91 * Controller for browser
92 */
93public class Controller
94 implements WebViewController, UiController {
95
96 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -080097 private static final String SEND_APP_ID_EXTRA =
98 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
99
Michael Kolb8233fac2010-10-26 16:08:53 -0700100
101 // public message ids
102 public final static int LOAD_URL = 1001;
103 public final static int STOP_LOAD = 1002;
104
105 // Message Ids
106 private static final int FOCUS_NODE_HREF = 102;
107 private static final int RELEASE_WAKELOCK = 107;
108
109 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
110
111 private static final int OPEN_BOOKMARKS = 201;
112
113 private static final int EMPTY_MENU = -1;
114
Michael Kolb8233fac2010-10-26 16:08:53 -0700115 // activity requestCode
116 final static int PREFERENCES_PAGE = 3;
117 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000118 final static int AUTOFILL_SETUP = 5;
119
Michael Kolb8233fac2010-10-26 16:08:53 -0700120 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
121
122 // As the ids are dynamically created, we can't guarantee that they will
123 // be in sequence, so this static array maps ids to a window number.
124 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
125 { R.id.window_one_menu_id, R.id.window_two_menu_id,
126 R.id.window_three_menu_id, R.id.window_four_menu_id,
127 R.id.window_five_menu_id, R.id.window_six_menu_id,
128 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
129
130 // "source" parameter for Google search through search key
131 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
132 // "source" parameter for Google search through simplily type
133 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
134
135 private Activity mActivity;
136 private UI mUi;
137 private TabControl mTabControl;
138 private BrowserSettings mSettings;
139 private WebViewFactory mFactory;
John Reckb3417f02011-01-14 11:01:05 -0800140 private OptionsMenuHandler mOptionsMenuHandler = null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700141
142 private WakeLock mWakeLock;
143
144 private UrlHandler mUrlHandler;
145 private UploadHandler mUploadHandler;
146 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700147 private PageDialogsHandler mPageDialogsHandler;
148 private NetworkStateHandler mNetworkHandler;
149
Ben Murdoch8029a772010-11-16 11:58:21 +0000150 private Message mAutoFillSetupMessage;
151
Michael Kolb8233fac2010-10-26 16:08:53 -0700152 private boolean mShouldShowErrorConsole;
153
154 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
155
156 // FIXME, temp address onPrepareMenu performance problem.
157 // When we move everything out of view, we should rewrite this.
158 private int mCurrentMenuState = 0;
159 private int mMenuState = R.id.MAIN_MENU;
160 private int mOldMenuState = EMPTY_MENU;
161 private Menu mCachedMenu;
162
163 // Used to prevent chording to result in firing two shortcuts immediately
164 // one after another. Fixes bug 1211714.
165 boolean mCanChord;
166 private boolean mMenuIsDown;
167
168 // For select and find, we keep track of the ActionMode so that
169 // finish() can be called as desired.
170 private ActionMode mActionMode;
171
172 /**
173 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
174 * of whether the configuration has changed. The first onMenuOpened call
175 * after a configuration change is simply a reopening of the same menu
176 * (i.e. mIconView did not change).
177 */
178 private boolean mConfigChanged;
179
180 /**
181 * Keeps track of whether the options menu is open. This is important in
182 * determining whether to show or hide the title bar overlay
183 */
184 private boolean mOptionsMenuOpen;
185
186 /**
187 * Whether or not the options menu is in its bigger, popup menu form. When
188 * true, we want the title bar overlay to be gone. When false, we do not.
189 * Only meaningful if mOptionsMenuOpen is true.
190 */
191 private boolean mExtendedMenuOpen;
192
193 private boolean mInLoad;
194
195 private boolean mActivityPaused = true;
196 private boolean mLoadStopped;
197
198 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500199 // Checks to see when the bookmarks database has changed, and updates the
200 // Tabs' notion of whether they represent bookmarked sites.
201 private ContentObserver mBookmarksObserver;
John Reck0ebd3ac2010-12-09 11:14:04 -0800202 private DataController mDataController;
Michael Kolb8233fac2010-10-26 16:08:53 -0700203
204 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
205 @Override
206 public Void doInBackground(File... files) {
207 if (files != null) {
208 for (File f : files) {
209 if (!f.delete()) {
210 Log.e(LOGTAG, f.getPath() + " was not deleted");
211 }
212 }
213 }
214 return null;
215 }
216 }
217
218 public Controller(Activity browser) {
219 mActivity = browser;
220 mSettings = BrowserSettings.getInstance();
John Reck0ebd3ac2010-12-09 11:14:04 -0800221 mDataController = DataController.getInstance(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700222 mTabControl = new TabControl(this);
223 mSettings.setController(this);
224
225 mUrlHandler = new UrlHandler(this);
226 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700227 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
228
229 PowerManager pm = (PowerManager) mActivity
230 .getSystemService(Context.POWER_SERVICE);
231 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
232
233 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500234 mBookmarksObserver = new ContentObserver(mHandler) {
235 @Override
236 public void onChange(boolean selfChange) {
237 int size = mTabControl.getTabCount();
238 for (int i = 0; i < size; i++) {
239 mTabControl.getTab(i).updateBookmarkedStatus();
240 }
241 }
242
243 };
244 browser.getContentResolver().registerContentObserver(
245 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700246
247 mNetworkHandler = new NetworkStateHandler(mActivity, this);
248 // Start watching the default geolocation permissions
249 mSystemAllowGeolocationOrigins =
250 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
251 mSystemAllowGeolocationOrigins.start();
252
253 retainIconsOnStartup();
254 }
255
256 void start(Bundle icicle, Intent intent) {
257 // Unless the last browser usage was within 24 hours, destroy any
258 // remaining incognito tabs.
259
260 Calendar lastActiveDate = icicle != null ?
261 (Calendar) icicle.getSerializable("lastActiveDate") : null;
262 Calendar today = Calendar.getInstance();
263 Calendar yesterday = Calendar.getInstance();
264 yesterday.add(Calendar.DATE, -1);
265
Michael Kolb1bf23132010-11-19 12:55:12 -0800266 boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700267 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800268 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700269
Michael Kolb1bf23132010-11-19 12:55:12 -0800270 if (!mTabControl.restoreState(icicle, restoreIncognitoTabs,
271 mUi.needsRestoreAllTabs())) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700272 // there is no quit on Android. But if we can't restore the state,
273 // we can treat it as a new Browser, remove the old session cookies.
Kristian Monsen3a4e8092010-12-08 11:09:25 +0000274 // This is done async in the CookieManager.
275 CookieManager.getInstance().removeSessionCookie();
Kristian Monsen2cd97012010-12-07 11:11:40 +0000276
Michael Kolb8233fac2010-10-26 16:08:53 -0700277 final Bundle extra = intent.getExtras();
278 // Create an initial tab.
279 // If the intent is ACTION_VIEW and data is not null, the Browser is
280 // invoked to view the content by another application. In this case,
281 // the tab will be close when exit.
282 UrlData urlData = mIntentHandler.getUrlDataFromIntent(intent);
283
284 String action = intent.getAction();
285 final Tab t = mTabControl.createNewTab(
286 (Intent.ACTION_VIEW.equals(action) &&
287 intent.getData() != null)
288 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
289 .equals(action),
290 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
291 urlData.mUrl, false);
292 addTab(t);
293 setActiveTab(t);
294 WebView webView = t.getWebView();
295 if (extra != null) {
296 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
297 if (scale > 0 && scale <= 1000) {
298 webView.setInitialScale(scale);
299 }
300 }
301
302 if (urlData.isEmpty()) {
303 loadUrl(webView, mSettings.getHomePage());
304 } else {
305 loadUrlDataIn(t, urlData);
306 }
307 } else {
Michael Kolb1bf23132010-11-19 12:55:12 -0800308 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700309 // TabControl.restoreState() will create a new tab even if
310 // restoring the state fails.
311 setActiveTab(mTabControl.getCurrentTab());
312 }
313 // clear up the thumbnail directory, which is no longer used;
314 // ideally this should only be run once after an upgrade from
315 // a previous version of the browser
316 new ClearThumbnails().execute(mTabControl.getThumbnailDir()
317 .listFiles());
318 // Read JavaScript flags if it exists.
319 String jsFlags = getSettings().getJsFlags();
320 if (jsFlags.trim().length() != 0) {
321 getCurrentWebView().setJsFlags(jsFlags);
322 }
John Reck439c9a52010-12-14 10:04:39 -0800323 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
324 bookmarksOrHistoryPicker(false);
325 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700326 }
327
328 void setWebViewFactory(WebViewFactory factory) {
329 mFactory = factory;
330 }
331
Michael Kolb1514bb72010-11-22 09:11:48 -0800332 @Override
333 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700334 return mFactory;
335 }
336
337 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800338 public void onSetWebView(Tab tab, WebView view) {
339 mUi.onSetWebView(tab, view);
340 }
341
342 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800343 public void createSubWindow(Tab tab) {
344 endActionMode();
345 WebView mainView = tab.getWebView();
346 WebView subView = mFactory.createWebView((mainView == null)
347 ? false
348 : mainView.isPrivateBrowsingEnabled());
349 mUi.createSubWindow(tab, subView);
350 }
351
352 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700353 public Activity getActivity() {
354 return mActivity;
355 }
356
357 void setUi(UI ui) {
358 mUi = ui;
359 }
360
361 BrowserSettings getSettings() {
362 return mSettings;
363 }
364
365 IntentHandler getIntentHandler() {
366 return mIntentHandler;
367 }
368
369 @Override
370 public UI getUi() {
371 return mUi;
372 }
373
374 int getMaxTabs() {
375 return mActivity.getResources().getInteger(R.integer.max_tabs);
376 }
377
378 @Override
379 public TabControl getTabControl() {
380 return mTabControl;
381 }
382
Michael Kolb1bf23132010-11-19 12:55:12 -0800383 @Override
384 public List<Tab> getTabs() {
385 return mTabControl.getTabs();
386 }
387
Michael Kolb8233fac2010-10-26 16:08:53 -0700388 // Open the icon database and retain all the icons for visited sites.
Ben Murdoch9446b932010-11-25 16:20:14 +0000389 // This is done on a background thread so as not to stall startup.
Michael Kolb8233fac2010-10-26 16:08:53 -0700390 private void retainIconsOnStartup() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000391 // WebIconDatabase needs to be retrieved on the UI thread so that if
392 // it has not been created successfully yet the Handler is started on the
393 // UI thread.
394 new RetainIconsOnStartupTask(WebIconDatabase.getInstance()).execute();
395 }
396
397 private class RetainIconsOnStartupTask extends AsyncTask<Void, Void, Void> {
398 private WebIconDatabase mDb;
399
400 public RetainIconsOnStartupTask(WebIconDatabase db) {
401 mDb = db;
402 }
403
John Recka00cbbd2010-12-16 12:38:19 -0800404 @Override
Ben Murdoch9446b932010-11-25 16:20:14 +0000405 protected Void doInBackground(Void... unused) {
406 mDb.open(mActivity.getDir("icons", 0).getPath());
407 Cursor c = null;
408 try {
409 c = Browser.getAllBookmarks(mActivity.getContentResolver());
410 if (c.moveToFirst()) {
411 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
412 do {
413 String url = c.getString(urlIndex);
414 mDb.retainIconForPageUrl(url);
415 } while (c.moveToNext());
416 }
417 } catch (IllegalStateException e) {
418 Log.e(LOGTAG, "retainIconsOnStartup", e);
419 } finally {
420 if (c != null) c.close();
Michael Kolb8233fac2010-10-26 16:08:53 -0700421 }
Ben Murdoch9446b932010-11-25 16:20:14 +0000422
423 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700424 }
425 }
426
427 private void startHandler() {
428 mHandler = new Handler() {
429
430 @Override
431 public void handleMessage(Message msg) {
432 switch (msg.what) {
433 case OPEN_BOOKMARKS:
434 bookmarksOrHistoryPicker(false);
435 break;
436 case FOCUS_NODE_HREF:
437 {
438 String url = (String) msg.getData().get("url");
439 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500440 String src = (String) msg.getData().get("src");
441 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700442 if (TextUtils.isEmpty(url)) {
443 break;
444 }
445 HashMap focusNodeMap = (HashMap) msg.obj;
446 WebView view = (WebView) focusNodeMap.get("webview");
447 // Only apply the action if the top window did not change.
448 if (getCurrentTopWebView() != view) {
449 break;
450 }
451 switch (msg.arg1) {
452 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -0700453 loadUrlFromContext(getCurrentTopWebView(), url);
454 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500455 case R.id.view_image_context_menu_id:
456 loadUrlFromContext(getCurrentTopWebView(), src);
457 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500458 case R.id.open_newtab_context_menu_id:
459 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -0800460 final Tab newTab = openTab(parent, url, false);
Leon Scroggins026f2542010-11-22 13:26:12 -0500461 if (newTab != null && newTab != parent) {
462 parent.addChildTab(newTab);
463 }
464 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700465 case R.id.copy_link_context_menu_id:
466 copy(url);
467 break;
468 case R.id.save_link_context_menu_id:
469 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500470 DownloadHandler.onDownloadStartNoStream(
471 mActivity, url, null, null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -0700472 break;
473 }
474 break;
475 }
476
477 case LOAD_URL:
478 loadUrlFromContext(getCurrentTopWebView(), (String) msg.obj);
479 break;
480
481 case STOP_LOAD:
482 stopLoading();
483 break;
484
485 case RELEASE_WAKELOCK:
486 if (mWakeLock.isHeld()) {
487 mWakeLock.release();
488 // if we reach here, Browser should be still in the
489 // background loading after WAKELOCK_TIMEOUT (5-min).
490 // To avoid burning the battery, stop loading.
491 mTabControl.stopAllLoading();
492 }
493 break;
494
495 case UPDATE_BOOKMARK_THUMBNAIL:
496 WebView view = (WebView) msg.obj;
497 if (view != null) {
498 updateScreenshot(view);
499 }
500 break;
501 }
502 }
503 };
504
505 }
506
Michael Kolbba99c5d2010-11-29 14:57:41 -0800507 @Override
508 public void shareCurrentPage() {
509 shareCurrentPage(mTabControl.getCurrentTab());
510 }
511
512 private void shareCurrentPage(Tab tab) {
513 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800514 sharePage(mActivity, tab.getTitle(),
515 tab.getUrl(), tab.getFavicon(),
516 createScreenshot(tab.getWebView(),
517 getDesiredThumbnailWidth(mActivity),
518 getDesiredThumbnailHeight(mActivity)));
519 }
520 }
521
Michael Kolb8233fac2010-10-26 16:08:53 -0700522 /**
523 * Share a page, providing the title, url, favicon, and a screenshot. Uses
524 * an {@link Intent} to launch the Activity chooser.
525 * @param c Context used to launch a new Activity.
526 * @param title Title of the page. Stored in the Intent with
527 * {@link Intent#EXTRA_SUBJECT}
528 * @param url URL of the page. Stored in the Intent with
529 * {@link Intent#EXTRA_TEXT}
530 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
531 * with {@link Browser#EXTRA_SHARE_FAVICON}
532 * @param screenshot Bitmap of a screenshot of the page. Stored in the
533 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
534 */
535 static final void sharePage(Context c, String title, String url,
536 Bitmap favicon, Bitmap screenshot) {
537 Intent send = new Intent(Intent.ACTION_SEND);
538 send.setType("text/plain");
539 send.putExtra(Intent.EXTRA_TEXT, url);
540 send.putExtra(Intent.EXTRA_SUBJECT, title);
541 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
542 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
543 try {
544 c.startActivity(Intent.createChooser(send, c.getString(
545 R.string.choosertitle_sharevia)));
546 } catch(android.content.ActivityNotFoundException ex) {
547 // if no app handles it, do nothing
548 }
549 }
550
551 private void copy(CharSequence text) {
552 ClipboardManager cm = (ClipboardManager) mActivity
553 .getSystemService(Context.CLIPBOARD_SERVICE);
554 cm.setText(text);
555 }
556
557 // lifecycle
558
559 protected void onConfgurationChanged(Configuration config) {
560 mConfigChanged = true;
561 if (mPageDialogsHandler != null) {
562 mPageDialogsHandler.onConfigurationChanged(config);
563 }
564 mUi.onConfigurationChanged(config);
565 }
566
567 @Override
568 public void handleNewIntent(Intent intent) {
569 mIntentHandler.onNewIntent(intent);
570 }
571
572 protected void onPause() {
573 if (mActivityPaused) {
574 Log.e(LOGTAG, "BrowserActivity is already paused.");
575 return;
576 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700577 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800578 Tab tab = mTabControl.getCurrentTab();
579 if (tab != null) {
580 tab.pause();
581 if (!pauseWebViewTimers(tab)) {
582 mWakeLock.acquire();
583 mHandler.sendMessageDelayed(mHandler
584 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
585 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700586 }
587 mUi.onPause();
588 mNetworkHandler.onPause();
589
590 WebView.disablePlatformNotifications();
591 }
592
593 void onSaveInstanceState(Bundle outState) {
594 // the default implementation requires each view to have an id. As the
595 // browser handles the state itself and it doesn't use id for the views,
596 // don't call the default implementation. Otherwise it will trigger the
597 // warning like this, "couldn't save which view has focus because the
598 // focused view XXX has no id".
599
600 // Save all the tabs
601 mTabControl.saveState(outState);
602 // Save time so that we know how old incognito tabs (if any) are.
603 outState.putSerializable("lastActiveDate", Calendar.getInstance());
604 }
605
606 void onResume() {
607 if (!mActivityPaused) {
608 Log.e(LOGTAG, "BrowserActivity is already resumed.");
609 return;
610 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700611 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800612 Tab current = mTabControl.getCurrentTab();
613 if (current != null) {
614 current.resume();
615 resumeWebViewTimers(current);
616 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700617 if (mWakeLock.isHeld()) {
618 mHandler.removeMessages(RELEASE_WAKELOCK);
619 mWakeLock.release();
620 }
621 mUi.onResume();
622 mNetworkHandler.onResume();
623 WebView.enablePlatformNotifications();
624 }
625
Michael Kolb70976932010-11-30 11:34:01 -0800626 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800627 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800628 * @param tab guaranteed non-null
629 */
630 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700631 boolean inLoad = tab.inPageLoad();
632 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
633 CookieSyncManager.getInstance().startSync();
634 WebView w = tab.getWebView();
635 if (w != null) {
636 w.resumeTimers();
637 }
638 }
639 }
640
Michael Kolb70976932010-11-30 11:34:01 -0800641 /**
642 * Pause all WebView timers using the WebView of the given tab
643 * @param tab
644 * @return true if the timers are paused or tab is null
645 */
646 private boolean pauseWebViewTimers(Tab tab) {
647 if (tab == null) {
648 return true;
649 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700650 CookieSyncManager.getInstance().stopSync();
651 WebView w = getCurrentWebView();
652 if (w != null) {
653 w.pauseTimers();
654 }
655 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700656 }
Michael Kolb70976932010-11-30 11:34:01 -0800657 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700658 }
659
660 void onDestroy() {
661 if (mUploadHandler != null) {
662 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
663 mUploadHandler = null;
664 }
665 if (mTabControl == null) return;
666 mUi.onDestroy();
667 // Remove the current tab and sub window
668 Tab t = mTabControl.getCurrentTab();
669 if (t != null) {
670 dismissSubWindow(t);
671 removeTab(t);
672 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500673 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700674 // Destroy all the tabs
675 mTabControl.destroy();
676 WebIconDatabase.getInstance().close();
677 // Stop watching the default geolocation permissions
678 mSystemAllowGeolocationOrigins.stop();
679 mSystemAllowGeolocationOrigins = null;
680 }
681
682 protected boolean isActivityPaused() {
683 return mActivityPaused;
684 }
685
686 protected void onLowMemory() {
687 mTabControl.freeMemory();
688 }
689
690 @Override
691 public boolean shouldShowErrorConsole() {
692 return mShouldShowErrorConsole;
693 }
694
695 protected void setShouldShowErrorConsole(boolean show) {
696 if (show == mShouldShowErrorConsole) {
697 // Nothing to do.
698 return;
699 }
700 mShouldShowErrorConsole = show;
701 Tab t = mTabControl.getCurrentTab();
702 if (t == null) {
703 // There is no current tab so we cannot toggle the error console
704 return;
705 }
706 mUi.setShouldShowErrorConsole(t, show);
707 }
708
709 @Override
710 public void stopLoading() {
711 mLoadStopped = true;
712 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700713 WebView w = getCurrentTopWebView();
714 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700715 mUi.onPageStopped(tab);
716 }
717
718 boolean didUserStopLoading() {
719 return mLoadStopped;
720 }
721
722 // WebViewController
723
724 @Override
John Reck324d4402011-01-11 16:56:42 -0800725 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700726
727 // We've started to load a new page. If there was a pending message
728 // to save a screenshot then we will now take the new page and save
729 // an incorrect screenshot. Therefore, remove any pending thumbnail
730 // messages from the queue.
731 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
732 view);
733
734 // reset sync timer to avoid sync starts during loading a page
735 CookieSyncManager.getInstance().resetSync();
736
737 if (!mNetworkHandler.isNetworkUp()) {
738 view.setNetworkAvailable(false);
739 }
740
741 // when BrowserActivity just starts, onPageStarted may be called before
742 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
743 // to start the timer. As we won't switch tabs while an activity is in
744 // pause state, we can ensure calling resume and pause in pair.
745 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800746 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700747 }
748 mLoadStopped = false;
749 if (!mNetworkHandler.isNetworkUp()) {
750 mNetworkHandler.createAndShowNetworkDialog();
751 }
752 endActionMode();
753
John Reck30c714c2010-12-16 17:30:34 -0800754 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700755
John Reck324d4402011-01-11 16:56:42 -0800756 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700757 // update the bookmark database for favicon
758 maybeUpdateFavicon(tab, null, url, favicon);
759
760 Performance.tracePageStart(url);
761
762 // Performance probe
763 if (false) {
764 Performance.onPageStarted();
765 }
766
767 }
768
769 @Override
John Reck324d4402011-01-11 16:56:42 -0800770 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800771 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800772 if (!tab.isPrivateBrowsingEnabled()
773 && !TextUtils.isEmpty(tab.getUrl())) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700774 if (tab.inForeground() && !didUserStopLoading()
775 || !tab.inForeground()) {
776 // Only update the bookmark screenshot if the user did not
777 // cancel the load early.
778 mHandler.sendMessageDelayed(mHandler.obtainMessage(
779 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab.getWebView()),
780 500);
781 }
782 }
783 // pause the WebView timer and release the wake lock if it is finished
784 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800785 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700786 if (mWakeLock.isHeld()) {
787 mHandler.removeMessages(RELEASE_WAKELOCK);
788 mWakeLock.release();
789 }
790 }
791 // Performance probe
792 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800793 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700794 }
795
796 Performance.tracePageFinished();
797 }
798
799 @Override
John Reck30c714c2010-12-16 17:30:34 -0800800 public void onProgressChanged(Tab tab) {
801 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700802
803 if (newProgress == 100) {
804 CookieSyncManager.getInstance().sync();
805 // onProgressChanged() may continue to be called after the main
806 // frame has finished loading, as any remaining sub frames continue
807 // to load. We'll only get called once though with newProgress as
808 // 100 when everything is loaded. (onPageFinished is called once
809 // when the main frame completes loading regardless of the state of
810 // any sub frames so calls to onProgressChanges may continue after
811 // onPageFinished has executed)
812 if (mInLoad) {
813 mInLoad = false;
814 updateInLoadMenuItems(mCachedMenu);
815 }
816 } else {
817 if (!mInLoad) {
818 // onPageFinished may have already been called but a subframe is
819 // still loading and updating the progress. Reset mInLoad and
820 // update the menu items.
821 mInLoad = true;
822 updateInLoadMenuItems(mCachedMenu);
823 }
824 }
John Reck30c714c2010-12-16 17:30:34 -0800825 mUi.onProgressChanged(tab);
826 }
827
828 @Override
829 public void onUpdatedLockIcon(Tab tab) {
830 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700831 }
832
833 @Override
834 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800835 mUi.onTabDataChanged(tab);
836 final String pageUrl = tab.getUrl();
John Reck324d4402011-01-11 16:56:42 -0800837 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700838 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
839 return;
840 }
841 // Update the title in the history database if not in private browsing mode
842 if (!tab.isPrivateBrowsingEnabled()) {
John Reck0ebd3ac2010-12-09 11:14:04 -0800843 mDataController.updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700844 }
845 }
846
847 @Override
848 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800849 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700850 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
851 }
852
853 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800854 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
855 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700856 }
857
858 @Override
859 public boolean shouldOverrideKeyEvent(KeyEvent event) {
860 if (mMenuIsDown) {
861 // only check shortcut key when MENU is held
862 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
863 event);
864 } else {
865 return false;
866 }
867 }
868
869 @Override
870 public void onUnhandledKeyEvent(KeyEvent event) {
871 if (!isActivityPaused()) {
872 if (event.getAction() == KeyEvent.ACTION_DOWN) {
873 mActivity.onKeyDown(event.getKeyCode(), event);
874 } else {
875 mActivity.onKeyUp(event.getKeyCode(), event);
876 }
877 }
878 }
879
880 @Override
John Reck324d4402011-01-11 16:56:42 -0800881 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700882 // Don't save anything in private browsing mode
883 if (tab.isPrivateBrowsingEnabled()) return;
John Reck324d4402011-01-11 16:56:42 -0800884 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700885
John Reck324d4402011-01-11 16:56:42 -0800886 if (TextUtils.isEmpty(url)
887 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700888 return;
889 }
John Reck0ebd3ac2010-12-09 11:14:04 -0800890 mDataController.updateVisitedHistory(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700891 WebIconDatabase.getInstance().retainIconForPageUrl(url);
892 }
893
894 @Override
895 public void getVisitedHistory(final ValueCallback<String[]> callback) {
896 AsyncTask<Void, Void, String[]> task =
897 new AsyncTask<Void, Void, String[]>() {
898 @Override
899 public String[] doInBackground(Void... unused) {
900 return Browser.getVisitedHistory(mActivity.getContentResolver());
901 }
902 @Override
903 public void onPostExecute(String[] result) {
904 callback.onReceiveValue(result);
905 }
906 };
907 task.execute();
908 }
909
910 @Override
911 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
912 final HttpAuthHandler handler, final String host,
913 final String realm) {
914 String username = null;
915 String password = null;
916
917 boolean reuseHttpAuthUsernamePassword
918 = handler.useHttpAuthUsernamePassword();
919
920 if (reuseHttpAuthUsernamePassword && view != null) {
921 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
922 if (credentials != null && credentials.length == 2) {
923 username = credentials[0];
924 password = credentials[1];
925 }
926 }
927
928 if (username != null && password != null) {
929 handler.proceed(username, password);
930 } else {
931 if (tab.inForeground()) {
932 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
933 } else {
934 handler.cancel();
935 }
936 }
937 }
938
939 @Override
940 public void onDownloadStart(Tab tab, String url, String userAgent,
941 String contentDisposition, String mimetype, long contentLength) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500942 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
943 contentDisposition, mimetype);
Michael Kolb8233fac2010-10-26 16:08:53 -0700944 if (tab.getWebView().copyBackForwardList().getSize() == 0) {
945 // This Tab was opened for the sole purpose of downloading a
946 // file. Remove it.
947 if (tab == mTabControl.getCurrentTab()) {
948 // In this case, the Tab is still on top.
949 goBackOnePageOrQuit();
950 } else {
951 // In this case, it is not.
952 closeTab(tab);
953 }
954 }
955 }
956
957 @Override
958 public Bitmap getDefaultVideoPoster() {
959 return mUi.getDefaultVideoPoster();
960 }
961
962 @Override
963 public View getVideoLoadingProgressView() {
964 return mUi.getVideoLoadingProgressView();
965 }
966
967 @Override
968 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
969 SslError error) {
970 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
971 }
972
973 // helper method
974
975 /*
976 * Update the favorites icon if the private browsing isn't enabled and the
977 * icon is valid.
978 */
979 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
980 final String url, Bitmap favicon) {
981 if (favicon == null) {
982 return;
983 }
984 if (!tab.isPrivateBrowsingEnabled()) {
985 Bookmarks.updateFavicon(mActivity
986 .getContentResolver(), originalUrl, url, favicon);
987 }
988 }
989
Leon Scroggins4cd97792010-12-03 15:31:56 -0500990 @Override
991 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -0800992 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -0500993 mUi.bookmarkedStatusHasChanged(tab);
994 }
995
Michael Kolb8233fac2010-10-26 16:08:53 -0700996 // end WebViewController
997
998 protected void pageUp() {
999 getCurrentTopWebView().pageUp(false);
1000 }
1001
1002 protected void pageDown() {
1003 getCurrentTopWebView().pageDown(false);
1004 }
1005
1006 // callback from phone title bar
1007 public void editUrl() {
1008 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
1009 String url = (getCurrentTopWebView() == null) ? null : getCurrentTopWebView().getUrl();
1010 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1011 null, false);
1012 }
1013
Michael Kolbcfa3af52010-12-14 10:36:11 -08001014 public void startVoiceSearch() {
1015 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1016 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1017 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1018 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1019 mActivity.getComponentName().flattenToString());
1020 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001021 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001022 mActivity.startActivity(intent);
1023 }
1024
Michael Kolb8233fac2010-10-26 16:08:53 -07001025 public void activateVoiceSearchMode(String title) {
1026 mUi.showVoiceTitleBar(title);
1027 }
1028
1029 public void revertVoiceSearchMode(Tab tab) {
1030 mUi.revertVoiceTitleBar(tab);
1031 }
1032
1033 public void showCustomView(Tab tab, View view,
1034 WebChromeClient.CustomViewCallback callback) {
1035 if (tab.inForeground()) {
1036 if (mUi.isCustomViewShowing()) {
1037 callback.onCustomViewHidden();
1038 return;
1039 }
1040 mUi.showCustomView(view, callback);
1041 // Save the menu state and set it to empty while the custom
1042 // view is showing.
1043 mOldMenuState = mMenuState;
1044 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001045 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001046 }
1047 }
1048
1049 @Override
1050 public void hideCustomView() {
1051 if (mUi.isCustomViewShowing()) {
1052 mUi.onHideCustomView();
1053 // Reset the old menu state.
1054 mMenuState = mOldMenuState;
1055 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001056 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001057 }
1058 }
1059
1060 protected void onActivityResult(int requestCode, int resultCode,
1061 Intent intent) {
1062 if (getCurrentTopWebView() == null) return;
1063 switch (requestCode) {
1064 case PREFERENCES_PAGE:
1065 if (resultCode == Activity.RESULT_OK && intent != null) {
1066 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
1067 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
1068 mTabControl.removeParentChildRelationShips();
1069 }
1070 }
1071 break;
1072 case FILE_SELECTED:
1073 // Choose a file from the file picker.
1074 if (null == mUploadHandler) break;
1075 mUploadHandler.onResult(resultCode, intent);
1076 mUploadHandler = null;
1077 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001078 case AUTOFILL_SETUP:
1079 // Determine whether a profile was actually set up or not
1080 // and if so, send the message back to the WebTextView to
1081 // fill the form with the new profile.
1082 if (getSettings().getAutoFillProfile() != null) {
1083 mAutoFillSetupMessage.sendToTarget();
1084 mAutoFillSetupMessage = null;
1085 }
1086 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001087 default:
1088 break;
1089 }
1090 getCurrentTopWebView().requestFocus();
1091 }
1092
1093 /**
1094 * Open the Go page.
1095 * @param startWithHistory If true, open starting on the history tab.
1096 * Otherwise, start with the bookmarks tab.
1097 */
1098 @Override
1099 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1100 if (mTabControl.getCurrentWebView() == null) {
1101 return;
1102 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001103 // clear action mode
1104 if (isInCustomActionMode()) {
1105 endActionMode();
1106 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001107 Bundle extras = new Bundle();
1108 // Disable opening in a new window if we have maxed out the windows
1109 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1110 !mTabControl.canCreateNewTab());
1111 mUi.showComboView(startWithHistory, extras);
1112 }
1113
1114 // combo view callbacks
1115
1116 /**
1117 * callback from ComboPage when clear history is requested
1118 */
1119 public void onRemoveParentChildRelationships() {
1120 mTabControl.removeParentChildRelationShips();
1121 }
1122
1123 /**
1124 * callback from ComboPage when bookmark/history selection
1125 */
1126 @Override
1127 public void onUrlSelected(String url, boolean newTab) {
1128 removeComboView();
1129 if (!TextUtils.isEmpty(url)) {
1130 if (newTab) {
Michael Kolb18eb3772010-12-10 14:29:51 -08001131 openTab(mTabControl.getCurrentTab(), url, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001132 } else {
1133 final Tab currentTab = mTabControl.getCurrentTab();
1134 dismissSubWindow(currentTab);
1135 loadUrl(getCurrentTopWebView(), url);
1136 }
1137 }
1138 }
1139
1140 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07001141 * dismiss the ComboPage
1142 */
1143 @Override
1144 public void removeComboView() {
1145 mUi.hideComboView();
1146 }
1147
1148 // active tabs page handling
1149
1150 protected void showActiveTabsPage() {
1151 mMenuState = EMPTY_MENU;
1152 mUi.showActiveTabsPage();
1153 }
1154
1155 /**
1156 * Remove the active tabs page.
1157 * @param needToAttach If true, the active tabs page did not attach a tab
1158 * to the content view, so we need to do that here.
1159 */
1160 @Override
1161 public void removeActiveTabsPage(boolean needToAttach) {
1162 mMenuState = R.id.MAIN_MENU;
1163 mUi.removeActiveTabsPage();
1164 if (needToAttach) {
1165 setActiveTab(mTabControl.getCurrentTab());
1166 }
1167 getCurrentTopWebView().requestFocus();
1168 }
1169
1170 // key handling
1171 protected void onBackKey() {
1172 if (!mUi.onBackKey()) {
1173 WebView subwindow = mTabControl.getCurrentSubWindow();
1174 if (subwindow != null) {
1175 if (subwindow.canGoBack()) {
1176 subwindow.goBack();
1177 } else {
1178 dismissSubWindow(mTabControl.getCurrentTab());
1179 }
1180 } else {
1181 goBackOnePageOrQuit();
1182 }
1183 }
1184 }
1185
1186 // menu handling and state
1187 // TODO: maybe put into separate handler
1188
1189 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckb3417f02011-01-14 11:01:05 -08001190 if (mOptionsMenuHandler != null) {
1191 return mOptionsMenuHandler.onCreateOptionsMenu(menu);
1192 }
1193
John Reckd73c5a22010-12-22 10:22:50 -08001194 if (mMenuState == EMPTY_MENU) {
1195 return false;
1196 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001197 MenuInflater inflater = mActivity.getMenuInflater();
1198 inflater.inflate(R.menu.browser, menu);
1199 updateInLoadMenuItems(menu);
1200 // hold on to the menu reference here; it is used by the page callbacks
1201 // to update the menu based on loading state
1202 mCachedMenu = menu;
1203 return true;
1204 }
1205
1206 protected void onCreateContextMenu(ContextMenu menu, View v,
1207 ContextMenuInfo menuInfo) {
1208 if (v instanceof TitleBarBase) {
1209 return;
1210 }
1211 if (!(v instanceof WebView)) {
1212 return;
1213 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001214 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001215 WebView.HitTestResult result = webview.getHitTestResult();
1216 if (result == null) {
1217 return;
1218 }
1219
1220 int type = result.getType();
1221 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1222 Log.w(LOGTAG,
1223 "We should not show context menu when nothing is touched");
1224 return;
1225 }
1226 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1227 // let TextView handles context menu
1228 return;
1229 }
1230
1231 // Note, http://b/issue?id=1106666 is requesting that
1232 // an inflated menu can be used again. This is not available
1233 // yet, so inflate each time (yuk!)
1234 MenuInflater inflater = mActivity.getMenuInflater();
1235 inflater.inflate(R.menu.browsercontext, menu);
1236
1237 // Show the correct menu group
1238 final String extra = result.getExtra();
1239 menu.setGroupVisible(R.id.PHONE_MENU,
1240 type == WebView.HitTestResult.PHONE_TYPE);
1241 menu.setGroupVisible(R.id.EMAIL_MENU,
1242 type == WebView.HitTestResult.EMAIL_TYPE);
1243 menu.setGroupVisible(R.id.GEO_MENU,
1244 type == WebView.HitTestResult.GEO_TYPE);
1245 menu.setGroupVisible(R.id.IMAGE_MENU,
1246 type == WebView.HitTestResult.IMAGE_TYPE
1247 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1248 menu.setGroupVisible(R.id.ANCHOR_MENU,
1249 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1250 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001251 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1252 || type == WebView.HitTestResult.PHONE_TYPE
1253 || type == WebView.HitTestResult.EMAIL_TYPE
1254 || type == WebView.HitTestResult.GEO_TYPE;
1255 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1256 if (hitText) {
1257 menu.findItem(R.id.select_text_menu_id)
1258 .setOnMenuItemClickListener(new SelectText(webview));
1259 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001260 // Setup custom handling depending on the type
1261 switch (type) {
1262 case WebView.HitTestResult.PHONE_TYPE:
1263 menu.setHeaderTitle(Uri.decode(extra));
1264 menu.findItem(R.id.dial_context_menu_id).setIntent(
1265 new Intent(Intent.ACTION_VIEW, Uri
1266 .parse(WebView.SCHEME_TEL + extra)));
1267 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1268 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1269 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1270 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1271 addIntent);
1272 menu.findItem(R.id.copy_phone_context_menu_id)
1273 .setOnMenuItemClickListener(
1274 new Copy(extra));
1275 break;
1276
1277 case WebView.HitTestResult.EMAIL_TYPE:
1278 menu.setHeaderTitle(extra);
1279 menu.findItem(R.id.email_context_menu_id).setIntent(
1280 new Intent(Intent.ACTION_VIEW, Uri
1281 .parse(WebView.SCHEME_MAILTO + extra)));
1282 menu.findItem(R.id.copy_mail_context_menu_id)
1283 .setOnMenuItemClickListener(
1284 new Copy(extra));
1285 break;
1286
1287 case WebView.HitTestResult.GEO_TYPE:
1288 menu.setHeaderTitle(extra);
1289 menu.findItem(R.id.map_context_menu_id).setIntent(
1290 new Intent(Intent.ACTION_VIEW, Uri
1291 .parse(WebView.SCHEME_GEO
1292 + URLEncoder.encode(extra))));
1293 menu.findItem(R.id.copy_geo_context_menu_id)
1294 .setOnMenuItemClickListener(
1295 new Copy(extra));
1296 break;
1297
1298 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1299 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001300 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001301 // decide whether to show the open link in new tab option
1302 boolean showNewTab = mTabControl.canCreateNewTab();
1303 MenuItem newTabItem
1304 = menu.findItem(R.id.open_newtab_context_menu_id);
Michael Kolb2dd65c82011-01-14 11:07:38 -08001305 newTabItem.setTitle(
1306 BrowserSettings.getInstance().openInBackground()
1307 ? R.string.contextmenu_openlink_newwindow_background
1308 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001309 newTabItem.setVisible(showNewTab);
1310 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001311 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1312 newTabItem.setOnMenuItemClickListener(
1313 new MenuItem.OnMenuItemClickListener() {
1314 @Override
1315 public boolean onMenuItemClick(MenuItem item) {
1316 final HashMap<String, WebView> hrefMap =
1317 new HashMap<String, WebView>();
1318 hrefMap.put("webview", webview);
1319 final Message msg = mHandler.obtainMessage(
1320 FOCUS_NODE_HREF,
1321 R.id.open_newtab_context_menu_id,
1322 0, hrefMap);
1323 webview.requestFocusNodeHref(msg);
1324 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001325 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001326 });
1327 } else {
1328 newTabItem.setOnMenuItemClickListener(
1329 new MenuItem.OnMenuItemClickListener() {
1330 @Override
1331 public boolean onMenuItemClick(MenuItem item) {
1332 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -08001333 final Tab newTab = openTab(parent,
1334 extra, false);
Leon Scroggins026f2542010-11-22 13:26:12 -05001335 if (newTab != parent) {
1336 parent.addChildTab(newTab);
1337 }
1338 return true;
1339 }
1340 });
1341 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001342 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001343 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1344 break;
1345 }
1346 // otherwise fall through to handle image part
1347 case WebView.HitTestResult.IMAGE_TYPE:
1348 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1349 menu.setHeaderTitle(extra);
1350 }
1351 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1352 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1353 menu.findItem(R.id.download_context_menu_id).
Leon Scroggins63c02662010-11-18 15:16:27 -05001354 setOnMenuItemClickListener(new Download(mActivity, extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001355 menu.findItem(R.id.set_wallpaper_context_menu_id).
1356 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1357 extra));
1358 break;
1359
1360 default:
1361 Log.w(LOGTAG, "We should not get here.");
1362 break;
1363 }
1364 //update the ui
1365 mUi.onContextMenuCreated(menu);
1366 }
1367
1368 /**
1369 * As the menu can be open when loading state changes
1370 * we must manually update the state of the stop/reload menu
1371 * item
1372 */
1373 private void updateInLoadMenuItems(Menu menu) {
1374 if (menu == null) {
1375 return;
1376 }
1377 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1378 MenuItem src = mInLoad ?
1379 menu.findItem(R.id.stop_menu_id):
1380 menu.findItem(R.id.reload_menu_id);
1381 if (src != null) {
1382 dest.setIcon(src.getIcon());
1383 dest.setTitle(src.getTitle());
1384 }
1385 }
1386
John Reckb3417f02011-01-14 11:01:05 -08001387 boolean onPrepareOptionsMenu(Menu menu) {
1388 if (mOptionsMenuHandler != null) {
1389 return mOptionsMenuHandler.onPrepareOptionsMenu(menu);
1390 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001391 // This happens when the user begins to hold down the menu key, so
1392 // allow them to chord to get a shortcut.
1393 mCanChord = true;
1394 // Note: setVisible will decide whether an item is visible; while
1395 // setEnabled() will decide whether an item is enabled, which also means
1396 // whether the matching shortcut key will function.
1397 switch (mMenuState) {
1398 case EMPTY_MENU:
1399 if (mCurrentMenuState != mMenuState) {
1400 menu.setGroupVisible(R.id.MAIN_MENU, false);
1401 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1402 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1403 }
1404 break;
1405 default:
1406 if (mCurrentMenuState != mMenuState) {
1407 menu.setGroupVisible(R.id.MAIN_MENU, true);
1408 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1409 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1410 }
1411 final WebView w = getCurrentTopWebView();
1412 boolean canGoBack = false;
1413 boolean canGoForward = false;
1414 boolean isHome = false;
1415 if (w != null) {
1416 canGoBack = w.canGoBack();
1417 canGoForward = w.canGoForward();
1418 isHome = mSettings.getHomePage().equals(w.getUrl());
1419 }
1420 final MenuItem back = menu.findItem(R.id.back_menu_id);
1421 back.setEnabled(canGoBack);
1422
1423 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1424 home.setEnabled(!isHome);
1425
1426 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1427 forward.setEnabled(canGoForward);
1428
1429 // decide whether to show the share link option
1430 PackageManager pm = mActivity.getPackageManager();
1431 Intent send = new Intent(Intent.ACTION_SEND);
1432 send.setType("text/plain");
1433 ResolveInfo ri = pm.resolveActivity(send,
1434 PackageManager.MATCH_DEFAULT_ONLY);
1435 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1436
1437 boolean isNavDump = mSettings.isNavDump();
1438 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1439 nav.setVisible(isNavDump);
1440 nav.setEnabled(isNavDump);
1441
1442 boolean showDebugSettings = mSettings.showDebugSettings();
1443 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1444 counter.setVisible(showDebugSettings);
1445 counter.setEnabled(showDebugSettings);
1446
John Reckb3417f02011-01-14 11:01:05 -08001447 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1448 newtab.setEnabled(getTabControl().canCreateNewTab());
Michael Kolb8233fac2010-10-26 16:08:53 -07001449
1450 break;
1451 }
1452 mCurrentMenuState = mMenuState;
1453 return true;
1454 }
1455
1456 public boolean onOptionsItemSelected(MenuItem item) {
John Reckb3417f02011-01-14 11:01:05 -08001457 if (mOptionsMenuHandler != null &&
1458 mOptionsMenuHandler.onOptionsItemSelected(item)) {
1459 return true;
1460 }
1461
Michael Kolb8233fac2010-10-26 16:08:53 -07001462 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1463 // menu remains active, so ensure comboview is dismissed
1464 // if main menu option is selected
1465 removeComboView();
1466 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001467 if (!mCanChord) {
1468 // The user has already fired a shortcut with this hold down of the
1469 // menu key.
1470 return false;
1471 }
1472 if (null == getCurrentTopWebView()) {
1473 return false;
1474 }
1475 if (mMenuIsDown) {
1476 // The shortcut action consumes the MENU. Even if it is still down,
1477 // it won't trigger the next shortcut action. In the case of the
1478 // shortcut action triggering a new activity, like Bookmarks, we
1479 // won't get onKeyUp for MENU. So it is important to reset it here.
1480 mMenuIsDown = false;
1481 }
1482 switch (item.getItemId()) {
1483 // -- Main menu
1484 case R.id.new_tab_menu_id:
1485 openTabToHomePage();
1486 break;
1487
1488 case R.id.incognito_menu_id:
1489 openIncognitoTab();
1490 break;
1491
1492 case R.id.goto_menu_id:
1493 editUrl();
1494 break;
1495
1496 case R.id.bookmarks_menu_id:
1497 bookmarksOrHistoryPicker(false);
1498 break;
1499
1500 case R.id.active_tabs_menu_id:
1501 showActiveTabsPage();
1502 break;
1503
1504 case R.id.add_bookmark_menu_id:
1505 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
1506 break;
1507
1508 case R.id.stop_reload_menu_id:
1509 if (mInLoad) {
1510 stopLoading();
1511 } else {
1512 getCurrentTopWebView().reload();
1513 }
1514 break;
1515
1516 case R.id.back_menu_id:
1517 getCurrentTopWebView().goBack();
1518 break;
1519
1520 case R.id.forward_menu_id:
1521 getCurrentTopWebView().goForward();
1522 break;
1523
1524 case R.id.close_menu_id:
1525 // Close the subwindow if it exists.
1526 if (mTabControl.getCurrentSubWindow() != null) {
1527 dismissSubWindow(mTabControl.getCurrentTab());
1528 break;
1529 }
1530 closeCurrentTab();
1531 break;
1532
1533 case R.id.homepage_menu_id:
1534 Tab current = mTabControl.getCurrentTab();
1535 if (current != null) {
1536 dismissSubWindow(current);
1537 loadUrl(current.getWebView(), mSettings.getHomePage());
1538 }
1539 break;
1540
1541 case R.id.preferences_menu_id:
1542 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1543 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1544 getCurrentTopWebView().getUrl());
1545 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1546 break;
1547
1548 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001549 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001550 break;
1551
1552 case R.id.page_info_menu_id:
1553 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1554 false);
1555 break;
1556
1557 case R.id.classic_history_menu_id:
1558 bookmarksOrHistoryPicker(true);
1559 break;
1560
1561 case R.id.title_bar_share_page_url:
1562 case R.id.share_page_menu_id:
1563 Tab currentTab = mTabControl.getCurrentTab();
1564 if (null == currentTab) {
1565 mCanChord = false;
1566 return false;
1567 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001568 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001569 break;
1570
1571 case R.id.dump_nav_menu_id:
1572 getCurrentTopWebView().debugDump();
1573 break;
1574
1575 case R.id.dump_counters_menu_id:
1576 getCurrentTopWebView().dumpV8Counters();
1577 break;
1578
1579 case R.id.zoom_in_menu_id:
1580 getCurrentTopWebView().zoomIn();
1581 break;
1582
1583 case R.id.zoom_out_menu_id:
1584 getCurrentTopWebView().zoomOut();
1585 break;
1586
1587 case R.id.view_downloads_menu_id:
1588 viewDownloads();
1589 break;
1590
1591 case R.id.window_one_menu_id:
1592 case R.id.window_two_menu_id:
1593 case R.id.window_three_menu_id:
1594 case R.id.window_four_menu_id:
1595 case R.id.window_five_menu_id:
1596 case R.id.window_six_menu_id:
1597 case R.id.window_seven_menu_id:
1598 case R.id.window_eight_menu_id:
1599 {
1600 int menuid = item.getItemId();
1601 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1602 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1603 Tab desiredTab = mTabControl.getTab(id);
1604 if (desiredTab != null &&
1605 desiredTab != mTabControl.getCurrentTab()) {
1606 switchToTab(id);
1607 }
1608 break;
1609 }
1610 }
1611 }
1612 break;
1613
1614 default:
1615 return false;
1616 }
1617 mCanChord = false;
1618 return true;
1619 }
1620
1621 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001622 // Let the History and Bookmark fragments handle menus they created.
1623 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1624 return false;
1625 }
1626
Michael Kolb8233fac2010-10-26 16:08:53 -07001627 // chording is not an issue with context menus, but we use the same
1628 // options selector, so set mCanChord to true so we can access them.
1629 mCanChord = true;
1630 int id = item.getItemId();
1631 boolean result = true;
1632 switch (id) {
1633 // For the context menu from the title bar
1634 case R.id.title_bar_copy_page_url:
1635 Tab currentTab = mTabControl.getCurrentTab();
1636 if (null == currentTab) {
1637 result = false;
1638 break;
1639 }
1640 WebView mainView = currentTab.getWebView();
1641 if (null == mainView) {
1642 result = false;
1643 break;
1644 }
1645 copy(mainView.getUrl());
1646 break;
1647 // -- Browser context menu
1648 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001649 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001650 case R.id.copy_link_context_menu_id:
1651 final WebView webView = getCurrentTopWebView();
1652 if (null == webView) {
1653 result = false;
1654 break;
1655 }
1656 final HashMap<String, WebView> hrefMap =
1657 new HashMap<String, WebView>();
1658 hrefMap.put("webview", webView);
1659 final Message msg = mHandler.obtainMessage(
1660 FOCUS_NODE_HREF, id, 0, hrefMap);
1661 webView.requestFocusNodeHref(msg);
1662 break;
1663
1664 default:
1665 // For other context menus
1666 result = onOptionsItemSelected(item);
1667 }
1668 mCanChord = false;
1669 return result;
1670 }
1671
1672 /**
1673 * support programmatically opening the context menu
1674 */
1675 public void openContextMenu(View view) {
1676 mActivity.openContextMenu(view);
1677 }
1678
1679 /**
1680 * programmatically open the options menu
1681 */
1682 public void openOptionsMenu() {
1683 mActivity.openOptionsMenu();
1684 }
1685
1686 public boolean onMenuOpened(int featureId, Menu menu) {
1687 if (mOptionsMenuOpen) {
1688 if (mConfigChanged) {
1689 // We do not need to make any changes to the state of the
1690 // title bar, since the only thing that happened was a
1691 // change in orientation
1692 mConfigChanged = false;
1693 } else {
1694 if (!mExtendedMenuOpen) {
1695 mExtendedMenuOpen = true;
1696 mUi.onExtendedMenuOpened();
1697 } else {
1698 // Switching the menu back to icon view, so show the
1699 // title bar once again.
1700 mExtendedMenuOpen = false;
1701 mUi.onExtendedMenuClosed(mInLoad);
1702 mUi.onOptionsMenuOpened();
1703 }
1704 }
1705 } else {
1706 // The options menu is closed, so open it, and show the title
1707 mOptionsMenuOpen = true;
1708 mConfigChanged = false;
1709 mExtendedMenuOpen = false;
1710 mUi.onOptionsMenuOpened();
1711 }
1712 return true;
1713 }
1714
1715 public void onOptionsMenuClosed(Menu menu) {
1716 mOptionsMenuOpen = false;
1717 mUi.onOptionsMenuClosed(mInLoad);
1718 }
1719
1720 public void onContextMenuClosed(Menu menu) {
1721 mUi.onContextMenuClosed(menu, mInLoad);
1722 }
1723
1724 // Helper method for getting the top window.
1725 @Override
1726 public WebView getCurrentTopWebView() {
1727 return mTabControl.getCurrentTopWebView();
1728 }
1729
1730 @Override
1731 public WebView getCurrentWebView() {
1732 return mTabControl.getCurrentWebView();
1733 }
1734
1735 /*
1736 * This method is called as a result of the user selecting the options
1737 * menu to see the download window. It shows the download window on top of
1738 * the current window.
1739 */
1740 void viewDownloads() {
1741 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1742 mActivity.startActivity(intent);
1743 }
1744
1745 // action mode
1746
1747 void onActionModeStarted(ActionMode mode) {
1748 mUi.onActionModeStarted(mode);
1749 mActionMode = mode;
1750 }
1751
1752 /*
1753 * True if a custom ActionMode (i.e. find or select) is in use.
1754 */
1755 @Override
1756 public boolean isInCustomActionMode() {
1757 return mActionMode != null;
1758 }
1759
1760 /*
1761 * End the current ActionMode.
1762 */
1763 @Override
1764 public void endActionMode() {
1765 if (mActionMode != null) {
1766 mActionMode.finish();
1767 }
1768 }
1769
1770 /*
1771 * Called by find and select when they are finished. Replace title bars
1772 * as necessary.
1773 */
1774 public void onActionModeFinished(ActionMode mode) {
1775 if (!isInCustomActionMode()) return;
1776 mUi.onActionModeFinished(mInLoad);
1777 mActionMode = null;
1778 }
1779
1780 boolean isInLoad() {
1781 return mInLoad;
1782 }
1783
1784 // bookmark handling
1785
1786 /**
1787 * add the current page as a bookmark to the given folder id
1788 * @param folderId use -1 for the default folder
1789 */
1790 @Override
1791 public void bookmarkCurrentPage(long folderId) {
1792 Intent i = new Intent(mActivity,
1793 AddBookmarkPage.class);
1794 WebView w = getCurrentTopWebView();
1795 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1796 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1797 String touchIconUrl = w.getTouchIconUrl();
1798 if (touchIconUrl != null) {
1799 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1800 WebSettings settings = w.getSettings();
1801 if (settings != null) {
1802 i.putExtra(AddBookmarkPage.USER_AGENT,
1803 settings.getUserAgentString());
1804 }
1805 }
1806 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1807 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1808 getDesiredThumbnailHeight(mActivity)));
1809 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1810 i.putExtra(BrowserContract.Bookmarks.PARENT,
1811 folderId);
1812 // Put the dialog at the upper right of the screen, covering the
1813 // star on the title bar.
1814 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1815 mActivity.startActivity(i);
1816 }
1817
1818 // file chooser
1819 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1820 mUploadHandler = new UploadHandler(this);
1821 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1822 }
1823
1824 // thumbnails
1825
1826 /**
1827 * Return the desired width for thumbnail screenshots, which are stored in
1828 * the database, and used on the bookmarks screen.
1829 * @param context Context for finding out the density of the screen.
1830 * @return desired width for thumbnail screenshot.
1831 */
1832 static int getDesiredThumbnailWidth(Context context) {
1833 return context.getResources().getDimensionPixelOffset(
1834 R.dimen.bookmarkThumbnailWidth);
1835 }
1836
1837 /**
1838 * Return the desired height for thumbnail screenshots, which are stored in
1839 * the database, and used on the bookmarks screen.
1840 * @param context Context for finding out the density of the screen.
1841 * @return desired height for thumbnail screenshot.
1842 */
1843 static int getDesiredThumbnailHeight(Context context) {
1844 return context.getResources().getDimensionPixelOffset(
1845 R.dimen.bookmarkThumbnailHeight);
1846 }
1847
1848 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001849 // We render to a bitmap 2x the desired size so that we can then
1850 // re-scale it with filtering since canvas.scale doesn't filter
1851 // This helps reduce aliasing at the cost of being slightly blurry
1852 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001853 Picture thumbnail = view.capturePicture();
1854 if (thumbnail == null) {
1855 return null;
1856 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001857 width *= filter_scale;
1858 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001859 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1860 Canvas canvas = new Canvas(bm);
1861 // May need to tweak these values to determine what is the
1862 // best scale factor
1863 int thumbnailWidth = thumbnail.getWidth();
1864 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001865 float scaleFactor = 1.0f;
Michael Kolb8233fac2010-10-26 16:08:53 -07001866 if (thumbnailWidth > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001867 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001868 } else {
1869 return null;
1870 }
John Reckfe49ab42010-11-16 17:09:37 -08001871
Michael Kolb8233fac2010-10-26 16:08:53 -07001872 if (view.getWidth() > view.getHeight() &&
1873 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
1874 // If the device is in landscape and the page is shorter
John Reckfe49ab42010-11-16 17:09:37 -08001875 // than the height of the view, center the thumnail and crop the sides
1876 scaleFactor = (float) height / (float)thumbnailHeight;
1877 float wx = (thumbnailWidth * scaleFactor) - width;
1878 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001879 }
1880
John Reckfe49ab42010-11-16 17:09:37 -08001881 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001882
1883 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001884 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
1885 height / filter_scale, true);
1886 bm.recycle();
1887 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001888 }
1889
1890 private void updateScreenshot(WebView view) {
1891 // If this is a bookmarked site, add a screenshot to the database.
1892 // FIXME: When should we update? Every time?
1893 // FIXME: Would like to make sure there is actually something to
1894 // draw, but the API for that (WebViewCore.pictureReady()) is not
1895 // currently accessible here.
1896
1897 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1898 getDesiredThumbnailHeight(mActivity));
1899 if (bm == null) {
1900 return;
1901 }
1902
1903 final ContentResolver cr = mActivity.getContentResolver();
1904 final String url = view.getUrl();
1905 final String originalUrl = view.getOriginalUrl();
1906
John Recka00cbbd2010-12-16 12:38:19 -08001907 // Only update thumbnails for web urls (http(s)://), not for
1908 // about:, javascript:, data:, etc...
John Reck9d038482011-01-04 17:02:09 -08001909 if (url != null && Patterns.WEB_URL.matcher(url).matches()) {
John Recka00cbbd2010-12-16 12:38:19 -08001910 new AsyncTask<Void, Void, Void>() {
1911 @Override
1912 protected Void doInBackground(Void... unused) {
1913 Cursor cursor = null;
1914 try {
1915 // TODO: Clean this up
1916 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
1917 if (cursor != null && cursor.moveToFirst()) {
1918 final ByteArrayOutputStream os =
1919 new ByteArrayOutputStream();
1920 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07001921
John Recka00cbbd2010-12-16 12:38:19 -08001922 ContentValues values = new ContentValues();
1923 values.put(Images.THUMBNAIL, os.toByteArray());
1924 values.put(Images.URL, cursor.getString(0));
Michael Kolb8233fac2010-10-26 16:08:53 -07001925
John Recka00cbbd2010-12-16 12:38:19 -08001926 do {
1927 cr.update(Images.CONTENT_URI, values, null, null);
1928 } while (cursor.moveToNext());
1929 }
1930 } catch (IllegalStateException e) {
1931 // Ignore
1932 } finally {
1933 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07001934 }
John Recka00cbbd2010-12-16 12:38:19 -08001935 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07001936 }
John Recka00cbbd2010-12-16 12:38:19 -08001937 }.execute();
1938 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001939 }
1940
1941 private class Copy implements OnMenuItemClickListener {
1942 private CharSequence mText;
1943
1944 public boolean onMenuItemClick(MenuItem item) {
1945 copy(mText);
1946 return true;
1947 }
1948
1949 public Copy(CharSequence toCopy) {
1950 mText = toCopy;
1951 }
1952 }
1953
Leon Scroggins63c02662010-11-18 15:16:27 -05001954 private static class Download implements OnMenuItemClickListener {
1955 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001956 private String mText;
1957
1958 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05001959 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
1960 null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001961 return true;
1962 }
1963
Leon Scroggins63c02662010-11-18 15:16:27 -05001964 public Download(Activity activity, String toDownload) {
1965 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001966 mText = toDownload;
1967 }
1968 }
1969
Cary Clark8974d282010-11-22 10:46:05 -05001970 private static class SelectText implements OnMenuItemClickListener {
1971 private WebView mWebView;
1972
1973 public boolean onMenuItemClick(MenuItem item) {
1974 if (mWebView != null) {
1975 return mWebView.selectText();
1976 }
1977 return false;
1978 }
1979
1980 public SelectText(WebView webView) {
1981 mWebView = webView;
1982 }
1983
1984 }
1985
Michael Kolb8233fac2010-10-26 16:08:53 -07001986 /********************** TODO: UI stuff *****************************/
1987
1988 // these methods have been copied, they still need to be cleaned up
1989
1990 /****************** tabs ***************************************************/
1991
1992 // basic tab interactions:
1993
1994 // it is assumed that tabcontrol already knows about the tab
1995 protected void addTab(Tab tab) {
1996 mUi.addTab(tab);
1997 }
1998
1999 protected void removeTab(Tab tab) {
2000 mUi.removeTab(tab);
2001 mTabControl.removeTab(tab);
2002 }
2003
2004 protected void setActiveTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002005 mTabControl.setCurrentTab(tab);
Michael Kolb77df4562010-11-19 14:49:34 -08002006 // the tab is guaranteed to have a webview after setCurrentTab
2007 mUi.setActiveTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002008 }
2009
2010 protected void closeEmptyChildTab() {
2011 Tab current = mTabControl.getCurrentTab();
2012 if (current != null
2013 && current.getWebView().copyBackForwardList().getSize() == 0) {
2014 Tab parent = current.getParentTab();
2015 if (parent != null) {
2016 switchToTab(mTabControl.getTabIndex(parent));
2017 closeTab(current);
2018 }
2019 }
2020 }
2021
2022 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
2023 Log.i(LOGTAG, "Reusing tab for " + appId);
2024 // Dismiss the subwindow if applicable.
2025 dismissSubWindow(appTab);
2026 // Since we might kill the WebView, remove it from the
2027 // content view first.
2028 mUi.detachTab(appTab);
2029 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002030 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002031 // TODO: analyze why the remove and add are necessary
2032 mUi.attachTab(appTab);
2033 if (mTabControl.getCurrentTab() != appTab) {
2034 switchToTab(mTabControl.getTabIndex(appTab));
John Reck30c714c2010-12-16 17:30:34 -08002035 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002036 } else {
2037 // If the tab was the current tab, we have to attach
2038 // it to the view system again.
2039 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002040 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002041 }
2042 }
2043
2044 // Remove the sub window if it exists. Also called by TabControl when the
2045 // user clicks the 'X' to dismiss a sub window.
2046 public void dismissSubWindow(Tab tab) {
2047 removeSubWindow(tab);
2048 // dismiss the subwindow. This will destroy the WebView.
2049 tab.dismissSubWindow();
2050 getCurrentTopWebView().requestFocus();
2051 }
2052
2053 @Override
2054 public void removeSubWindow(Tab t) {
2055 if (t.getSubWebView() != null) {
2056 mUi.removeSubWindow(t.getSubViewContainer());
2057 }
2058 }
2059
2060 @Override
2061 public void attachSubWindow(Tab tab) {
2062 if (tab.getSubWebView() != null) {
2063 mUi.attachSubWindow(tab.getSubViewContainer());
2064 getCurrentTopWebView().requestFocus();
2065 }
2066 }
2067
Michael Kolb843510f2010-12-09 10:51:49 -08002068 @Override
2069 public Tab openTabToHomePage() {
2070 // check for max tabs
2071 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002072 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2073 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002074 } else {
2075 mUi.showMaxTabsWarning();
2076 return null;
2077 }
2078 }
2079
Michael Kolb18eb3772010-12-10 14:29:51 -08002080 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2081 if (mSettings.openInBackground() && !forceForeground) {
2082 Tab tab = mTabControl.createNewTab(false, null, null,
2083 (parent != null) && parent.isPrivateBrowsingEnabled());
2084 if (tab != null) {
2085 addTab(tab);
2086 WebView view = tab.getWebView();
2087 loadUrl(view, url);
2088 }
2089 return tab;
2090 } else {
2091 return openTabAndShow(parent, new UrlData(url), false, null);
2092 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002093 }
2094
Michael Kolb18eb3772010-12-10 14:29:51 -08002095
Michael Kolb8233fac2010-10-26 16:08:53 -07002096 // This method does a ton of stuff. It will attempt to create a new tab
2097 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2098 // url isn't null, it will load the given url.
Michael Kolb18eb3772010-12-10 14:29:51 -08002099 public Tab openTabAndShow(Tab parent, UrlData urlData, boolean closeOnExit,
Michael Kolb8233fac2010-10-26 16:08:53 -07002100 String appId) {
2101 final Tab currentTab = mTabControl.getCurrentTab();
2102 if (mTabControl.canCreateNewTab()) {
2103 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Michael Kolb18eb3772010-12-10 14:29:51 -08002104 urlData.mUrl,
2105 (parent != null) && parent.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -07002106 WebView webview = tab.getWebView();
2107 // We must set the new tab as the current tab to reflect the old
2108 // animation behavior.
2109 addTab(tab);
2110 setActiveTab(tab);
2111 if (!urlData.isEmpty()) {
2112 loadUrlDataIn(tab, urlData);
2113 }
2114 return tab;
2115 } else {
2116 // Get rid of the subwindow if it exists
2117 dismissSubWindow(currentTab);
2118 if (!urlData.isEmpty()) {
2119 // Load the given url.
2120 loadUrlDataIn(currentTab, urlData);
2121 }
2122 return currentTab;
2123 }
2124 }
2125
Michael Kolb8233fac2010-10-26 16:08:53 -07002126 @Override
2127 public Tab openIncognitoTab() {
2128 if (mTabControl.canCreateNewTab()) {
2129 Tab currentTab = mTabControl.getCurrentTab();
2130 Tab tab = mTabControl.createNewTab(false, null, null, true);
2131 addTab(tab);
2132 setActiveTab(tab);
2133 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002134 } else {
2135 mUi.showMaxTabsWarning();
2136 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002137 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002138 }
2139
2140 /**
2141 * @param index Index of the tab to change to, as defined by
2142 * mTabControl.getTabIndex(Tab t).
2143 * @return boolean True if we successfully switched to a different tab. If
2144 * the indexth tab is null, or if that tab is the same as
2145 * the current one, return false.
2146 */
2147 @Override
2148 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002149 // hide combo view if open
2150 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002151 Tab tab = mTabControl.getTab(index);
2152 Tab currentTab = mTabControl.getCurrentTab();
2153 if (tab == null || tab == currentTab) {
2154 return false;
2155 }
2156 setActiveTab(tab);
2157 return true;
2158 }
2159
2160 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002161 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002162 // hide combo view if open
2163 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002164 final Tab current = mTabControl.getCurrentTab();
2165 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002166 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002167 return;
2168 }
2169 final Tab parent = current.getParentTab();
2170 int indexToShow = -1;
2171 if (parent != null) {
2172 indexToShow = mTabControl.getTabIndex(parent);
2173 } else {
2174 final int currentIndex = mTabControl.getCurrentIndex();
2175 // Try to move to the tab to the right
2176 indexToShow = currentIndex + 1;
2177 if (indexToShow > mTabControl.getTabCount() - 1) {
2178 // Try to move to the tab to the left
2179 indexToShow = currentIndex - 1;
2180 }
2181 }
2182 if (switchToTab(indexToShow)) {
2183 // Close window
2184 closeTab(current);
2185 }
2186 }
2187
2188 /**
2189 * Close the tab, remove its associated title bar, and adjust mTabControl's
2190 * current tab to a valid value.
2191 */
2192 @Override
2193 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002194 // hide combo view if open
2195 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002196 int currentIndex = mTabControl.getCurrentIndex();
2197 int removeIndex = mTabControl.getTabIndex(tab);
2198 removeTab(tab);
2199 if (currentIndex >= removeIndex && currentIndex != 0) {
2200 currentIndex--;
2201 }
2202 Tab newtab = mTabControl.getTab(currentIndex);
2203 setActiveTab(newtab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002204 }
2205
2206 /**************** TODO: Url loading clean up *******************************/
2207
2208 // Called when loading from context menu or LOAD_URL message
2209 protected void loadUrlFromContext(WebView view, String url) {
2210 // In case the user enters nothing.
2211 if (url != null && url.length() != 0 && view != null) {
2212 url = UrlUtils.smartUrlFilter(url);
2213 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2214 loadUrl(view, url);
2215 }
2216 }
2217 }
2218
2219 /**
2220 * Load the URL into the given WebView and update the title bar
2221 * to reflect the new load. Call this instead of WebView.loadUrl
2222 * directly.
2223 * @param view The WebView used to load url.
2224 * @param url The URL to load.
2225 */
2226 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002227 view.loadUrl(url);
2228 }
2229
2230 /**
2231 * Load UrlData into a Tab and update the title bar to reflect the new
2232 * load. Call this instead of UrlData.loadIn directly.
2233 * @param t The Tab used to load.
2234 * @param data The UrlData being loaded.
2235 */
2236 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002237 data.loadIn(t);
2238 }
2239
John Reck30c714c2010-12-16 17:30:34 -08002240 @Override
2241 public void onUserCanceledSsl(Tab tab) {
2242 WebView web = tab.getWebView();
2243 // TODO: Figure out the "right" behavior
2244 if (web.canGoBack()) {
2245 web.goBack();
2246 } else {
2247 web.loadUrl(mSettings.getHomePage());
2248 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002249 }
2250
2251 void goBackOnePageOrQuit() {
2252 Tab current = mTabControl.getCurrentTab();
2253 if (current == null) {
2254 /*
2255 * Instead of finishing the activity, simply push this to the back
2256 * of the stack and let ActivityManager to choose the foreground
2257 * activity. As BrowserActivity is singleTask, it will be always the
2258 * root of the task. So we can use either true or false for
2259 * moveTaskToBack().
2260 */
2261 mActivity.moveTaskToBack(true);
2262 return;
2263 }
2264 WebView w = current.getWebView();
2265 if (w.canGoBack()) {
2266 w.goBack();
2267 } else {
2268 // Check to see if we are closing a window that was created by
2269 // another window. If so, we switch back to that window.
2270 Tab parent = current.getParentTab();
2271 if (parent != null) {
2272 switchToTab(mTabControl.getTabIndex(parent));
2273 // Now we close the other tab
2274 closeTab(current);
2275 } else {
2276 if (current.closeOnExit()) {
2277 // force the tab's inLoad() to be false as we are going to
2278 // either finish the activity or remove the tab. This will
2279 // ensure pauseWebViewTimers() taking action.
Michael Kolb70976932010-11-30 11:34:01 -08002280 current.clearInPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07002281 if (mTabControl.getTabCount() == 1) {
2282 mActivity.finish();
2283 return;
2284 }
2285 if (mActivityPaused) {
2286 Log.e(LOGTAG, "BrowserActivity is already paused "
2287 + "while handing goBackOnePageOrQuit.");
2288 }
Michael Kolb70976932010-11-30 11:34:01 -08002289 pauseWebViewTimers(current);
Michael Kolb8233fac2010-10-26 16:08:53 -07002290 removeTab(current);
2291 }
2292 /*
2293 * Instead of finishing the activity, simply push this to the back
2294 * of the stack and let ActivityManager to choose the foreground
2295 * activity. As BrowserActivity is singleTask, it will be always the
2296 * root of the task. So we can use either true or false for
2297 * moveTaskToBack().
2298 */
2299 mActivity.moveTaskToBack(true);
2300 }
2301 }
2302 }
2303
2304 /**
2305 * Feed the previously stored results strings to the BrowserProvider so that
2306 * the SearchDialog will show them instead of the standard searches.
2307 * @param result String to show on the editable line of the SearchDialog.
2308 */
2309 @Override
2310 public void showVoiceSearchResults(String result) {
2311 ContentProviderClient client = mActivity.getContentResolver()
2312 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2313 ContentProvider prov = client.getLocalContentProvider();
2314 BrowserProvider bp = (BrowserProvider) prov;
2315 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2316 client.release();
2317
2318 Bundle bundle = createGoogleSearchSourceBundle(
2319 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2320 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2321 startSearch(result, false, bundle, false);
2322 }
2323
2324 private void startSearch(String initialQuery, boolean selectInitialQuery,
2325 Bundle appSearchData, boolean globalSearch) {
2326 if (appSearchData == null) {
2327 appSearchData = createGoogleSearchSourceBundle(
2328 GOOGLE_SEARCH_SOURCE_TYPE);
2329 }
2330
2331 SearchEngine searchEngine = mSettings.getSearchEngine();
2332 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2333 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2334 }
2335 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2336 globalSearch);
2337 }
2338
2339 private Bundle createGoogleSearchSourceBundle(String source) {
2340 Bundle bundle = new Bundle();
2341 bundle.putString(Search.SOURCE, source);
2342 return bundle;
2343 }
2344
2345 /**
2346 * handle key events in browser
2347 *
2348 * @param keyCode
2349 * @param event
2350 * @return true if handled, false to pass to super
2351 */
2352 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002353 boolean noModifiers = event.hasNoModifiers();
2354
Michael Kolb8233fac2010-10-26 16:08:53 -07002355 // Even if MENU is already held down, we need to call to super to open
2356 // the IME on long press.
Cary Clark160bbb92011-01-10 11:17:07 -05002357 if (!noModifiers && KeyEvent.KEYCODE_MENU == keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002358 mMenuIsDown = true;
2359 return false;
2360 }
2361 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2362 // still down, we don't want to trigger the search. Pretend to consume
2363 // the key and do nothing.
2364 if (mMenuIsDown) return true;
2365
Cary Clark8ff8c662010-12-29 15:03:05 -05002366 WebView webView = getCurrentTopWebView();
2367 if (webView == null) return false;
2368
Cary Clark160bbb92011-01-10 11:17:07 -05002369 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2370 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002371
Michael Kolb8233fac2010-10-26 16:08:53 -07002372 switch(keyCode) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002373 case KeyEvent.KEYCODE_ESCAPE:
Cary Clark160bbb92011-01-10 11:17:07 -05002374 if (!noModifiers) break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002375 stopLoading();
2376 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07002377 case KeyEvent.KEYCODE_SPACE:
2378 // WebView/WebTextView handle the keys in the KeyDown. As
2379 // the Activity's shortcut keys are only handled when WebView
2380 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002381 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002382 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002383 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002384 pageDown();
2385 }
2386 return true;
2387 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002388 if (!noModifiers) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002389 if (event.getRepeatCount() == 0) {
2390 event.startTracking();
2391 return true;
2392 } else if (mUi.showsWeb()
2393 && event.isLongPress()) {
2394 bookmarksOrHistoryPicker(true);
2395 return true;
2396 }
2397 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002398 case KeyEvent.KEYCODE_DPAD_LEFT:
2399 if (ctrl) {
2400 webView.goBack();
2401 return true;
2402 }
2403 break;
2404 case KeyEvent.KEYCODE_DPAD_RIGHT:
2405 if (ctrl) {
2406 webView.goForward();
2407 return true;
2408 }
2409 break;
2410 case KeyEvent.KEYCODE_A:
2411 if (ctrl) {
2412 webView.selectAll();
2413 return true;
2414 }
2415 break;
2416 case KeyEvent.KEYCODE_B:
2417 if (ctrl) {
2418 bookmarksOrHistoryPicker(false);
2419 return true;
2420 }
2421 break;
2422 case KeyEvent.KEYCODE_C:
2423 if (ctrl) {
2424 webView.copySelection();
2425 return true;
2426 }
2427 break;
2428 case KeyEvent.KEYCODE_D:
2429 if (ctrl) {
2430 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
2431 return true;
2432 }
2433 break;
2434// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
2435 case KeyEvent.KEYCODE_F:
2436 if (ctrl) {
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05002437 webView.showFindDialog(null, true);
Cary Clark8ff8c662010-12-29 15:03:05 -05002438 return true;
2439 }
2440 break;
2441// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
2442 case KeyEvent.KEYCODE_H:
2443 if (ctrl) {
2444 bookmarksOrHistoryPicker(true);
2445 return true;
2446 }
2447 break;
2448// case KeyEvent.KEYCODE_I: // unused
2449 case KeyEvent.KEYCODE_J:
2450 if (ctrl) {
2451 viewDownloads();
2452 return true;
2453 }
2454 break;
2455// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
2456 case KeyEvent.KEYCODE_L:
2457 if (ctrl) {
2458 editUrl();
2459 return true;
2460 }
2461 break;
2462// case KeyEvent.KEYCODE_M: // unused
2463// case KeyEvent.KEYCODE_N: // in Chrome: new window
2464// case KeyEvent.KEYCODE_O: // in Chrome: open file
2465// case KeyEvent.KEYCODE_P: // in Chrome: print page
2466// case KeyEvent.KEYCODE_Q: // unused
2467 case KeyEvent.KEYCODE_R:
2468 if (ctrl) {
2469 if (mInLoad) {
2470 stopLoading();
2471 } else {
2472 webView.reload();
2473 }
2474 return true;
2475 }
2476 break;
2477// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2478 case KeyEvent.KEYCODE_T:
2479 if (ctrl) {
2480 if (event.isShiftPressed()) {
2481 openIncognitoTab();
2482 } else {
2483 openTabToHomePage();
2484 }
2485 return true;
2486 }
2487 break;
2488// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2489// case KeyEvent.KEYCODE_V: // text view intercepts to paste
2490 case KeyEvent.KEYCODE_W:
2491 if (ctrl) {
2492 closeCurrentTab();
2493 return true;
2494 }
2495 break;
2496// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2497// case KeyEvent.KEYCODE_Y: // unused
2498// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002499 }
2500 return false;
2501 }
2502
2503 boolean onKeyUp(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002504 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002505 switch(keyCode) {
2506 case KeyEvent.KEYCODE_MENU:
2507 mMenuIsDown = false;
2508 break;
2509 case KeyEvent.KEYCODE_BACK:
2510 if (event.isTracking() && !event.isCanceled()) {
2511 onBackKey();
2512 return true;
2513 }
2514 break;
2515 }
2516 return false;
2517 }
2518
2519 public boolean isMenuDown() {
2520 return mMenuIsDown;
2521 }
2522
Ben Murdoch8029a772010-11-16 11:58:21 +00002523 public void setupAutoFill(Message message) {
2524 // Open the settings activity at the AutoFill profile fragment so that
2525 // the user can create a new profile. When they return, we will dispatch
2526 // the message so that we can autofill the form using their new profile.
2527 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2528 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2529 AutoFillSettingsFragment.class.getName());
2530 mAutoFillSetupMessage = message;
2531 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2532 }
John Reckb3417f02011-01-14 11:01:05 -08002533
2534 @Override
2535 public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
2536 mOptionsMenuHandler = handler;
2537 }
2538
2539 @Override
2540 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
2541 if (mOptionsMenuHandler == handler) {
2542 mOptionsMenuHandler = null;
2543 }
2544 }
2545
Michael Kolb8233fac2010-10-26 16:08:53 -07002546}