blob: a2ddc8c9140b2793f9d16960c7d17f3bdd714659 [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;
Michael Kolb8233fac2010-10-26 16:08:53 -070066import android.view.Menu;
67import android.view.MenuInflater;
68import android.view.MenuItem;
69import android.view.MenuItem.OnMenuItemClickListener;
70import android.view.View;
71import android.webkit.CookieManager;
72import android.webkit.CookieSyncManager;
73import android.webkit.HttpAuthHandler;
74import android.webkit.SslErrorHandler;
75import android.webkit.ValueCallback;
76import android.webkit.WebChromeClient;
77import android.webkit.WebIconDatabase;
78import android.webkit.WebSettings;
79import android.webkit.WebView;
Michael Kolb8233fac2010-10-26 16:08:53 -070080
81import java.io.ByteArrayOutputStream;
82import java.io.File;
83import java.net.URLEncoder;
84import java.util.Calendar;
85import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -080086import java.util.List;
Michael Kolb8233fac2010-10-26 16:08:53 -070087
88/**
89 * Controller for browser
90 */
91public class Controller
92 implements WebViewController, UiController {
93
94 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -080095 private static final String SEND_APP_ID_EXTRA =
96 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
97
Michael Kolb8233fac2010-10-26 16:08:53 -070098
99 // public message ids
100 public final static int LOAD_URL = 1001;
101 public final static int STOP_LOAD = 1002;
102
103 // Message Ids
104 private static final int FOCUS_NODE_HREF = 102;
105 private static final int RELEASE_WAKELOCK = 107;
106
107 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
108
109 private static final int OPEN_BOOKMARKS = 201;
110
111 private static final int EMPTY_MENU = -1;
112
Michael Kolb8233fac2010-10-26 16:08:53 -0700113 // activity requestCode
114 final static int PREFERENCES_PAGE = 3;
115 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000116 final static int AUTOFILL_SETUP = 5;
117
Michael Kolb8233fac2010-10-26 16:08:53 -0700118 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
119
120 // As the ids are dynamically created, we can't guarantee that they will
121 // be in sequence, so this static array maps ids to a window number.
122 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
123 { R.id.window_one_menu_id, R.id.window_two_menu_id,
124 R.id.window_three_menu_id, R.id.window_four_menu_id,
125 R.id.window_five_menu_id, R.id.window_six_menu_id,
126 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
127
128 // "source" parameter for Google search through search key
129 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
130 // "source" parameter for Google search through simplily type
131 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
132
133 private Activity mActivity;
134 private UI mUi;
135 private TabControl mTabControl;
136 private BrowserSettings mSettings;
137 private WebViewFactory mFactory;
John Reckb3417f02011-01-14 11:01:05 -0800138 private OptionsMenuHandler mOptionsMenuHandler = null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700139
140 private WakeLock mWakeLock;
141
142 private UrlHandler mUrlHandler;
143 private UploadHandler mUploadHandler;
144 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700145 private PageDialogsHandler mPageDialogsHandler;
146 private NetworkStateHandler mNetworkHandler;
147
Ben Murdoch8029a772010-11-16 11:58:21 +0000148 private Message mAutoFillSetupMessage;
149
Michael Kolb8233fac2010-10-26 16:08:53 -0700150 private boolean mShouldShowErrorConsole;
151
152 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
153
154 // FIXME, temp address onPrepareMenu performance problem.
155 // When we move everything out of view, we should rewrite this.
156 private int mCurrentMenuState = 0;
157 private int mMenuState = R.id.MAIN_MENU;
158 private int mOldMenuState = EMPTY_MENU;
159 private Menu mCachedMenu;
160
161 // Used to prevent chording to result in firing two shortcuts immediately
162 // one after another. Fixes bug 1211714.
163 boolean mCanChord;
164 private boolean mMenuIsDown;
165
166 // For select and find, we keep track of the ActionMode so that
167 // finish() can be called as desired.
168 private ActionMode mActionMode;
169
170 /**
171 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
172 * of whether the configuration has changed. The first onMenuOpened call
173 * after a configuration change is simply a reopening of the same menu
174 * (i.e. mIconView did not change).
175 */
176 private boolean mConfigChanged;
177
178 /**
179 * Keeps track of whether the options menu is open. This is important in
180 * determining whether to show or hide the title bar overlay
181 */
182 private boolean mOptionsMenuOpen;
183
184 /**
185 * Whether or not the options menu is in its bigger, popup menu form. When
186 * true, we want the title bar overlay to be gone. When false, we do not.
187 * Only meaningful if mOptionsMenuOpen is true.
188 */
189 private boolean mExtendedMenuOpen;
190
191 private boolean mInLoad;
192
193 private boolean mActivityPaused = true;
194 private boolean mLoadStopped;
195
196 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500197 // Checks to see when the bookmarks database has changed, and updates the
198 // Tabs' notion of whether they represent bookmarked sites.
199 private ContentObserver mBookmarksObserver;
John Reck0ebd3ac2010-12-09 11:14:04 -0800200 private DataController mDataController;
Michael Kolb8233fac2010-10-26 16:08:53 -0700201
202 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
203 @Override
204 public Void doInBackground(File... files) {
205 if (files != null) {
206 for (File f : files) {
207 if (!f.delete()) {
208 Log.e(LOGTAG, f.getPath() + " was not deleted");
209 }
210 }
211 }
212 return null;
213 }
214 }
215
216 public Controller(Activity browser) {
217 mActivity = browser;
218 mSettings = BrowserSettings.getInstance();
John Reck0ebd3ac2010-12-09 11:14:04 -0800219 mDataController = DataController.getInstance(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700220 mTabControl = new TabControl(this);
221 mSettings.setController(this);
222
223 mUrlHandler = new UrlHandler(this);
224 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700225 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
226
227 PowerManager pm = (PowerManager) mActivity
228 .getSystemService(Context.POWER_SERVICE);
229 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
230
231 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500232 mBookmarksObserver = new ContentObserver(mHandler) {
233 @Override
234 public void onChange(boolean selfChange) {
235 int size = mTabControl.getTabCount();
236 for (int i = 0; i < size; i++) {
237 mTabControl.getTab(i).updateBookmarkedStatus();
238 }
239 }
240
241 };
242 browser.getContentResolver().registerContentObserver(
243 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700244
245 mNetworkHandler = new NetworkStateHandler(mActivity, this);
246 // Start watching the default geolocation permissions
247 mSystemAllowGeolocationOrigins =
248 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
249 mSystemAllowGeolocationOrigins.start();
250
251 retainIconsOnStartup();
252 }
253
254 void start(Bundle icicle, Intent intent) {
255 // Unless the last browser usage was within 24 hours, destroy any
256 // remaining incognito tabs.
257
258 Calendar lastActiveDate = icicle != null ?
259 (Calendar) icicle.getSerializable("lastActiveDate") : null;
260 Calendar today = Calendar.getInstance();
261 Calendar yesterday = Calendar.getInstance();
262 yesterday.add(Calendar.DATE, -1);
263
Michael Kolb1bf23132010-11-19 12:55:12 -0800264 boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700265 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800266 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700267
Michael Kolb1bf23132010-11-19 12:55:12 -0800268 if (!mTabControl.restoreState(icicle, restoreIncognitoTabs,
269 mUi.needsRestoreAllTabs())) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700270 // there is no quit on Android. But if we can't restore the state,
271 // we can treat it as a new Browser, remove the old session cookies.
Kristian Monsen3a4e8092010-12-08 11:09:25 +0000272 // This is done async in the CookieManager.
273 CookieManager.getInstance().removeSessionCookie();
Kristian Monsen2cd97012010-12-07 11:11:40 +0000274
Michael Kolb8233fac2010-10-26 16:08:53 -0700275 final Bundle extra = intent.getExtras();
276 // Create an initial tab.
277 // If the intent is ACTION_VIEW and data is not null, the Browser is
278 // invoked to view the content by another application. In this case,
279 // the tab will be close when exit.
280 UrlData urlData = mIntentHandler.getUrlDataFromIntent(intent);
281
282 String action = intent.getAction();
283 final Tab t = mTabControl.createNewTab(
284 (Intent.ACTION_VIEW.equals(action) &&
285 intent.getData() != null)
286 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
287 .equals(action),
288 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
289 urlData.mUrl, false);
290 addTab(t);
291 setActiveTab(t);
292 WebView webView = t.getWebView();
293 if (extra != null) {
294 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
295 if (scale > 0 && scale <= 1000) {
296 webView.setInitialScale(scale);
297 }
298 }
299
300 if (urlData.isEmpty()) {
301 loadUrl(webView, mSettings.getHomePage());
302 } else {
303 loadUrlDataIn(t, urlData);
304 }
305 } else {
Michael Kolb1bf23132010-11-19 12:55:12 -0800306 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700307 // TabControl.restoreState() will create a new tab even if
308 // restoring the state fails.
309 setActiveTab(mTabControl.getCurrentTab());
310 }
311 // clear up the thumbnail directory, which is no longer used;
312 // ideally this should only be run once after an upgrade from
313 // a previous version of the browser
314 new ClearThumbnails().execute(mTabControl.getThumbnailDir()
315 .listFiles());
316 // Read JavaScript flags if it exists.
317 String jsFlags = getSettings().getJsFlags();
318 if (jsFlags.trim().length() != 0) {
319 getCurrentWebView().setJsFlags(jsFlags);
320 }
John Reck439c9a52010-12-14 10:04:39 -0800321 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
322 bookmarksOrHistoryPicker(false);
323 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700324 }
325
326 void setWebViewFactory(WebViewFactory factory) {
327 mFactory = factory;
328 }
329
Michael Kolb1514bb72010-11-22 09:11:48 -0800330 @Override
331 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700332 return mFactory;
333 }
334
335 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800336 public void onSetWebView(Tab tab, WebView view) {
337 mUi.onSetWebView(tab, view);
338 }
339
340 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800341 public void createSubWindow(Tab tab) {
342 endActionMode();
343 WebView mainView = tab.getWebView();
344 WebView subView = mFactory.createWebView((mainView == null)
345 ? false
346 : mainView.isPrivateBrowsingEnabled());
347 mUi.createSubWindow(tab, subView);
348 }
349
350 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700351 public Activity getActivity() {
352 return mActivity;
353 }
354
355 void setUi(UI ui) {
356 mUi = ui;
357 }
358
359 BrowserSettings getSettings() {
360 return mSettings;
361 }
362
363 IntentHandler getIntentHandler() {
364 return mIntentHandler;
365 }
366
367 @Override
368 public UI getUi() {
369 return mUi;
370 }
371
372 int getMaxTabs() {
373 return mActivity.getResources().getInteger(R.integer.max_tabs);
374 }
375
376 @Override
377 public TabControl getTabControl() {
378 return mTabControl;
379 }
380
Michael Kolb1bf23132010-11-19 12:55:12 -0800381 @Override
382 public List<Tab> getTabs() {
383 return mTabControl.getTabs();
384 }
385
Michael Kolb8233fac2010-10-26 16:08:53 -0700386 // Open the icon database and retain all the icons for visited sites.
Ben Murdoch9446b932010-11-25 16:20:14 +0000387 // This is done on a background thread so as not to stall startup.
Michael Kolb8233fac2010-10-26 16:08:53 -0700388 private void retainIconsOnStartup() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000389 // WebIconDatabase needs to be retrieved on the UI thread so that if
390 // it has not been created successfully yet the Handler is started on the
391 // UI thread.
392 new RetainIconsOnStartupTask(WebIconDatabase.getInstance()).execute();
393 }
394
395 private class RetainIconsOnStartupTask extends AsyncTask<Void, Void, Void> {
396 private WebIconDatabase mDb;
397
398 public RetainIconsOnStartupTask(WebIconDatabase db) {
399 mDb = db;
400 }
401
John Recka00cbbd2010-12-16 12:38:19 -0800402 @Override
Ben Murdoch9446b932010-11-25 16:20:14 +0000403 protected Void doInBackground(Void... unused) {
404 mDb.open(mActivity.getDir("icons", 0).getPath());
405 Cursor c = null;
406 try {
407 c = Browser.getAllBookmarks(mActivity.getContentResolver());
408 if (c.moveToFirst()) {
409 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
410 do {
411 String url = c.getString(urlIndex);
412 mDb.retainIconForPageUrl(url);
413 } while (c.moveToNext());
414 }
415 } catch (IllegalStateException e) {
416 Log.e(LOGTAG, "retainIconsOnStartup", e);
417 } finally {
418 if (c != null) c.close();
Michael Kolb8233fac2010-10-26 16:08:53 -0700419 }
Ben Murdoch9446b932010-11-25 16:20:14 +0000420
421 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700422 }
423 }
424
425 private void startHandler() {
426 mHandler = new Handler() {
427
428 @Override
429 public void handleMessage(Message msg) {
430 switch (msg.what) {
431 case OPEN_BOOKMARKS:
432 bookmarksOrHistoryPicker(false);
433 break;
434 case FOCUS_NODE_HREF:
435 {
436 String url = (String) msg.getData().get("url");
437 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500438 String src = (String) msg.getData().get("src");
439 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700440 if (TextUtils.isEmpty(url)) {
441 break;
442 }
443 HashMap focusNodeMap = (HashMap) msg.obj;
444 WebView view = (WebView) focusNodeMap.get("webview");
445 // Only apply the action if the top window did not change.
446 if (getCurrentTopWebView() != view) {
447 break;
448 }
449 switch (msg.arg1) {
450 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -0700451 loadUrlFromContext(getCurrentTopWebView(), url);
452 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500453 case R.id.view_image_context_menu_id:
454 loadUrlFromContext(getCurrentTopWebView(), src);
455 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500456 case R.id.open_newtab_context_menu_id:
457 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -0800458 final Tab newTab = openTab(parent, url, false);
Leon Scroggins026f2542010-11-22 13:26:12 -0500459 if (newTab != null && newTab != parent) {
460 parent.addChildTab(newTab);
461 }
462 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700463 case R.id.copy_link_context_menu_id:
464 copy(url);
465 break;
466 case R.id.save_link_context_menu_id:
467 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500468 DownloadHandler.onDownloadStartNoStream(
469 mActivity, url, null, null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -0700470 break;
471 }
472 break;
473 }
474
475 case LOAD_URL:
476 loadUrlFromContext(getCurrentTopWebView(), (String) msg.obj);
477 break;
478
479 case STOP_LOAD:
480 stopLoading();
481 break;
482
483 case RELEASE_WAKELOCK:
484 if (mWakeLock.isHeld()) {
485 mWakeLock.release();
486 // if we reach here, Browser should be still in the
487 // background loading after WAKELOCK_TIMEOUT (5-min).
488 // To avoid burning the battery, stop loading.
489 mTabControl.stopAllLoading();
490 }
491 break;
492
493 case UPDATE_BOOKMARK_THUMBNAIL:
494 WebView view = (WebView) msg.obj;
495 if (view != null) {
496 updateScreenshot(view);
497 }
498 break;
499 }
500 }
501 };
502
503 }
504
Michael Kolbba99c5d2010-11-29 14:57:41 -0800505 @Override
506 public void shareCurrentPage() {
507 shareCurrentPage(mTabControl.getCurrentTab());
508 }
509
510 private void shareCurrentPage(Tab tab) {
511 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800512 sharePage(mActivity, tab.getTitle(),
513 tab.getUrl(), tab.getFavicon(),
514 createScreenshot(tab.getWebView(),
515 getDesiredThumbnailWidth(mActivity),
516 getDesiredThumbnailHeight(mActivity)));
517 }
518 }
519
Michael Kolb8233fac2010-10-26 16:08:53 -0700520 /**
521 * Share a page, providing the title, url, favicon, and a screenshot. Uses
522 * an {@link Intent} to launch the Activity chooser.
523 * @param c Context used to launch a new Activity.
524 * @param title Title of the page. Stored in the Intent with
525 * {@link Intent#EXTRA_SUBJECT}
526 * @param url URL of the page. Stored in the Intent with
527 * {@link Intent#EXTRA_TEXT}
528 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
529 * with {@link Browser#EXTRA_SHARE_FAVICON}
530 * @param screenshot Bitmap of a screenshot of the page. Stored in the
531 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
532 */
533 static final void sharePage(Context c, String title, String url,
534 Bitmap favicon, Bitmap screenshot) {
535 Intent send = new Intent(Intent.ACTION_SEND);
536 send.setType("text/plain");
537 send.putExtra(Intent.EXTRA_TEXT, url);
538 send.putExtra(Intent.EXTRA_SUBJECT, title);
539 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
540 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
541 try {
542 c.startActivity(Intent.createChooser(send, c.getString(
543 R.string.choosertitle_sharevia)));
544 } catch(android.content.ActivityNotFoundException ex) {
545 // if no app handles it, do nothing
546 }
547 }
548
549 private void copy(CharSequence text) {
550 ClipboardManager cm = (ClipboardManager) mActivity
551 .getSystemService(Context.CLIPBOARD_SERVICE);
552 cm.setText(text);
553 }
554
555 // lifecycle
556
557 protected void onConfgurationChanged(Configuration config) {
558 mConfigChanged = true;
559 if (mPageDialogsHandler != null) {
560 mPageDialogsHandler.onConfigurationChanged(config);
561 }
562 mUi.onConfigurationChanged(config);
563 }
564
565 @Override
566 public void handleNewIntent(Intent intent) {
567 mIntentHandler.onNewIntent(intent);
568 }
569
570 protected void onPause() {
571 if (mActivityPaused) {
572 Log.e(LOGTAG, "BrowserActivity is already paused.");
573 return;
574 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700575 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800576 Tab tab = mTabControl.getCurrentTab();
577 if (tab != null) {
578 tab.pause();
579 if (!pauseWebViewTimers(tab)) {
580 mWakeLock.acquire();
581 mHandler.sendMessageDelayed(mHandler
582 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
583 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700584 }
585 mUi.onPause();
586 mNetworkHandler.onPause();
587
588 WebView.disablePlatformNotifications();
589 }
590
591 void onSaveInstanceState(Bundle outState) {
592 // the default implementation requires each view to have an id. As the
593 // browser handles the state itself and it doesn't use id for the views,
594 // don't call the default implementation. Otherwise it will trigger the
595 // warning like this, "couldn't save which view has focus because the
596 // focused view XXX has no id".
597
598 // Save all the tabs
599 mTabControl.saveState(outState);
600 // Save time so that we know how old incognito tabs (if any) are.
601 outState.putSerializable("lastActiveDate", Calendar.getInstance());
602 }
603
604 void onResume() {
605 if (!mActivityPaused) {
606 Log.e(LOGTAG, "BrowserActivity is already resumed.");
607 return;
608 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700609 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800610 Tab current = mTabControl.getCurrentTab();
611 if (current != null) {
612 current.resume();
613 resumeWebViewTimers(current);
614 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700615 if (mWakeLock.isHeld()) {
616 mHandler.removeMessages(RELEASE_WAKELOCK);
617 mWakeLock.release();
618 }
619 mUi.onResume();
620 mNetworkHandler.onResume();
621 WebView.enablePlatformNotifications();
622 }
623
Michael Kolb70976932010-11-30 11:34:01 -0800624 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800625 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800626 * @param tab guaranteed non-null
627 */
628 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700629 boolean inLoad = tab.inPageLoad();
630 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
631 CookieSyncManager.getInstance().startSync();
632 WebView w = tab.getWebView();
633 if (w != null) {
634 w.resumeTimers();
635 }
636 }
637 }
638
Michael Kolb70976932010-11-30 11:34:01 -0800639 /**
640 * Pause all WebView timers using the WebView of the given tab
641 * @param tab
642 * @return true if the timers are paused or tab is null
643 */
644 private boolean pauseWebViewTimers(Tab tab) {
645 if (tab == null) {
646 return true;
647 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700648 CookieSyncManager.getInstance().stopSync();
649 WebView w = getCurrentWebView();
650 if (w != null) {
651 w.pauseTimers();
652 }
653 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700654 }
Michael Kolb70976932010-11-30 11:34:01 -0800655 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700656 }
657
658 void onDestroy() {
659 if (mUploadHandler != null) {
660 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
661 mUploadHandler = null;
662 }
663 if (mTabControl == null) return;
664 mUi.onDestroy();
665 // Remove the current tab and sub window
666 Tab t = mTabControl.getCurrentTab();
667 if (t != null) {
668 dismissSubWindow(t);
669 removeTab(t);
670 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500671 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700672 // Destroy all the tabs
673 mTabControl.destroy();
674 WebIconDatabase.getInstance().close();
675 // Stop watching the default geolocation permissions
676 mSystemAllowGeolocationOrigins.stop();
677 mSystemAllowGeolocationOrigins = null;
678 }
679
680 protected boolean isActivityPaused() {
681 return mActivityPaused;
682 }
683
684 protected void onLowMemory() {
685 mTabControl.freeMemory();
686 }
687
688 @Override
689 public boolean shouldShowErrorConsole() {
690 return mShouldShowErrorConsole;
691 }
692
693 protected void setShouldShowErrorConsole(boolean show) {
694 if (show == mShouldShowErrorConsole) {
695 // Nothing to do.
696 return;
697 }
698 mShouldShowErrorConsole = show;
699 Tab t = mTabControl.getCurrentTab();
700 if (t == null) {
701 // There is no current tab so we cannot toggle the error console
702 return;
703 }
704 mUi.setShouldShowErrorConsole(t, show);
705 }
706
707 @Override
708 public void stopLoading() {
709 mLoadStopped = true;
710 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700711 WebView w = getCurrentTopWebView();
712 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700713 mUi.onPageStopped(tab);
714 }
715
716 boolean didUserStopLoading() {
717 return mLoadStopped;
718 }
719
720 // WebViewController
721
722 @Override
John Reck324d4402011-01-11 16:56:42 -0800723 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700724
725 // We've started to load a new page. If there was a pending message
726 // to save a screenshot then we will now take the new page and save
727 // an incorrect screenshot. Therefore, remove any pending thumbnail
728 // messages from the queue.
729 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
730 view);
731
732 // reset sync timer to avoid sync starts during loading a page
733 CookieSyncManager.getInstance().resetSync();
734
735 if (!mNetworkHandler.isNetworkUp()) {
736 view.setNetworkAvailable(false);
737 }
738
739 // when BrowserActivity just starts, onPageStarted may be called before
740 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
741 // to start the timer. As we won't switch tabs while an activity is in
742 // pause state, we can ensure calling resume and pause in pair.
743 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800744 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700745 }
746 mLoadStopped = false;
747 if (!mNetworkHandler.isNetworkUp()) {
748 mNetworkHandler.createAndShowNetworkDialog();
749 }
750 endActionMode();
751
John Reck30c714c2010-12-16 17:30:34 -0800752 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700753
John Reck324d4402011-01-11 16:56:42 -0800754 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700755 // update the bookmark database for favicon
756 maybeUpdateFavicon(tab, null, url, favicon);
757
758 Performance.tracePageStart(url);
759
760 // Performance probe
761 if (false) {
762 Performance.onPageStarted();
763 }
764
765 }
766
767 @Override
John Reck324d4402011-01-11 16:56:42 -0800768 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800769 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800770 if (!tab.isPrivateBrowsingEnabled()
771 && !TextUtils.isEmpty(tab.getUrl())) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700772 if (tab.inForeground() && !didUserStopLoading()
773 || !tab.inForeground()) {
774 // Only update the bookmark screenshot if the user did not
775 // cancel the load early.
776 mHandler.sendMessageDelayed(mHandler.obtainMessage(
777 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab.getWebView()),
778 500);
779 }
780 }
781 // pause the WebView timer and release the wake lock if it is finished
782 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800783 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700784 if (mWakeLock.isHeld()) {
785 mHandler.removeMessages(RELEASE_WAKELOCK);
786 mWakeLock.release();
787 }
788 }
789 // Performance probe
790 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800791 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700792 }
793
794 Performance.tracePageFinished();
795 }
796
797 @Override
John Reck30c714c2010-12-16 17:30:34 -0800798 public void onProgressChanged(Tab tab) {
799 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700800
801 if (newProgress == 100) {
802 CookieSyncManager.getInstance().sync();
803 // onProgressChanged() may continue to be called after the main
804 // frame has finished loading, as any remaining sub frames continue
805 // to load. We'll only get called once though with newProgress as
806 // 100 when everything is loaded. (onPageFinished is called once
807 // when the main frame completes loading regardless of the state of
808 // any sub frames so calls to onProgressChanges may continue after
809 // onPageFinished has executed)
810 if (mInLoad) {
811 mInLoad = false;
812 updateInLoadMenuItems(mCachedMenu);
813 }
814 } else {
815 if (!mInLoad) {
816 // onPageFinished may have already been called but a subframe is
817 // still loading and updating the progress. Reset mInLoad and
818 // update the menu items.
819 mInLoad = true;
820 updateInLoadMenuItems(mCachedMenu);
821 }
822 }
John Reck30c714c2010-12-16 17:30:34 -0800823 mUi.onProgressChanged(tab);
824 }
825
826 @Override
827 public void onUpdatedLockIcon(Tab tab) {
828 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700829 }
830
831 @Override
832 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800833 mUi.onTabDataChanged(tab);
834 final String pageUrl = tab.getUrl();
John Reck324d4402011-01-11 16:56:42 -0800835 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700836 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
837 return;
838 }
839 // Update the title in the history database if not in private browsing mode
840 if (!tab.isPrivateBrowsingEnabled()) {
John Reck0ebd3ac2010-12-09 11:14:04 -0800841 mDataController.updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700842 }
843 }
844
845 @Override
846 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800847 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700848 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
849 }
850
851 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800852 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
853 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700854 }
855
856 @Override
857 public boolean shouldOverrideKeyEvent(KeyEvent event) {
858 if (mMenuIsDown) {
859 // only check shortcut key when MENU is held
860 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
861 event);
862 } else {
863 return false;
864 }
865 }
866
867 @Override
868 public void onUnhandledKeyEvent(KeyEvent event) {
869 if (!isActivityPaused()) {
870 if (event.getAction() == KeyEvent.ACTION_DOWN) {
871 mActivity.onKeyDown(event.getKeyCode(), event);
872 } else {
873 mActivity.onKeyUp(event.getKeyCode(), event);
874 }
875 }
876 }
877
878 @Override
John Reck324d4402011-01-11 16:56:42 -0800879 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700880 // Don't save anything in private browsing mode
881 if (tab.isPrivateBrowsingEnabled()) return;
John Reck324d4402011-01-11 16:56:42 -0800882 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700883
John Reck324d4402011-01-11 16:56:42 -0800884 if (TextUtils.isEmpty(url)
885 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700886 return;
887 }
John Reck0ebd3ac2010-12-09 11:14:04 -0800888 mDataController.updateVisitedHistory(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700889 WebIconDatabase.getInstance().retainIconForPageUrl(url);
890 }
891
892 @Override
893 public void getVisitedHistory(final ValueCallback<String[]> callback) {
894 AsyncTask<Void, Void, String[]> task =
895 new AsyncTask<Void, Void, String[]>() {
896 @Override
897 public String[] doInBackground(Void... unused) {
898 return Browser.getVisitedHistory(mActivity.getContentResolver());
899 }
900 @Override
901 public void onPostExecute(String[] result) {
902 callback.onReceiveValue(result);
903 }
904 };
905 task.execute();
906 }
907
908 @Override
909 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
910 final HttpAuthHandler handler, final String host,
911 final String realm) {
912 String username = null;
913 String password = null;
914
915 boolean reuseHttpAuthUsernamePassword
916 = handler.useHttpAuthUsernamePassword();
917
918 if (reuseHttpAuthUsernamePassword && view != null) {
919 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
920 if (credentials != null && credentials.length == 2) {
921 username = credentials[0];
922 password = credentials[1];
923 }
924 }
925
926 if (username != null && password != null) {
927 handler.proceed(username, password);
928 } else {
929 if (tab.inForeground()) {
930 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
931 } else {
932 handler.cancel();
933 }
934 }
935 }
936
937 @Override
938 public void onDownloadStart(Tab tab, String url, String userAgent,
939 String contentDisposition, String mimetype, long contentLength) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500940 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
941 contentDisposition, mimetype);
Michael Kolb8233fac2010-10-26 16:08:53 -0700942 if (tab.getWebView().copyBackForwardList().getSize() == 0) {
943 // This Tab was opened for the sole purpose of downloading a
944 // file. Remove it.
945 if (tab == mTabControl.getCurrentTab()) {
946 // In this case, the Tab is still on top.
947 goBackOnePageOrQuit();
948 } else {
949 // In this case, it is not.
950 closeTab(tab);
951 }
952 }
953 }
954
955 @Override
956 public Bitmap getDefaultVideoPoster() {
957 return mUi.getDefaultVideoPoster();
958 }
959
960 @Override
961 public View getVideoLoadingProgressView() {
962 return mUi.getVideoLoadingProgressView();
963 }
964
965 @Override
966 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
967 SslError error) {
968 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
969 }
970
971 // helper method
972
973 /*
974 * Update the favorites icon if the private browsing isn't enabled and the
975 * icon is valid.
976 */
977 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
978 final String url, Bitmap favicon) {
979 if (favicon == null) {
980 return;
981 }
982 if (!tab.isPrivateBrowsingEnabled()) {
983 Bookmarks.updateFavicon(mActivity
984 .getContentResolver(), originalUrl, url, favicon);
985 }
986 }
987
Leon Scroggins4cd97792010-12-03 15:31:56 -0500988 @Override
989 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -0800990 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -0500991 mUi.bookmarkedStatusHasChanged(tab);
992 }
993
Michael Kolb8233fac2010-10-26 16:08:53 -0700994 // end WebViewController
995
996 protected void pageUp() {
997 getCurrentTopWebView().pageUp(false);
998 }
999
1000 protected void pageDown() {
1001 getCurrentTopWebView().pageDown(false);
1002 }
1003
1004 // callback from phone title bar
1005 public void editUrl() {
1006 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
1007 String url = (getCurrentTopWebView() == null) ? null : getCurrentTopWebView().getUrl();
1008 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1009 null, false);
1010 }
1011
Michael Kolbcfa3af52010-12-14 10:36:11 -08001012 public void startVoiceSearch() {
1013 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1014 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1015 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1016 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1017 mActivity.getComponentName().flattenToString());
1018 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001019 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001020 mActivity.startActivity(intent);
1021 }
1022
Michael Kolb8233fac2010-10-26 16:08:53 -07001023 public void activateVoiceSearchMode(String title) {
1024 mUi.showVoiceTitleBar(title);
1025 }
1026
1027 public void revertVoiceSearchMode(Tab tab) {
1028 mUi.revertVoiceTitleBar(tab);
1029 }
1030
1031 public void showCustomView(Tab tab, View view,
1032 WebChromeClient.CustomViewCallback callback) {
1033 if (tab.inForeground()) {
1034 if (mUi.isCustomViewShowing()) {
1035 callback.onCustomViewHidden();
1036 return;
1037 }
1038 mUi.showCustomView(view, callback);
1039 // Save the menu state and set it to empty while the custom
1040 // view is showing.
1041 mOldMenuState = mMenuState;
1042 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001043 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001044 }
1045 }
1046
1047 @Override
1048 public void hideCustomView() {
1049 if (mUi.isCustomViewShowing()) {
1050 mUi.onHideCustomView();
1051 // Reset the old menu state.
1052 mMenuState = mOldMenuState;
1053 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001054 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001055 }
1056 }
1057
1058 protected void onActivityResult(int requestCode, int resultCode,
1059 Intent intent) {
1060 if (getCurrentTopWebView() == null) return;
1061 switch (requestCode) {
1062 case PREFERENCES_PAGE:
1063 if (resultCode == Activity.RESULT_OK && intent != null) {
1064 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
1065 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
1066 mTabControl.removeParentChildRelationShips();
1067 }
1068 }
1069 break;
1070 case FILE_SELECTED:
1071 // Choose a file from the file picker.
1072 if (null == mUploadHandler) break;
1073 mUploadHandler.onResult(resultCode, intent);
1074 mUploadHandler = null;
1075 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001076 case AUTOFILL_SETUP:
1077 // Determine whether a profile was actually set up or not
1078 // and if so, send the message back to the WebTextView to
1079 // fill the form with the new profile.
1080 if (getSettings().getAutoFillProfile() != null) {
1081 mAutoFillSetupMessage.sendToTarget();
1082 mAutoFillSetupMessage = null;
1083 }
1084 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001085 default:
1086 break;
1087 }
1088 getCurrentTopWebView().requestFocus();
1089 }
1090
1091 /**
1092 * Open the Go page.
1093 * @param startWithHistory If true, open starting on the history tab.
1094 * Otherwise, start with the bookmarks tab.
1095 */
1096 @Override
1097 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1098 if (mTabControl.getCurrentWebView() == null) {
1099 return;
1100 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001101 // clear action mode
1102 if (isInCustomActionMode()) {
1103 endActionMode();
1104 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001105 Bundle extras = new Bundle();
1106 // Disable opening in a new window if we have maxed out the windows
1107 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1108 !mTabControl.canCreateNewTab());
1109 mUi.showComboView(startWithHistory, extras);
1110 }
1111
1112 // combo view callbacks
1113
1114 /**
1115 * callback from ComboPage when clear history is requested
1116 */
1117 public void onRemoveParentChildRelationships() {
1118 mTabControl.removeParentChildRelationShips();
1119 }
1120
1121 /**
1122 * callback from ComboPage when bookmark/history selection
1123 */
1124 @Override
1125 public void onUrlSelected(String url, boolean newTab) {
1126 removeComboView();
1127 if (!TextUtils.isEmpty(url)) {
1128 if (newTab) {
Michael Kolb18eb3772010-12-10 14:29:51 -08001129 openTab(mTabControl.getCurrentTab(), url, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001130 } else {
1131 final Tab currentTab = mTabControl.getCurrentTab();
1132 dismissSubWindow(currentTab);
1133 loadUrl(getCurrentTopWebView(), url);
1134 }
1135 }
1136 }
1137
1138 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07001139 * dismiss the ComboPage
1140 */
1141 @Override
1142 public void removeComboView() {
1143 mUi.hideComboView();
1144 }
1145
1146 // active tabs page handling
1147
1148 protected void showActiveTabsPage() {
1149 mMenuState = EMPTY_MENU;
1150 mUi.showActiveTabsPage();
1151 }
1152
1153 /**
1154 * Remove the active tabs page.
1155 * @param needToAttach If true, the active tabs page did not attach a tab
1156 * to the content view, so we need to do that here.
1157 */
1158 @Override
1159 public void removeActiveTabsPage(boolean needToAttach) {
1160 mMenuState = R.id.MAIN_MENU;
1161 mUi.removeActiveTabsPage();
1162 if (needToAttach) {
1163 setActiveTab(mTabControl.getCurrentTab());
1164 }
1165 getCurrentTopWebView().requestFocus();
1166 }
1167
1168 // key handling
1169 protected void onBackKey() {
1170 if (!mUi.onBackKey()) {
1171 WebView subwindow = mTabControl.getCurrentSubWindow();
1172 if (subwindow != null) {
1173 if (subwindow.canGoBack()) {
1174 subwindow.goBack();
1175 } else {
1176 dismissSubWindow(mTabControl.getCurrentTab());
1177 }
1178 } else {
1179 goBackOnePageOrQuit();
1180 }
1181 }
1182 }
1183
1184 // menu handling and state
1185 // TODO: maybe put into separate handler
1186
1187 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckb3417f02011-01-14 11:01:05 -08001188 if (mOptionsMenuHandler != null) {
1189 return mOptionsMenuHandler.onCreateOptionsMenu(menu);
1190 }
1191
John Reckd73c5a22010-12-22 10:22:50 -08001192 if (mMenuState == EMPTY_MENU) {
1193 return false;
1194 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001195 MenuInflater inflater = mActivity.getMenuInflater();
1196 inflater.inflate(R.menu.browser, menu);
1197 updateInLoadMenuItems(menu);
1198 // hold on to the menu reference here; it is used by the page callbacks
1199 // to update the menu based on loading state
1200 mCachedMenu = menu;
1201 return true;
1202 }
1203
1204 protected void onCreateContextMenu(ContextMenu menu, View v,
1205 ContextMenuInfo menuInfo) {
1206 if (v instanceof TitleBarBase) {
1207 return;
1208 }
1209 if (!(v instanceof WebView)) {
1210 return;
1211 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001212 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001213 WebView.HitTestResult result = webview.getHitTestResult();
1214 if (result == null) {
1215 return;
1216 }
1217
1218 int type = result.getType();
1219 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1220 Log.w(LOGTAG,
1221 "We should not show context menu when nothing is touched");
1222 return;
1223 }
1224 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1225 // let TextView handles context menu
1226 return;
1227 }
1228
1229 // Note, http://b/issue?id=1106666 is requesting that
1230 // an inflated menu can be used again. This is not available
1231 // yet, so inflate each time (yuk!)
1232 MenuInflater inflater = mActivity.getMenuInflater();
1233 inflater.inflate(R.menu.browsercontext, menu);
1234
1235 // Show the correct menu group
1236 final String extra = result.getExtra();
1237 menu.setGroupVisible(R.id.PHONE_MENU,
1238 type == WebView.HitTestResult.PHONE_TYPE);
1239 menu.setGroupVisible(R.id.EMAIL_MENU,
1240 type == WebView.HitTestResult.EMAIL_TYPE);
1241 menu.setGroupVisible(R.id.GEO_MENU,
1242 type == WebView.HitTestResult.GEO_TYPE);
1243 menu.setGroupVisible(R.id.IMAGE_MENU,
1244 type == WebView.HitTestResult.IMAGE_TYPE
1245 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1246 menu.setGroupVisible(R.id.ANCHOR_MENU,
1247 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1248 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001249 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1250 || type == WebView.HitTestResult.PHONE_TYPE
1251 || type == WebView.HitTestResult.EMAIL_TYPE
1252 || type == WebView.HitTestResult.GEO_TYPE;
1253 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1254 if (hitText) {
1255 menu.findItem(R.id.select_text_menu_id)
1256 .setOnMenuItemClickListener(new SelectText(webview));
1257 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001258 // Setup custom handling depending on the type
1259 switch (type) {
1260 case WebView.HitTestResult.PHONE_TYPE:
1261 menu.setHeaderTitle(Uri.decode(extra));
1262 menu.findItem(R.id.dial_context_menu_id).setIntent(
1263 new Intent(Intent.ACTION_VIEW, Uri
1264 .parse(WebView.SCHEME_TEL + extra)));
1265 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1266 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1267 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1268 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1269 addIntent);
1270 menu.findItem(R.id.copy_phone_context_menu_id)
1271 .setOnMenuItemClickListener(
1272 new Copy(extra));
1273 break;
1274
1275 case WebView.HitTestResult.EMAIL_TYPE:
1276 menu.setHeaderTitle(extra);
1277 menu.findItem(R.id.email_context_menu_id).setIntent(
1278 new Intent(Intent.ACTION_VIEW, Uri
1279 .parse(WebView.SCHEME_MAILTO + extra)));
1280 menu.findItem(R.id.copy_mail_context_menu_id)
1281 .setOnMenuItemClickListener(
1282 new Copy(extra));
1283 break;
1284
1285 case WebView.HitTestResult.GEO_TYPE:
1286 menu.setHeaderTitle(extra);
1287 menu.findItem(R.id.map_context_menu_id).setIntent(
1288 new Intent(Intent.ACTION_VIEW, Uri
1289 .parse(WebView.SCHEME_GEO
1290 + URLEncoder.encode(extra))));
1291 menu.findItem(R.id.copy_geo_context_menu_id)
1292 .setOnMenuItemClickListener(
1293 new Copy(extra));
1294 break;
1295
1296 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1297 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001298 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001299 // decide whether to show the open link in new tab option
1300 boolean showNewTab = mTabControl.canCreateNewTab();
1301 MenuItem newTabItem
1302 = menu.findItem(R.id.open_newtab_context_menu_id);
Michael Kolb2dd65c82011-01-14 11:07:38 -08001303 newTabItem.setTitle(
1304 BrowserSettings.getInstance().openInBackground()
1305 ? R.string.contextmenu_openlink_newwindow_background
1306 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001307 newTabItem.setVisible(showNewTab);
1308 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001309 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1310 newTabItem.setOnMenuItemClickListener(
1311 new MenuItem.OnMenuItemClickListener() {
1312 @Override
1313 public boolean onMenuItemClick(MenuItem item) {
1314 final HashMap<String, WebView> hrefMap =
1315 new HashMap<String, WebView>();
1316 hrefMap.put("webview", webview);
1317 final Message msg = mHandler.obtainMessage(
1318 FOCUS_NODE_HREF,
1319 R.id.open_newtab_context_menu_id,
1320 0, hrefMap);
1321 webview.requestFocusNodeHref(msg);
1322 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001323 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001324 });
1325 } else {
1326 newTabItem.setOnMenuItemClickListener(
1327 new MenuItem.OnMenuItemClickListener() {
1328 @Override
1329 public boolean onMenuItemClick(MenuItem item) {
1330 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -08001331 final Tab newTab = openTab(parent,
1332 extra, false);
Leon Scroggins026f2542010-11-22 13:26:12 -05001333 if (newTab != parent) {
1334 parent.addChildTab(newTab);
1335 }
1336 return true;
1337 }
1338 });
1339 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001340 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001341 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1342 break;
1343 }
1344 // otherwise fall through to handle image part
1345 case WebView.HitTestResult.IMAGE_TYPE:
1346 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1347 menu.setHeaderTitle(extra);
1348 }
1349 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1350 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1351 menu.findItem(R.id.download_context_menu_id).
Leon Scroggins63c02662010-11-18 15:16:27 -05001352 setOnMenuItemClickListener(new Download(mActivity, extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001353 menu.findItem(R.id.set_wallpaper_context_menu_id).
1354 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1355 extra));
1356 break;
1357
1358 default:
1359 Log.w(LOGTAG, "We should not get here.");
1360 break;
1361 }
1362 //update the ui
1363 mUi.onContextMenuCreated(menu);
1364 }
1365
1366 /**
1367 * As the menu can be open when loading state changes
1368 * we must manually update the state of the stop/reload menu
1369 * item
1370 */
1371 private void updateInLoadMenuItems(Menu menu) {
1372 if (menu == null) {
1373 return;
1374 }
1375 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1376 MenuItem src = mInLoad ?
1377 menu.findItem(R.id.stop_menu_id):
1378 menu.findItem(R.id.reload_menu_id);
1379 if (src != null) {
1380 dest.setIcon(src.getIcon());
1381 dest.setTitle(src.getTitle());
1382 }
1383 }
1384
John Reckb3417f02011-01-14 11:01:05 -08001385 boolean onPrepareOptionsMenu(Menu menu) {
1386 if (mOptionsMenuHandler != null) {
1387 return mOptionsMenuHandler.onPrepareOptionsMenu(menu);
1388 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001389 // This happens when the user begins to hold down the menu key, so
1390 // allow them to chord to get a shortcut.
1391 mCanChord = true;
1392 // Note: setVisible will decide whether an item is visible; while
1393 // setEnabled() will decide whether an item is enabled, which also means
1394 // whether the matching shortcut key will function.
1395 switch (mMenuState) {
1396 case EMPTY_MENU:
1397 if (mCurrentMenuState != mMenuState) {
1398 menu.setGroupVisible(R.id.MAIN_MENU, false);
1399 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1400 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1401 }
1402 break;
1403 default:
1404 if (mCurrentMenuState != mMenuState) {
1405 menu.setGroupVisible(R.id.MAIN_MENU, true);
1406 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1407 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1408 }
1409 final WebView w = getCurrentTopWebView();
1410 boolean canGoBack = false;
1411 boolean canGoForward = false;
1412 boolean isHome = false;
1413 if (w != null) {
1414 canGoBack = w.canGoBack();
1415 canGoForward = w.canGoForward();
1416 isHome = mSettings.getHomePage().equals(w.getUrl());
1417 }
1418 final MenuItem back = menu.findItem(R.id.back_menu_id);
1419 back.setEnabled(canGoBack);
1420
1421 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1422 home.setEnabled(!isHome);
1423
1424 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1425 forward.setEnabled(canGoForward);
1426
1427 // decide whether to show the share link option
1428 PackageManager pm = mActivity.getPackageManager();
1429 Intent send = new Intent(Intent.ACTION_SEND);
1430 send.setType("text/plain");
1431 ResolveInfo ri = pm.resolveActivity(send,
1432 PackageManager.MATCH_DEFAULT_ONLY);
1433 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1434
1435 boolean isNavDump = mSettings.isNavDump();
1436 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1437 nav.setVisible(isNavDump);
1438 nav.setEnabled(isNavDump);
1439
1440 boolean showDebugSettings = mSettings.showDebugSettings();
1441 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1442 counter.setVisible(showDebugSettings);
1443 counter.setEnabled(showDebugSettings);
1444
John Reckb3417f02011-01-14 11:01:05 -08001445 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1446 newtab.setEnabled(getTabControl().canCreateNewTab());
Michael Kolb8233fac2010-10-26 16:08:53 -07001447
1448 break;
1449 }
1450 mCurrentMenuState = mMenuState;
1451 return true;
1452 }
1453
1454 public boolean onOptionsItemSelected(MenuItem item) {
John Reckb3417f02011-01-14 11:01:05 -08001455 if (mOptionsMenuHandler != null &&
1456 mOptionsMenuHandler.onOptionsItemSelected(item)) {
1457 return true;
1458 }
1459
Michael Kolb8233fac2010-10-26 16:08:53 -07001460 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1461 // menu remains active, so ensure comboview is dismissed
1462 // if main menu option is selected
1463 removeComboView();
1464 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001465 if (!mCanChord) {
1466 // The user has already fired a shortcut with this hold down of the
1467 // menu key.
1468 return false;
1469 }
1470 if (null == getCurrentTopWebView()) {
1471 return false;
1472 }
1473 if (mMenuIsDown) {
1474 // The shortcut action consumes the MENU. Even if it is still down,
1475 // it won't trigger the next shortcut action. In the case of the
1476 // shortcut action triggering a new activity, like Bookmarks, we
1477 // won't get onKeyUp for MENU. So it is important to reset it here.
1478 mMenuIsDown = false;
1479 }
1480 switch (item.getItemId()) {
1481 // -- Main menu
1482 case R.id.new_tab_menu_id:
1483 openTabToHomePage();
1484 break;
1485
1486 case R.id.incognito_menu_id:
1487 openIncognitoTab();
1488 break;
1489
1490 case R.id.goto_menu_id:
1491 editUrl();
1492 break;
1493
1494 case R.id.bookmarks_menu_id:
1495 bookmarksOrHistoryPicker(false);
1496 break;
1497
1498 case R.id.active_tabs_menu_id:
1499 showActiveTabsPage();
1500 break;
1501
1502 case R.id.add_bookmark_menu_id:
1503 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
1504 break;
1505
1506 case R.id.stop_reload_menu_id:
1507 if (mInLoad) {
1508 stopLoading();
1509 } else {
1510 getCurrentTopWebView().reload();
1511 }
1512 break;
1513
1514 case R.id.back_menu_id:
1515 getCurrentTopWebView().goBack();
1516 break;
1517
1518 case R.id.forward_menu_id:
1519 getCurrentTopWebView().goForward();
1520 break;
1521
1522 case R.id.close_menu_id:
1523 // Close the subwindow if it exists.
1524 if (mTabControl.getCurrentSubWindow() != null) {
1525 dismissSubWindow(mTabControl.getCurrentTab());
1526 break;
1527 }
1528 closeCurrentTab();
1529 break;
1530
1531 case R.id.homepage_menu_id:
1532 Tab current = mTabControl.getCurrentTab();
1533 if (current != null) {
1534 dismissSubWindow(current);
1535 loadUrl(current.getWebView(), mSettings.getHomePage());
1536 }
1537 break;
1538
1539 case R.id.preferences_menu_id:
1540 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1541 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1542 getCurrentTopWebView().getUrl());
1543 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1544 break;
1545
1546 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001547 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001548 break;
1549
1550 case R.id.page_info_menu_id:
1551 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1552 false);
1553 break;
1554
1555 case R.id.classic_history_menu_id:
1556 bookmarksOrHistoryPicker(true);
1557 break;
1558
1559 case R.id.title_bar_share_page_url:
1560 case R.id.share_page_menu_id:
1561 Tab currentTab = mTabControl.getCurrentTab();
1562 if (null == currentTab) {
1563 mCanChord = false;
1564 return false;
1565 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001566 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001567 break;
1568
1569 case R.id.dump_nav_menu_id:
1570 getCurrentTopWebView().debugDump();
1571 break;
1572
1573 case R.id.dump_counters_menu_id:
1574 getCurrentTopWebView().dumpV8Counters();
1575 break;
1576
1577 case R.id.zoom_in_menu_id:
1578 getCurrentTopWebView().zoomIn();
1579 break;
1580
1581 case R.id.zoom_out_menu_id:
1582 getCurrentTopWebView().zoomOut();
1583 break;
1584
1585 case R.id.view_downloads_menu_id:
1586 viewDownloads();
1587 break;
1588
1589 case R.id.window_one_menu_id:
1590 case R.id.window_two_menu_id:
1591 case R.id.window_three_menu_id:
1592 case R.id.window_four_menu_id:
1593 case R.id.window_five_menu_id:
1594 case R.id.window_six_menu_id:
1595 case R.id.window_seven_menu_id:
1596 case R.id.window_eight_menu_id:
1597 {
1598 int menuid = item.getItemId();
1599 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1600 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1601 Tab desiredTab = mTabControl.getTab(id);
1602 if (desiredTab != null &&
1603 desiredTab != mTabControl.getCurrentTab()) {
1604 switchToTab(id);
1605 }
1606 break;
1607 }
1608 }
1609 }
1610 break;
1611
1612 default:
1613 return false;
1614 }
1615 mCanChord = false;
1616 return true;
1617 }
1618
1619 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001620 // Let the History and Bookmark fragments handle menus they created.
1621 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1622 return false;
1623 }
1624
Michael Kolb8233fac2010-10-26 16:08:53 -07001625 // chording is not an issue with context menus, but we use the same
1626 // options selector, so set mCanChord to true so we can access them.
1627 mCanChord = true;
1628 int id = item.getItemId();
1629 boolean result = true;
1630 switch (id) {
1631 // For the context menu from the title bar
1632 case R.id.title_bar_copy_page_url:
1633 Tab currentTab = mTabControl.getCurrentTab();
1634 if (null == currentTab) {
1635 result = false;
1636 break;
1637 }
1638 WebView mainView = currentTab.getWebView();
1639 if (null == mainView) {
1640 result = false;
1641 break;
1642 }
1643 copy(mainView.getUrl());
1644 break;
1645 // -- Browser context menu
1646 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001647 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001648 case R.id.copy_link_context_menu_id:
1649 final WebView webView = getCurrentTopWebView();
1650 if (null == webView) {
1651 result = false;
1652 break;
1653 }
1654 final HashMap<String, WebView> hrefMap =
1655 new HashMap<String, WebView>();
1656 hrefMap.put("webview", webView);
1657 final Message msg = mHandler.obtainMessage(
1658 FOCUS_NODE_HREF, id, 0, hrefMap);
1659 webView.requestFocusNodeHref(msg);
1660 break;
1661
1662 default:
1663 // For other context menus
1664 result = onOptionsItemSelected(item);
1665 }
1666 mCanChord = false;
1667 return result;
1668 }
1669
1670 /**
1671 * support programmatically opening the context menu
1672 */
1673 public void openContextMenu(View view) {
1674 mActivity.openContextMenu(view);
1675 }
1676
1677 /**
1678 * programmatically open the options menu
1679 */
1680 public void openOptionsMenu() {
1681 mActivity.openOptionsMenu();
1682 }
1683
1684 public boolean onMenuOpened(int featureId, Menu menu) {
1685 if (mOptionsMenuOpen) {
1686 if (mConfigChanged) {
1687 // We do not need to make any changes to the state of the
1688 // title bar, since the only thing that happened was a
1689 // change in orientation
1690 mConfigChanged = false;
1691 } else {
1692 if (!mExtendedMenuOpen) {
1693 mExtendedMenuOpen = true;
1694 mUi.onExtendedMenuOpened();
1695 } else {
1696 // Switching the menu back to icon view, so show the
1697 // title bar once again.
1698 mExtendedMenuOpen = false;
1699 mUi.onExtendedMenuClosed(mInLoad);
1700 mUi.onOptionsMenuOpened();
1701 }
1702 }
1703 } else {
1704 // The options menu is closed, so open it, and show the title
1705 mOptionsMenuOpen = true;
1706 mConfigChanged = false;
1707 mExtendedMenuOpen = false;
1708 mUi.onOptionsMenuOpened();
1709 }
1710 return true;
1711 }
1712
1713 public void onOptionsMenuClosed(Menu menu) {
1714 mOptionsMenuOpen = false;
1715 mUi.onOptionsMenuClosed(mInLoad);
1716 }
1717
1718 public void onContextMenuClosed(Menu menu) {
1719 mUi.onContextMenuClosed(menu, mInLoad);
1720 }
1721
1722 // Helper method for getting the top window.
1723 @Override
1724 public WebView getCurrentTopWebView() {
1725 return mTabControl.getCurrentTopWebView();
1726 }
1727
1728 @Override
1729 public WebView getCurrentWebView() {
1730 return mTabControl.getCurrentWebView();
1731 }
1732
1733 /*
1734 * This method is called as a result of the user selecting the options
1735 * menu to see the download window. It shows the download window on top of
1736 * the current window.
1737 */
1738 void viewDownloads() {
1739 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1740 mActivity.startActivity(intent);
1741 }
1742
1743 // action mode
1744
1745 void onActionModeStarted(ActionMode mode) {
1746 mUi.onActionModeStarted(mode);
1747 mActionMode = mode;
1748 }
1749
1750 /*
1751 * True if a custom ActionMode (i.e. find or select) is in use.
1752 */
1753 @Override
1754 public boolean isInCustomActionMode() {
1755 return mActionMode != null;
1756 }
1757
1758 /*
1759 * End the current ActionMode.
1760 */
1761 @Override
1762 public void endActionMode() {
1763 if (mActionMode != null) {
1764 mActionMode.finish();
1765 }
1766 }
1767
1768 /*
1769 * Called by find and select when they are finished. Replace title bars
1770 * as necessary.
1771 */
1772 public void onActionModeFinished(ActionMode mode) {
1773 if (!isInCustomActionMode()) return;
1774 mUi.onActionModeFinished(mInLoad);
1775 mActionMode = null;
1776 }
1777
1778 boolean isInLoad() {
1779 return mInLoad;
1780 }
1781
1782 // bookmark handling
1783
1784 /**
1785 * add the current page as a bookmark to the given folder id
1786 * @param folderId use -1 for the default folder
1787 */
1788 @Override
1789 public void bookmarkCurrentPage(long folderId) {
1790 Intent i = new Intent(mActivity,
1791 AddBookmarkPage.class);
1792 WebView w = getCurrentTopWebView();
1793 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1794 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1795 String touchIconUrl = w.getTouchIconUrl();
1796 if (touchIconUrl != null) {
1797 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1798 WebSettings settings = w.getSettings();
1799 if (settings != null) {
1800 i.putExtra(AddBookmarkPage.USER_AGENT,
1801 settings.getUserAgentString());
1802 }
1803 }
1804 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1805 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1806 getDesiredThumbnailHeight(mActivity)));
1807 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1808 i.putExtra(BrowserContract.Bookmarks.PARENT,
1809 folderId);
1810 // Put the dialog at the upper right of the screen, covering the
1811 // star on the title bar.
1812 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1813 mActivity.startActivity(i);
1814 }
1815
1816 // file chooser
1817 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1818 mUploadHandler = new UploadHandler(this);
1819 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1820 }
1821
1822 // thumbnails
1823
1824 /**
1825 * Return the desired width for thumbnail screenshots, which are stored in
1826 * the database, and used on the bookmarks screen.
1827 * @param context Context for finding out the density of the screen.
1828 * @return desired width for thumbnail screenshot.
1829 */
1830 static int getDesiredThumbnailWidth(Context context) {
1831 return context.getResources().getDimensionPixelOffset(
1832 R.dimen.bookmarkThumbnailWidth);
1833 }
1834
1835 /**
1836 * Return the desired height for thumbnail screenshots, which are stored in
1837 * the database, and used on the bookmarks screen.
1838 * @param context Context for finding out the density of the screen.
1839 * @return desired height for thumbnail screenshot.
1840 */
1841 static int getDesiredThumbnailHeight(Context context) {
1842 return context.getResources().getDimensionPixelOffset(
1843 R.dimen.bookmarkThumbnailHeight);
1844 }
1845
1846 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001847 // We render to a bitmap 2x the desired size so that we can then
1848 // re-scale it with filtering since canvas.scale doesn't filter
1849 // This helps reduce aliasing at the cost of being slightly blurry
1850 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001851 Picture thumbnail = view.capturePicture();
1852 if (thumbnail == null) {
1853 return null;
1854 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001855 width *= filter_scale;
1856 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001857 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1858 Canvas canvas = new Canvas(bm);
1859 // May need to tweak these values to determine what is the
1860 // best scale factor
1861 int thumbnailWidth = thumbnail.getWidth();
1862 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001863 float scaleFactor = 1.0f;
Michael Kolb8233fac2010-10-26 16:08:53 -07001864 if (thumbnailWidth > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001865 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001866 } else {
1867 return null;
1868 }
John Reckfe49ab42010-11-16 17:09:37 -08001869
Michael Kolb8233fac2010-10-26 16:08:53 -07001870 if (view.getWidth() > view.getHeight() &&
1871 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
1872 // If the device is in landscape and the page is shorter
John Reckfe49ab42010-11-16 17:09:37 -08001873 // than the height of the view, center the thumnail and crop the sides
1874 scaleFactor = (float) height / (float)thumbnailHeight;
1875 float wx = (thumbnailWidth * scaleFactor) - width;
1876 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001877 }
1878
John Reckfe49ab42010-11-16 17:09:37 -08001879 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001880
1881 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001882 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
1883 height / filter_scale, true);
1884 bm.recycle();
1885 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001886 }
1887
1888 private void updateScreenshot(WebView view) {
1889 // If this is a bookmarked site, add a screenshot to the database.
1890 // FIXME: When should we update? Every time?
1891 // FIXME: Would like to make sure there is actually something to
1892 // draw, but the API for that (WebViewCore.pictureReady()) is not
1893 // currently accessible here.
1894
1895 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1896 getDesiredThumbnailHeight(mActivity));
1897 if (bm == null) {
1898 return;
1899 }
1900
1901 final ContentResolver cr = mActivity.getContentResolver();
1902 final String url = view.getUrl();
1903 final String originalUrl = view.getOriginalUrl();
1904
John Recka00cbbd2010-12-16 12:38:19 -08001905 // Only update thumbnails for web urls (http(s)://), not for
1906 // about:, javascript:, data:, etc...
John Reck9d038482011-01-04 17:02:09 -08001907 if (url != null && Patterns.WEB_URL.matcher(url).matches()) {
John Recka00cbbd2010-12-16 12:38:19 -08001908 new AsyncTask<Void, Void, Void>() {
1909 @Override
1910 protected Void doInBackground(Void... unused) {
1911 Cursor cursor = null;
1912 try {
1913 // TODO: Clean this up
1914 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
1915 if (cursor != null && cursor.moveToFirst()) {
1916 final ByteArrayOutputStream os =
1917 new ByteArrayOutputStream();
1918 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07001919
John Recka00cbbd2010-12-16 12:38:19 -08001920 ContentValues values = new ContentValues();
1921 values.put(Images.THUMBNAIL, os.toByteArray());
1922 values.put(Images.URL, cursor.getString(0));
Michael Kolb8233fac2010-10-26 16:08:53 -07001923
John Recka00cbbd2010-12-16 12:38:19 -08001924 do {
1925 cr.update(Images.CONTENT_URI, values, null, null);
1926 } while (cursor.moveToNext());
1927 }
1928 } catch (IllegalStateException e) {
1929 // Ignore
1930 } finally {
1931 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07001932 }
John Recka00cbbd2010-12-16 12:38:19 -08001933 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07001934 }
John Recka00cbbd2010-12-16 12:38:19 -08001935 }.execute();
1936 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001937 }
1938
1939 private class Copy implements OnMenuItemClickListener {
1940 private CharSequence mText;
1941
1942 public boolean onMenuItemClick(MenuItem item) {
1943 copy(mText);
1944 return true;
1945 }
1946
1947 public Copy(CharSequence toCopy) {
1948 mText = toCopy;
1949 }
1950 }
1951
Leon Scroggins63c02662010-11-18 15:16:27 -05001952 private static class Download implements OnMenuItemClickListener {
1953 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001954 private String mText;
1955
1956 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05001957 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
1958 null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001959 return true;
1960 }
1961
Leon Scroggins63c02662010-11-18 15:16:27 -05001962 public Download(Activity activity, String toDownload) {
1963 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001964 mText = toDownload;
1965 }
1966 }
1967
Cary Clark8974d282010-11-22 10:46:05 -05001968 private static class SelectText implements OnMenuItemClickListener {
1969 private WebView mWebView;
1970
1971 public boolean onMenuItemClick(MenuItem item) {
1972 if (mWebView != null) {
1973 return mWebView.selectText();
1974 }
1975 return false;
1976 }
1977
1978 public SelectText(WebView webView) {
1979 mWebView = webView;
1980 }
1981
1982 }
1983
Michael Kolb8233fac2010-10-26 16:08:53 -07001984 /********************** TODO: UI stuff *****************************/
1985
1986 // these methods have been copied, they still need to be cleaned up
1987
1988 /****************** tabs ***************************************************/
1989
1990 // basic tab interactions:
1991
1992 // it is assumed that tabcontrol already knows about the tab
1993 protected void addTab(Tab tab) {
1994 mUi.addTab(tab);
1995 }
1996
1997 protected void removeTab(Tab tab) {
1998 mUi.removeTab(tab);
1999 mTabControl.removeTab(tab);
2000 }
2001
2002 protected void setActiveTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002003 mTabControl.setCurrentTab(tab);
Michael Kolb77df4562010-11-19 14:49:34 -08002004 // the tab is guaranteed to have a webview after setCurrentTab
2005 mUi.setActiveTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002006 }
2007
2008 protected void closeEmptyChildTab() {
2009 Tab current = mTabControl.getCurrentTab();
2010 if (current != null
2011 && current.getWebView().copyBackForwardList().getSize() == 0) {
2012 Tab parent = current.getParentTab();
2013 if (parent != null) {
2014 switchToTab(mTabControl.getTabIndex(parent));
2015 closeTab(current);
2016 }
2017 }
2018 }
2019
2020 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002021 // Dismiss the subwindow if applicable.
2022 dismissSubWindow(appTab);
2023 // Since we might kill the WebView, remove it from the
2024 // content view first.
2025 mUi.detachTab(appTab);
2026 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002027 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002028 // TODO: analyze why the remove and add are necessary
2029 mUi.attachTab(appTab);
2030 if (mTabControl.getCurrentTab() != appTab) {
2031 switchToTab(mTabControl.getTabIndex(appTab));
John Reck30c714c2010-12-16 17:30:34 -08002032 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002033 } else {
2034 // If the tab was the current tab, we have to attach
2035 // it to the view system again.
2036 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002037 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002038 }
2039 }
2040
2041 // Remove the sub window if it exists. Also called by TabControl when the
2042 // user clicks the 'X' to dismiss a sub window.
2043 public void dismissSubWindow(Tab tab) {
2044 removeSubWindow(tab);
2045 // dismiss the subwindow. This will destroy the WebView.
2046 tab.dismissSubWindow();
2047 getCurrentTopWebView().requestFocus();
2048 }
2049
2050 @Override
2051 public void removeSubWindow(Tab t) {
2052 if (t.getSubWebView() != null) {
2053 mUi.removeSubWindow(t.getSubViewContainer());
2054 }
2055 }
2056
2057 @Override
2058 public void attachSubWindow(Tab tab) {
2059 if (tab.getSubWebView() != null) {
2060 mUi.attachSubWindow(tab.getSubViewContainer());
2061 getCurrentTopWebView().requestFocus();
2062 }
2063 }
2064
Michael Kolb843510f2010-12-09 10:51:49 -08002065 @Override
2066 public Tab openTabToHomePage() {
2067 // check for max tabs
2068 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002069 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2070 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002071 } else {
2072 mUi.showMaxTabsWarning();
2073 return null;
2074 }
2075 }
2076
Michael Kolb18eb3772010-12-10 14:29:51 -08002077 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2078 if (mSettings.openInBackground() && !forceForeground) {
2079 Tab tab = mTabControl.createNewTab(false, null, null,
2080 (parent != null) && parent.isPrivateBrowsingEnabled());
2081 if (tab != null) {
2082 addTab(tab);
2083 WebView view = tab.getWebView();
2084 loadUrl(view, url);
2085 }
2086 return tab;
2087 } else {
2088 return openTabAndShow(parent, new UrlData(url), false, null);
2089 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002090 }
2091
Michael Kolb18eb3772010-12-10 14:29:51 -08002092
Michael Kolb8233fac2010-10-26 16:08:53 -07002093 // This method does a ton of stuff. It will attempt to create a new tab
2094 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2095 // url isn't null, it will load the given url.
Patrick Scottcd135082011-01-31 18:21:58 -05002096 public Tab openTabAndShow(Tab parent, final UrlData urlData,
2097 boolean closeOnExit, String appId) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002098 final Tab currentTab = mTabControl.getCurrentTab();
2099 if (mTabControl.canCreateNewTab()) {
2100 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Michael Kolb18eb3772010-12-10 14:29:51 -08002101 urlData.mUrl,
2102 (parent != null) && parent.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -07002103 WebView webview = tab.getWebView();
2104 // We must set the new tab as the current tab to reflect the old
2105 // animation behavior.
2106 addTab(tab);
2107 setActiveTab(tab);
Patrick Scottcd135082011-01-31 18:21:58 -05002108
2109 // Callback to load the url data.
2110 final Runnable load = new Runnable() {
2111 @Override public void run() {
2112 if (!urlData.isEmpty()) {
2113 loadUrlDataIn(tab, urlData);
2114 }
2115 }
2116 };
2117
2118 GoogleAccountLogin.startLoginIfNeeded(mActivity, mSettings, load);
Michael Kolb8233fac2010-10-26 16:08:53 -07002119 return tab;
2120 } else {
2121 // Get rid of the subwindow if it exists
2122 dismissSubWindow(currentTab);
2123 if (!urlData.isEmpty()) {
2124 // Load the given url.
2125 loadUrlDataIn(currentTab, urlData);
2126 }
2127 return currentTab;
2128 }
2129 }
2130
Michael Kolb8233fac2010-10-26 16:08:53 -07002131 @Override
2132 public Tab openIncognitoTab() {
2133 if (mTabControl.canCreateNewTab()) {
2134 Tab currentTab = mTabControl.getCurrentTab();
Michael Kolb8e7178d2011-01-26 19:13:36 -08002135 Tab tab = mTabControl.createNewTab(false, null,
John Reck4bfc0db2011-01-27 17:47:12 -08002136 null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07002137 addTab(tab);
2138 setActiveTab(tab);
John Reck4bfc0db2011-01-27 17:47:12 -08002139 loadUrlDataIn(tab, new UrlData("browser:incognito"));
Michael Kolb8233fac2010-10-26 16:08:53 -07002140 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002141 } else {
2142 mUi.showMaxTabsWarning();
2143 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002144 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002145 }
2146
2147 /**
2148 * @param index Index of the tab to change to, as defined by
2149 * mTabControl.getTabIndex(Tab t).
2150 * @return boolean True if we successfully switched to a different tab. If
2151 * the indexth tab is null, or if that tab is the same as
2152 * the current one, return false.
2153 */
2154 @Override
2155 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002156 // hide combo view if open
2157 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002158 Tab tab = mTabControl.getTab(index);
2159 Tab currentTab = mTabControl.getCurrentTab();
2160 if (tab == null || tab == currentTab) {
2161 return false;
2162 }
2163 setActiveTab(tab);
2164 return true;
2165 }
2166
2167 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002168 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002169 // hide combo view if open
2170 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002171 final Tab current = mTabControl.getCurrentTab();
2172 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002173 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002174 return;
2175 }
2176 final Tab parent = current.getParentTab();
2177 int indexToShow = -1;
2178 if (parent != null) {
2179 indexToShow = mTabControl.getTabIndex(parent);
2180 } else {
2181 final int currentIndex = mTabControl.getCurrentIndex();
2182 // Try to move to the tab to the right
2183 indexToShow = currentIndex + 1;
2184 if (indexToShow > mTabControl.getTabCount() - 1) {
2185 // Try to move to the tab to the left
2186 indexToShow = currentIndex - 1;
2187 }
2188 }
2189 if (switchToTab(indexToShow)) {
2190 // Close window
2191 closeTab(current);
2192 }
2193 }
2194
2195 /**
2196 * Close the tab, remove its associated title bar, and adjust mTabControl's
2197 * current tab to a valid value.
2198 */
2199 @Override
2200 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002201 // hide combo view if open
2202 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002203 int currentIndex = mTabControl.getCurrentIndex();
2204 int removeIndex = mTabControl.getTabIndex(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002205 Tab newtab = mTabControl.getTab(currentIndex);
2206 setActiveTab(newtab);
Michael Kolb2d59c322011-01-25 13:18:55 -08002207 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002208 }
2209
2210 /**************** TODO: Url loading clean up *******************************/
2211
2212 // Called when loading from context menu or LOAD_URL message
2213 protected void loadUrlFromContext(WebView view, String url) {
2214 // In case the user enters nothing.
2215 if (url != null && url.length() != 0 && view != null) {
2216 url = UrlUtils.smartUrlFilter(url);
2217 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2218 loadUrl(view, url);
2219 }
2220 }
2221 }
2222
2223 /**
2224 * Load the URL into the given WebView and update the title bar
2225 * to reflect the new load. Call this instead of WebView.loadUrl
2226 * directly.
2227 * @param view The WebView used to load url.
2228 * @param url The URL to load.
2229 */
2230 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002231 view.loadUrl(url);
2232 }
2233
2234 /**
2235 * Load UrlData into a Tab and update the title bar to reflect the new
2236 * load. Call this instead of UrlData.loadIn directly.
2237 * @param t The Tab used to load.
2238 * @param data The UrlData being loaded.
2239 */
2240 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002241 data.loadIn(t);
2242 }
2243
John Reck30c714c2010-12-16 17:30:34 -08002244 @Override
2245 public void onUserCanceledSsl(Tab tab) {
2246 WebView web = tab.getWebView();
2247 // TODO: Figure out the "right" behavior
2248 if (web.canGoBack()) {
2249 web.goBack();
2250 } else {
2251 web.loadUrl(mSettings.getHomePage());
2252 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002253 }
2254
2255 void goBackOnePageOrQuit() {
2256 Tab current = mTabControl.getCurrentTab();
2257 if (current == null) {
2258 /*
2259 * Instead of finishing the activity, simply push this to the back
2260 * of the stack and let ActivityManager to choose the foreground
2261 * activity. As BrowserActivity is singleTask, it will be always the
2262 * root of the task. So we can use either true or false for
2263 * moveTaskToBack().
2264 */
2265 mActivity.moveTaskToBack(true);
2266 return;
2267 }
2268 WebView w = current.getWebView();
2269 if (w.canGoBack()) {
2270 w.goBack();
2271 } else {
2272 // Check to see if we are closing a window that was created by
2273 // another window. If so, we switch back to that window.
2274 Tab parent = current.getParentTab();
2275 if (parent != null) {
2276 switchToTab(mTabControl.getTabIndex(parent));
2277 // Now we close the other tab
2278 closeTab(current);
2279 } else {
2280 if (current.closeOnExit()) {
2281 // force the tab's inLoad() to be false as we are going to
2282 // either finish the activity or remove the tab. This will
2283 // ensure pauseWebViewTimers() taking action.
Michael Kolb70976932010-11-30 11:34:01 -08002284 current.clearInPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07002285 if (mTabControl.getTabCount() == 1) {
2286 mActivity.finish();
2287 return;
2288 }
2289 if (mActivityPaused) {
2290 Log.e(LOGTAG, "BrowserActivity is already paused "
2291 + "while handing goBackOnePageOrQuit.");
2292 }
Michael Kolb70976932010-11-30 11:34:01 -08002293 pauseWebViewTimers(current);
Michael Kolb8233fac2010-10-26 16:08:53 -07002294 removeTab(current);
2295 }
2296 /*
2297 * Instead of finishing the activity, simply push this to the back
2298 * of the stack and let ActivityManager to choose the foreground
2299 * activity. As BrowserActivity is singleTask, it will be always the
2300 * root of the task. So we can use either true or false for
2301 * moveTaskToBack().
2302 */
2303 mActivity.moveTaskToBack(true);
2304 }
2305 }
2306 }
2307
2308 /**
2309 * Feed the previously stored results strings to the BrowserProvider so that
2310 * the SearchDialog will show them instead of the standard searches.
2311 * @param result String to show on the editable line of the SearchDialog.
2312 */
2313 @Override
2314 public void showVoiceSearchResults(String result) {
2315 ContentProviderClient client = mActivity.getContentResolver()
2316 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2317 ContentProvider prov = client.getLocalContentProvider();
2318 BrowserProvider bp = (BrowserProvider) prov;
2319 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2320 client.release();
2321
2322 Bundle bundle = createGoogleSearchSourceBundle(
2323 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2324 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2325 startSearch(result, false, bundle, false);
2326 }
2327
2328 private void startSearch(String initialQuery, boolean selectInitialQuery,
2329 Bundle appSearchData, boolean globalSearch) {
2330 if (appSearchData == null) {
2331 appSearchData = createGoogleSearchSourceBundle(
2332 GOOGLE_SEARCH_SOURCE_TYPE);
2333 }
2334
2335 SearchEngine searchEngine = mSettings.getSearchEngine();
2336 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2337 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2338 }
2339 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2340 globalSearch);
2341 }
2342
2343 private Bundle createGoogleSearchSourceBundle(String source) {
2344 Bundle bundle = new Bundle();
2345 bundle.putString(Search.SOURCE, source);
2346 return bundle;
2347 }
2348
2349 /**
2350 * handle key events in browser
2351 *
2352 * @param keyCode
2353 * @param event
2354 * @return true if handled, false to pass to super
2355 */
2356 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002357 boolean noModifiers = event.hasNoModifiers();
2358
Michael Kolb8233fac2010-10-26 16:08:53 -07002359 // Even if MENU is already held down, we need to call to super to open
2360 // the IME on long press.
Cary Clark160bbb92011-01-10 11:17:07 -05002361 if (!noModifiers && KeyEvent.KEYCODE_MENU == keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002362 mMenuIsDown = true;
2363 return false;
2364 }
2365 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2366 // still down, we don't want to trigger the search. Pretend to consume
2367 // the key and do nothing.
2368 if (mMenuIsDown) return true;
2369
Cary Clark8ff8c662010-12-29 15:03:05 -05002370 WebView webView = getCurrentTopWebView();
2371 if (webView == null) return false;
2372
Cary Clark160bbb92011-01-10 11:17:07 -05002373 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2374 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002375
Michael Kolb8233fac2010-10-26 16:08:53 -07002376 switch(keyCode) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002377 case KeyEvent.KEYCODE_ESCAPE:
Cary Clark160bbb92011-01-10 11:17:07 -05002378 if (!noModifiers) break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002379 stopLoading();
2380 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07002381 case KeyEvent.KEYCODE_SPACE:
2382 // WebView/WebTextView handle the keys in the KeyDown. As
2383 // the Activity's shortcut keys are only handled when WebView
2384 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002385 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002386 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002387 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002388 pageDown();
2389 }
2390 return true;
2391 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002392 if (!noModifiers) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002393 if (event.getRepeatCount() == 0) {
2394 event.startTracking();
2395 return true;
2396 } else if (mUi.showsWeb()
2397 && event.isLongPress()) {
2398 bookmarksOrHistoryPicker(true);
2399 return true;
2400 }
2401 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002402 case KeyEvent.KEYCODE_DPAD_LEFT:
2403 if (ctrl) {
2404 webView.goBack();
2405 return true;
2406 }
2407 break;
2408 case KeyEvent.KEYCODE_DPAD_RIGHT:
2409 if (ctrl) {
2410 webView.goForward();
2411 return true;
2412 }
2413 break;
2414 case KeyEvent.KEYCODE_A:
2415 if (ctrl) {
2416 webView.selectAll();
2417 return true;
2418 }
2419 break;
Michael Kolba4183062011-01-16 10:43:21 -08002420// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002421 case KeyEvent.KEYCODE_C:
2422 if (ctrl) {
2423 webView.copySelection();
2424 return true;
2425 }
2426 break;
Michael Kolba4183062011-01-16 10:43:21 -08002427// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002428// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002429// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002430// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002431// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002432// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002433// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002434// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002435// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002436// case KeyEvent.KEYCODE_M: // unused
2437// case KeyEvent.KEYCODE_N: // in Chrome: new window
2438// case KeyEvent.KEYCODE_O: // in Chrome: open file
2439// case KeyEvent.KEYCODE_P: // in Chrome: print page
2440// case KeyEvent.KEYCODE_Q: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002441// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002442// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2443 case KeyEvent.KEYCODE_T:
2444 if (ctrl) {
2445 if (event.isShiftPressed()) {
2446 openIncognitoTab();
2447 } else {
2448 openTabToHomePage();
2449 }
2450 return true;
2451 }
2452 break;
2453// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2454// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolba4183062011-01-16 10:43:21 -08002455// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002456// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2457// case KeyEvent.KEYCODE_Y: // unused
2458// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002459 }
Michael Kolba4183062011-01-16 10:43:21 -08002460 // if we get here, it is a regular key and webview is not null
2461 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002462 }
2463
2464 boolean onKeyUp(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002465 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002466 switch(keyCode) {
2467 case KeyEvent.KEYCODE_MENU:
2468 mMenuIsDown = false;
2469 break;
2470 case KeyEvent.KEYCODE_BACK:
2471 if (event.isTracking() && !event.isCanceled()) {
2472 onBackKey();
2473 return true;
2474 }
2475 break;
2476 }
2477 return false;
2478 }
2479
2480 public boolean isMenuDown() {
2481 return mMenuIsDown;
2482 }
2483
Ben Murdoch8029a772010-11-16 11:58:21 +00002484 public void setupAutoFill(Message message) {
2485 // Open the settings activity at the AutoFill profile fragment so that
2486 // the user can create a new profile. When they return, we will dispatch
2487 // the message so that we can autofill the form using their new profile.
2488 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2489 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2490 AutoFillSettingsFragment.class.getName());
2491 mAutoFillSetupMessage = message;
2492 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2493 }
John Reckb3417f02011-01-14 11:01:05 -08002494
2495 @Override
2496 public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
2497 mOptionsMenuHandler = handler;
2498 }
2499
2500 @Override
2501 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
2502 if (mOptionsMenuHandler == handler) {
2503 mOptionsMenuHandler = null;
2504 }
2505 }
2506
Michael Kolb8233fac2010-10-26 16:08:53 -07002507}