blob: 07e1ef97efcb8ebf47941ed249ec13cedd72cdbf [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() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800571 if (mUi.isCustomViewShowing()) {
572 hideCustomView();
573 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700574 if (mActivityPaused) {
575 Log.e(LOGTAG, "BrowserActivity is already paused.");
576 return;
577 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700578 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800579 Tab tab = mTabControl.getCurrentTab();
580 if (tab != null) {
581 tab.pause();
582 if (!pauseWebViewTimers(tab)) {
583 mWakeLock.acquire();
584 mHandler.sendMessageDelayed(mHandler
585 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
586 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700587 }
588 mUi.onPause();
589 mNetworkHandler.onPause();
590
591 WebView.disablePlatformNotifications();
592 }
593
594 void onSaveInstanceState(Bundle outState) {
595 // the default implementation requires each view to have an id. As the
596 // browser handles the state itself and it doesn't use id for the views,
597 // don't call the default implementation. Otherwise it will trigger the
598 // warning like this, "couldn't save which view has focus because the
599 // focused view XXX has no id".
600
601 // Save all the tabs
602 mTabControl.saveState(outState);
603 // Save time so that we know how old incognito tabs (if any) are.
604 outState.putSerializable("lastActiveDate", Calendar.getInstance());
605 }
606
607 void onResume() {
608 if (!mActivityPaused) {
609 Log.e(LOGTAG, "BrowserActivity is already resumed.");
610 return;
611 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700612 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800613 Tab current = mTabControl.getCurrentTab();
614 if (current != null) {
615 current.resume();
616 resumeWebViewTimers(current);
617 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700618 if (mWakeLock.isHeld()) {
619 mHandler.removeMessages(RELEASE_WAKELOCK);
620 mWakeLock.release();
621 }
622 mUi.onResume();
623 mNetworkHandler.onResume();
624 WebView.enablePlatformNotifications();
625 }
626
Michael Kolb70976932010-11-30 11:34:01 -0800627 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800628 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800629 * @param tab guaranteed non-null
630 */
631 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700632 boolean inLoad = tab.inPageLoad();
633 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
634 CookieSyncManager.getInstance().startSync();
635 WebView w = tab.getWebView();
636 if (w != null) {
637 w.resumeTimers();
638 }
639 }
640 }
641
Michael Kolb70976932010-11-30 11:34:01 -0800642 /**
643 * Pause all WebView timers using the WebView of the given tab
644 * @param tab
645 * @return true if the timers are paused or tab is null
646 */
647 private boolean pauseWebViewTimers(Tab tab) {
648 if (tab == null) {
649 return true;
650 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700651 CookieSyncManager.getInstance().stopSync();
652 WebView w = getCurrentWebView();
653 if (w != null) {
654 w.pauseTimers();
655 }
656 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700657 }
Michael Kolb70976932010-11-30 11:34:01 -0800658 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700659 }
660
661 void onDestroy() {
662 if (mUploadHandler != null) {
663 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
664 mUploadHandler = null;
665 }
666 if (mTabControl == null) return;
667 mUi.onDestroy();
668 // Remove the current tab and sub window
669 Tab t = mTabControl.getCurrentTab();
670 if (t != null) {
671 dismissSubWindow(t);
672 removeTab(t);
673 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500674 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700675 // Destroy all the tabs
676 mTabControl.destroy();
677 WebIconDatabase.getInstance().close();
678 // Stop watching the default geolocation permissions
679 mSystemAllowGeolocationOrigins.stop();
680 mSystemAllowGeolocationOrigins = null;
681 }
682
683 protected boolean isActivityPaused() {
684 return mActivityPaused;
685 }
686
687 protected void onLowMemory() {
688 mTabControl.freeMemory();
689 }
690
691 @Override
692 public boolean shouldShowErrorConsole() {
693 return mShouldShowErrorConsole;
694 }
695
696 protected void setShouldShowErrorConsole(boolean show) {
697 if (show == mShouldShowErrorConsole) {
698 // Nothing to do.
699 return;
700 }
701 mShouldShowErrorConsole = show;
702 Tab t = mTabControl.getCurrentTab();
703 if (t == null) {
704 // There is no current tab so we cannot toggle the error console
705 return;
706 }
707 mUi.setShouldShowErrorConsole(t, show);
708 }
709
710 @Override
711 public void stopLoading() {
712 mLoadStopped = true;
713 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700714 WebView w = getCurrentTopWebView();
715 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700716 mUi.onPageStopped(tab);
717 }
718
719 boolean didUserStopLoading() {
720 return mLoadStopped;
721 }
722
723 // WebViewController
724
725 @Override
John Reck324d4402011-01-11 16:56:42 -0800726 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700727
728 // We've started to load a new page. If there was a pending message
729 // to save a screenshot then we will now take the new page and save
730 // an incorrect screenshot. Therefore, remove any pending thumbnail
731 // messages from the queue.
732 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
733 view);
734
735 // reset sync timer to avoid sync starts during loading a page
736 CookieSyncManager.getInstance().resetSync();
737
738 if (!mNetworkHandler.isNetworkUp()) {
739 view.setNetworkAvailable(false);
740 }
741
742 // when BrowserActivity just starts, onPageStarted may be called before
743 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
744 // to start the timer. As we won't switch tabs while an activity is in
745 // pause state, we can ensure calling resume and pause in pair.
746 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800747 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700748 }
749 mLoadStopped = false;
750 if (!mNetworkHandler.isNetworkUp()) {
751 mNetworkHandler.createAndShowNetworkDialog();
752 }
753 endActionMode();
754
John Reck30c714c2010-12-16 17:30:34 -0800755 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700756
John Reck324d4402011-01-11 16:56:42 -0800757 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700758 // update the bookmark database for favicon
759 maybeUpdateFavicon(tab, null, url, favicon);
760
761 Performance.tracePageStart(url);
762
763 // Performance probe
764 if (false) {
765 Performance.onPageStarted();
766 }
767
768 }
769
770 @Override
John Reck324d4402011-01-11 16:56:42 -0800771 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800772 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800773 if (!tab.isPrivateBrowsingEnabled()
774 && !TextUtils.isEmpty(tab.getUrl())) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700775 if (tab.inForeground() && !didUserStopLoading()
776 || !tab.inForeground()) {
777 // Only update the bookmark screenshot if the user did not
778 // cancel the load early.
779 mHandler.sendMessageDelayed(mHandler.obtainMessage(
780 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab.getWebView()),
781 500);
782 }
783 }
784 // pause the WebView timer and release the wake lock if it is finished
785 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800786 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700787 if (mWakeLock.isHeld()) {
788 mHandler.removeMessages(RELEASE_WAKELOCK);
789 mWakeLock.release();
790 }
791 }
792 // Performance probe
793 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800794 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700795 }
796
797 Performance.tracePageFinished();
798 }
799
800 @Override
John Reck30c714c2010-12-16 17:30:34 -0800801 public void onProgressChanged(Tab tab) {
802 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700803
804 if (newProgress == 100) {
805 CookieSyncManager.getInstance().sync();
806 // onProgressChanged() may continue to be called after the main
807 // frame has finished loading, as any remaining sub frames continue
808 // to load. We'll only get called once though with newProgress as
809 // 100 when everything is loaded. (onPageFinished is called once
810 // when the main frame completes loading regardless of the state of
811 // any sub frames so calls to onProgressChanges may continue after
812 // onPageFinished has executed)
813 if (mInLoad) {
814 mInLoad = false;
815 updateInLoadMenuItems(mCachedMenu);
816 }
817 } else {
818 if (!mInLoad) {
819 // onPageFinished may have already been called but a subframe is
820 // still loading and updating the progress. Reset mInLoad and
821 // update the menu items.
822 mInLoad = true;
823 updateInLoadMenuItems(mCachedMenu);
824 }
825 }
John Reck30c714c2010-12-16 17:30:34 -0800826 mUi.onProgressChanged(tab);
827 }
828
829 @Override
830 public void onUpdatedLockIcon(Tab tab) {
831 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700832 }
833
834 @Override
835 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800836 mUi.onTabDataChanged(tab);
837 final String pageUrl = tab.getUrl();
John Reck324d4402011-01-11 16:56:42 -0800838 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700839 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
840 return;
841 }
842 // Update the title in the history database if not in private browsing mode
843 if (!tab.isPrivateBrowsingEnabled()) {
John Reck0ebd3ac2010-12-09 11:14:04 -0800844 mDataController.updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700845 }
846 }
847
848 @Override
849 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800850 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700851 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
852 }
853
854 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800855 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
856 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700857 }
858
859 @Override
860 public boolean shouldOverrideKeyEvent(KeyEvent event) {
861 if (mMenuIsDown) {
862 // only check shortcut key when MENU is held
863 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
864 event);
865 } else {
866 return false;
867 }
868 }
869
870 @Override
871 public void onUnhandledKeyEvent(KeyEvent event) {
872 if (!isActivityPaused()) {
873 if (event.getAction() == KeyEvent.ACTION_DOWN) {
874 mActivity.onKeyDown(event.getKeyCode(), event);
875 } else {
876 mActivity.onKeyUp(event.getKeyCode(), event);
877 }
878 }
879 }
880
881 @Override
John Reck324d4402011-01-11 16:56:42 -0800882 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700883 // Don't save anything in private browsing mode
884 if (tab.isPrivateBrowsingEnabled()) return;
John Reck324d4402011-01-11 16:56:42 -0800885 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700886
John Reck324d4402011-01-11 16:56:42 -0800887 if (TextUtils.isEmpty(url)
888 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700889 return;
890 }
John Reck0ebd3ac2010-12-09 11:14:04 -0800891 mDataController.updateVisitedHistory(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700892 WebIconDatabase.getInstance().retainIconForPageUrl(url);
893 }
894
895 @Override
896 public void getVisitedHistory(final ValueCallback<String[]> callback) {
897 AsyncTask<Void, Void, String[]> task =
898 new AsyncTask<Void, Void, String[]>() {
899 @Override
900 public String[] doInBackground(Void... unused) {
901 return Browser.getVisitedHistory(mActivity.getContentResolver());
902 }
903 @Override
904 public void onPostExecute(String[] result) {
905 callback.onReceiveValue(result);
906 }
907 };
908 task.execute();
909 }
910
911 @Override
912 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
913 final HttpAuthHandler handler, final String host,
914 final String realm) {
915 String username = null;
916 String password = null;
917
918 boolean reuseHttpAuthUsernamePassword
919 = handler.useHttpAuthUsernamePassword();
920
921 if (reuseHttpAuthUsernamePassword && view != null) {
922 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
923 if (credentials != null && credentials.length == 2) {
924 username = credentials[0];
925 password = credentials[1];
926 }
927 }
928
929 if (username != null && password != null) {
930 handler.proceed(username, password);
931 } else {
932 if (tab.inForeground()) {
933 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
934 } else {
935 handler.cancel();
936 }
937 }
938 }
939
940 @Override
941 public void onDownloadStart(Tab tab, String url, String userAgent,
942 String contentDisposition, String mimetype, long contentLength) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500943 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
944 contentDisposition, mimetype);
Michael Kolb8233fac2010-10-26 16:08:53 -0700945 if (tab.getWebView().copyBackForwardList().getSize() == 0) {
946 // This Tab was opened for the sole purpose of downloading a
947 // file. Remove it.
948 if (tab == mTabControl.getCurrentTab()) {
949 // In this case, the Tab is still on top.
950 goBackOnePageOrQuit();
951 } else {
952 // In this case, it is not.
953 closeTab(tab);
954 }
955 }
956 }
957
958 @Override
959 public Bitmap getDefaultVideoPoster() {
960 return mUi.getDefaultVideoPoster();
961 }
962
963 @Override
964 public View getVideoLoadingProgressView() {
965 return mUi.getVideoLoadingProgressView();
966 }
967
968 @Override
969 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
970 SslError error) {
971 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
972 }
973
974 // helper method
975
976 /*
977 * Update the favorites icon if the private browsing isn't enabled and the
978 * icon is valid.
979 */
980 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
981 final String url, Bitmap favicon) {
982 if (favicon == null) {
983 return;
984 }
985 if (!tab.isPrivateBrowsingEnabled()) {
986 Bookmarks.updateFavicon(mActivity
987 .getContentResolver(), originalUrl, url, favicon);
988 }
989 }
990
Leon Scroggins4cd97792010-12-03 15:31:56 -0500991 @Override
992 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -0800993 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -0500994 mUi.bookmarkedStatusHasChanged(tab);
995 }
996
Michael Kolb8233fac2010-10-26 16:08:53 -0700997 // end WebViewController
998
999 protected void pageUp() {
1000 getCurrentTopWebView().pageUp(false);
1001 }
1002
1003 protected void pageDown() {
1004 getCurrentTopWebView().pageDown(false);
1005 }
1006
1007 // callback from phone title bar
1008 public void editUrl() {
1009 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
1010 String url = (getCurrentTopWebView() == null) ? null : getCurrentTopWebView().getUrl();
1011 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1012 null, false);
1013 }
1014
Michael Kolbcfa3af52010-12-14 10:36:11 -08001015 public void startVoiceSearch() {
1016 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1017 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1018 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1019 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1020 mActivity.getComponentName().flattenToString());
1021 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001022 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001023 mActivity.startActivity(intent);
1024 }
1025
Michael Kolb8233fac2010-10-26 16:08:53 -07001026 public void activateVoiceSearchMode(String title) {
1027 mUi.showVoiceTitleBar(title);
1028 }
1029
1030 public void revertVoiceSearchMode(Tab tab) {
1031 mUi.revertVoiceTitleBar(tab);
1032 }
1033
1034 public void showCustomView(Tab tab, View view,
1035 WebChromeClient.CustomViewCallback callback) {
1036 if (tab.inForeground()) {
1037 if (mUi.isCustomViewShowing()) {
1038 callback.onCustomViewHidden();
1039 return;
1040 }
1041 mUi.showCustomView(view, callback);
1042 // Save the menu state and set it to empty while the custom
1043 // view is showing.
1044 mOldMenuState = mMenuState;
1045 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001046 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001047 }
1048 }
1049
1050 @Override
1051 public void hideCustomView() {
1052 if (mUi.isCustomViewShowing()) {
1053 mUi.onHideCustomView();
1054 // Reset the old menu state.
1055 mMenuState = mOldMenuState;
1056 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001057 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001058 }
1059 }
1060
1061 protected void onActivityResult(int requestCode, int resultCode,
1062 Intent intent) {
1063 if (getCurrentTopWebView() == null) return;
1064 switch (requestCode) {
1065 case PREFERENCES_PAGE:
1066 if (resultCode == Activity.RESULT_OK && intent != null) {
1067 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
1068 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
1069 mTabControl.removeParentChildRelationShips();
1070 }
1071 }
1072 break;
1073 case FILE_SELECTED:
1074 // Choose a file from the file picker.
1075 if (null == mUploadHandler) break;
1076 mUploadHandler.onResult(resultCode, intent);
1077 mUploadHandler = null;
1078 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001079 case AUTOFILL_SETUP:
1080 // Determine whether a profile was actually set up or not
1081 // and if so, send the message back to the WebTextView to
1082 // fill the form with the new profile.
1083 if (getSettings().getAutoFillProfile() != null) {
1084 mAutoFillSetupMessage.sendToTarget();
1085 mAutoFillSetupMessage = null;
1086 }
1087 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001088 default:
1089 break;
1090 }
1091 getCurrentTopWebView().requestFocus();
1092 }
1093
1094 /**
1095 * Open the Go page.
1096 * @param startWithHistory If true, open starting on the history tab.
1097 * Otherwise, start with the bookmarks tab.
1098 */
1099 @Override
1100 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1101 if (mTabControl.getCurrentWebView() == null) {
1102 return;
1103 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001104 // clear action mode
1105 if (isInCustomActionMode()) {
1106 endActionMode();
1107 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001108 Bundle extras = new Bundle();
1109 // Disable opening in a new window if we have maxed out the windows
1110 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1111 !mTabControl.canCreateNewTab());
1112 mUi.showComboView(startWithHistory, extras);
1113 }
1114
1115 // combo view callbacks
1116
1117 /**
1118 * callback from ComboPage when clear history is requested
1119 */
1120 public void onRemoveParentChildRelationships() {
1121 mTabControl.removeParentChildRelationShips();
1122 }
1123
1124 /**
1125 * callback from ComboPage when bookmark/history selection
1126 */
1127 @Override
1128 public void onUrlSelected(String url, boolean newTab) {
1129 removeComboView();
1130 if (!TextUtils.isEmpty(url)) {
1131 if (newTab) {
Michael Kolb18eb3772010-12-10 14:29:51 -08001132 openTab(mTabControl.getCurrentTab(), url, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001133 } else {
1134 final Tab currentTab = mTabControl.getCurrentTab();
1135 dismissSubWindow(currentTab);
1136 loadUrl(getCurrentTopWebView(), url);
1137 }
1138 }
1139 }
1140
1141 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07001142 * dismiss the ComboPage
1143 */
1144 @Override
1145 public void removeComboView() {
1146 mUi.hideComboView();
1147 }
1148
1149 // active tabs page handling
1150
1151 protected void showActiveTabsPage() {
1152 mMenuState = EMPTY_MENU;
1153 mUi.showActiveTabsPage();
1154 }
1155
1156 /**
1157 * Remove the active tabs page.
1158 * @param needToAttach If true, the active tabs page did not attach a tab
1159 * to the content view, so we need to do that here.
1160 */
1161 @Override
1162 public void removeActiveTabsPage(boolean needToAttach) {
1163 mMenuState = R.id.MAIN_MENU;
1164 mUi.removeActiveTabsPage();
1165 if (needToAttach) {
1166 setActiveTab(mTabControl.getCurrentTab());
1167 }
1168 getCurrentTopWebView().requestFocus();
1169 }
1170
1171 // key handling
1172 protected void onBackKey() {
1173 if (!mUi.onBackKey()) {
1174 WebView subwindow = mTabControl.getCurrentSubWindow();
1175 if (subwindow != null) {
1176 if (subwindow.canGoBack()) {
1177 subwindow.goBack();
1178 } else {
1179 dismissSubWindow(mTabControl.getCurrentTab());
1180 }
1181 } else {
1182 goBackOnePageOrQuit();
1183 }
1184 }
1185 }
1186
1187 // menu handling and state
1188 // TODO: maybe put into separate handler
1189
1190 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckb3417f02011-01-14 11:01:05 -08001191 if (mOptionsMenuHandler != null) {
1192 return mOptionsMenuHandler.onCreateOptionsMenu(menu);
1193 }
1194
John Reckd73c5a22010-12-22 10:22:50 -08001195 if (mMenuState == EMPTY_MENU) {
1196 return false;
1197 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001198 MenuInflater inflater = mActivity.getMenuInflater();
1199 inflater.inflate(R.menu.browser, menu);
1200 updateInLoadMenuItems(menu);
1201 // hold on to the menu reference here; it is used by the page callbacks
1202 // to update the menu based on loading state
1203 mCachedMenu = menu;
1204 return true;
1205 }
1206
1207 protected void onCreateContextMenu(ContextMenu menu, View v,
1208 ContextMenuInfo menuInfo) {
1209 if (v instanceof TitleBarBase) {
1210 return;
1211 }
1212 if (!(v instanceof WebView)) {
1213 return;
1214 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001215 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001216 WebView.HitTestResult result = webview.getHitTestResult();
1217 if (result == null) {
1218 return;
1219 }
1220
1221 int type = result.getType();
1222 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1223 Log.w(LOGTAG,
1224 "We should not show context menu when nothing is touched");
1225 return;
1226 }
1227 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1228 // let TextView handles context menu
1229 return;
1230 }
1231
1232 // Note, http://b/issue?id=1106666 is requesting that
1233 // an inflated menu can be used again. This is not available
1234 // yet, so inflate each time (yuk!)
1235 MenuInflater inflater = mActivity.getMenuInflater();
1236 inflater.inflate(R.menu.browsercontext, menu);
1237
1238 // Show the correct menu group
1239 final String extra = result.getExtra();
1240 menu.setGroupVisible(R.id.PHONE_MENU,
1241 type == WebView.HitTestResult.PHONE_TYPE);
1242 menu.setGroupVisible(R.id.EMAIL_MENU,
1243 type == WebView.HitTestResult.EMAIL_TYPE);
1244 menu.setGroupVisible(R.id.GEO_MENU,
1245 type == WebView.HitTestResult.GEO_TYPE);
1246 menu.setGroupVisible(R.id.IMAGE_MENU,
1247 type == WebView.HitTestResult.IMAGE_TYPE
1248 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1249 menu.setGroupVisible(R.id.ANCHOR_MENU,
1250 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1251 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001252 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1253 || type == WebView.HitTestResult.PHONE_TYPE
1254 || type == WebView.HitTestResult.EMAIL_TYPE
1255 || type == WebView.HitTestResult.GEO_TYPE;
1256 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1257 if (hitText) {
1258 menu.findItem(R.id.select_text_menu_id)
1259 .setOnMenuItemClickListener(new SelectText(webview));
1260 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001261 // Setup custom handling depending on the type
1262 switch (type) {
1263 case WebView.HitTestResult.PHONE_TYPE:
1264 menu.setHeaderTitle(Uri.decode(extra));
1265 menu.findItem(R.id.dial_context_menu_id).setIntent(
1266 new Intent(Intent.ACTION_VIEW, Uri
1267 .parse(WebView.SCHEME_TEL + extra)));
1268 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1269 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1270 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1271 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1272 addIntent);
1273 menu.findItem(R.id.copy_phone_context_menu_id)
1274 .setOnMenuItemClickListener(
1275 new Copy(extra));
1276 break;
1277
1278 case WebView.HitTestResult.EMAIL_TYPE:
1279 menu.setHeaderTitle(extra);
1280 menu.findItem(R.id.email_context_menu_id).setIntent(
1281 new Intent(Intent.ACTION_VIEW, Uri
1282 .parse(WebView.SCHEME_MAILTO + extra)));
1283 menu.findItem(R.id.copy_mail_context_menu_id)
1284 .setOnMenuItemClickListener(
1285 new Copy(extra));
1286 break;
1287
1288 case WebView.HitTestResult.GEO_TYPE:
1289 menu.setHeaderTitle(extra);
1290 menu.findItem(R.id.map_context_menu_id).setIntent(
1291 new Intent(Intent.ACTION_VIEW, Uri
1292 .parse(WebView.SCHEME_GEO
1293 + URLEncoder.encode(extra))));
1294 menu.findItem(R.id.copy_geo_context_menu_id)
1295 .setOnMenuItemClickListener(
1296 new Copy(extra));
1297 break;
1298
1299 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1300 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001301 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001302 // decide whether to show the open link in new tab option
1303 boolean showNewTab = mTabControl.canCreateNewTab();
1304 MenuItem newTabItem
1305 = menu.findItem(R.id.open_newtab_context_menu_id);
Michael Kolb2dd65c82011-01-14 11:07:38 -08001306 newTabItem.setTitle(
1307 BrowserSettings.getInstance().openInBackground()
1308 ? R.string.contextmenu_openlink_newwindow_background
1309 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001310 newTabItem.setVisible(showNewTab);
1311 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001312 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1313 newTabItem.setOnMenuItemClickListener(
1314 new MenuItem.OnMenuItemClickListener() {
1315 @Override
1316 public boolean onMenuItemClick(MenuItem item) {
1317 final HashMap<String, WebView> hrefMap =
1318 new HashMap<String, WebView>();
1319 hrefMap.put("webview", webview);
1320 final Message msg = mHandler.obtainMessage(
1321 FOCUS_NODE_HREF,
1322 R.id.open_newtab_context_menu_id,
1323 0, hrefMap);
1324 webview.requestFocusNodeHref(msg);
1325 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001326 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001327 });
1328 } else {
1329 newTabItem.setOnMenuItemClickListener(
1330 new MenuItem.OnMenuItemClickListener() {
1331 @Override
1332 public boolean onMenuItemClick(MenuItem item) {
1333 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -08001334 final Tab newTab = openTab(parent,
1335 extra, false);
Leon Scroggins026f2542010-11-22 13:26:12 -05001336 if (newTab != parent) {
1337 parent.addChildTab(newTab);
1338 }
1339 return true;
1340 }
1341 });
1342 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001343 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001344 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1345 break;
1346 }
1347 // otherwise fall through to handle image part
1348 case WebView.HitTestResult.IMAGE_TYPE:
1349 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1350 menu.setHeaderTitle(extra);
1351 }
1352 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1353 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1354 menu.findItem(R.id.download_context_menu_id).
Leon Scroggins63c02662010-11-18 15:16:27 -05001355 setOnMenuItemClickListener(new Download(mActivity, extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001356 menu.findItem(R.id.set_wallpaper_context_menu_id).
1357 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1358 extra));
1359 break;
1360
1361 default:
1362 Log.w(LOGTAG, "We should not get here.");
1363 break;
1364 }
1365 //update the ui
1366 mUi.onContextMenuCreated(menu);
1367 }
1368
1369 /**
1370 * As the menu can be open when loading state changes
1371 * we must manually update the state of the stop/reload menu
1372 * item
1373 */
1374 private void updateInLoadMenuItems(Menu menu) {
1375 if (menu == null) {
1376 return;
1377 }
1378 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1379 MenuItem src = mInLoad ?
1380 menu.findItem(R.id.stop_menu_id):
1381 menu.findItem(R.id.reload_menu_id);
1382 if (src != null) {
1383 dest.setIcon(src.getIcon());
1384 dest.setTitle(src.getTitle());
1385 }
1386 }
1387
John Reckb3417f02011-01-14 11:01:05 -08001388 boolean onPrepareOptionsMenu(Menu menu) {
1389 if (mOptionsMenuHandler != null) {
1390 return mOptionsMenuHandler.onPrepareOptionsMenu(menu);
1391 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001392 // This happens when the user begins to hold down the menu key, so
1393 // allow them to chord to get a shortcut.
1394 mCanChord = true;
1395 // Note: setVisible will decide whether an item is visible; while
1396 // setEnabled() will decide whether an item is enabled, which also means
1397 // whether the matching shortcut key will function.
1398 switch (mMenuState) {
1399 case EMPTY_MENU:
1400 if (mCurrentMenuState != mMenuState) {
1401 menu.setGroupVisible(R.id.MAIN_MENU, false);
1402 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1403 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1404 }
1405 break;
1406 default:
1407 if (mCurrentMenuState != mMenuState) {
1408 menu.setGroupVisible(R.id.MAIN_MENU, true);
1409 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1410 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1411 }
1412 final WebView w = getCurrentTopWebView();
1413 boolean canGoBack = false;
1414 boolean canGoForward = false;
1415 boolean isHome = false;
1416 if (w != null) {
1417 canGoBack = w.canGoBack();
1418 canGoForward = w.canGoForward();
1419 isHome = mSettings.getHomePage().equals(w.getUrl());
1420 }
1421 final MenuItem back = menu.findItem(R.id.back_menu_id);
1422 back.setEnabled(canGoBack);
1423
1424 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1425 home.setEnabled(!isHome);
1426
1427 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1428 forward.setEnabled(canGoForward);
1429
1430 // decide whether to show the share link option
1431 PackageManager pm = mActivity.getPackageManager();
1432 Intent send = new Intent(Intent.ACTION_SEND);
1433 send.setType("text/plain");
1434 ResolveInfo ri = pm.resolveActivity(send,
1435 PackageManager.MATCH_DEFAULT_ONLY);
1436 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1437
1438 boolean isNavDump = mSettings.isNavDump();
1439 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1440 nav.setVisible(isNavDump);
1441 nav.setEnabled(isNavDump);
1442
1443 boolean showDebugSettings = mSettings.showDebugSettings();
1444 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1445 counter.setVisible(showDebugSettings);
1446 counter.setEnabled(showDebugSettings);
1447
John Reckb3417f02011-01-14 11:01:05 -08001448 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1449 newtab.setEnabled(getTabControl().canCreateNewTab());
Michael Kolb8233fac2010-10-26 16:08:53 -07001450
1451 break;
1452 }
1453 mCurrentMenuState = mMenuState;
1454 return true;
1455 }
1456
1457 public boolean onOptionsItemSelected(MenuItem item) {
John Reckb3417f02011-01-14 11:01:05 -08001458 if (mOptionsMenuHandler != null &&
1459 mOptionsMenuHandler.onOptionsItemSelected(item)) {
1460 return true;
1461 }
1462
Michael Kolb8233fac2010-10-26 16:08:53 -07001463 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1464 // menu remains active, so ensure comboview is dismissed
1465 // if main menu option is selected
1466 removeComboView();
1467 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001468 if (!mCanChord) {
1469 // The user has already fired a shortcut with this hold down of the
1470 // menu key.
1471 return false;
1472 }
1473 if (null == getCurrentTopWebView()) {
1474 return false;
1475 }
1476 if (mMenuIsDown) {
1477 // The shortcut action consumes the MENU. Even if it is still down,
1478 // it won't trigger the next shortcut action. In the case of the
1479 // shortcut action triggering a new activity, like Bookmarks, we
1480 // won't get onKeyUp for MENU. So it is important to reset it here.
1481 mMenuIsDown = false;
1482 }
1483 switch (item.getItemId()) {
1484 // -- Main menu
1485 case R.id.new_tab_menu_id:
1486 openTabToHomePage();
1487 break;
1488
1489 case R.id.incognito_menu_id:
1490 openIncognitoTab();
1491 break;
1492
1493 case R.id.goto_menu_id:
1494 editUrl();
1495 break;
1496
1497 case R.id.bookmarks_menu_id:
1498 bookmarksOrHistoryPicker(false);
1499 break;
1500
1501 case R.id.active_tabs_menu_id:
1502 showActiveTabsPage();
1503 break;
1504
1505 case R.id.add_bookmark_menu_id:
1506 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
1507 break;
1508
1509 case R.id.stop_reload_menu_id:
1510 if (mInLoad) {
1511 stopLoading();
1512 } else {
1513 getCurrentTopWebView().reload();
1514 }
1515 break;
1516
1517 case R.id.back_menu_id:
1518 getCurrentTopWebView().goBack();
1519 break;
1520
1521 case R.id.forward_menu_id:
1522 getCurrentTopWebView().goForward();
1523 break;
1524
1525 case R.id.close_menu_id:
1526 // Close the subwindow if it exists.
1527 if (mTabControl.getCurrentSubWindow() != null) {
1528 dismissSubWindow(mTabControl.getCurrentTab());
1529 break;
1530 }
1531 closeCurrentTab();
1532 break;
1533
1534 case R.id.homepage_menu_id:
1535 Tab current = mTabControl.getCurrentTab();
1536 if (current != null) {
1537 dismissSubWindow(current);
1538 loadUrl(current.getWebView(), mSettings.getHomePage());
1539 }
1540 break;
1541
1542 case R.id.preferences_menu_id:
1543 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1544 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1545 getCurrentTopWebView().getUrl());
1546 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1547 break;
1548
1549 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001550 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001551 break;
1552
1553 case R.id.page_info_menu_id:
1554 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1555 false);
1556 break;
1557
1558 case R.id.classic_history_menu_id:
1559 bookmarksOrHistoryPicker(true);
1560 break;
1561
1562 case R.id.title_bar_share_page_url:
1563 case R.id.share_page_menu_id:
1564 Tab currentTab = mTabControl.getCurrentTab();
1565 if (null == currentTab) {
1566 mCanChord = false;
1567 return false;
1568 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001569 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001570 break;
1571
1572 case R.id.dump_nav_menu_id:
1573 getCurrentTopWebView().debugDump();
1574 break;
1575
1576 case R.id.dump_counters_menu_id:
1577 getCurrentTopWebView().dumpV8Counters();
1578 break;
1579
1580 case R.id.zoom_in_menu_id:
1581 getCurrentTopWebView().zoomIn();
1582 break;
1583
1584 case R.id.zoom_out_menu_id:
1585 getCurrentTopWebView().zoomOut();
1586 break;
1587
1588 case R.id.view_downloads_menu_id:
1589 viewDownloads();
1590 break;
1591
1592 case R.id.window_one_menu_id:
1593 case R.id.window_two_menu_id:
1594 case R.id.window_three_menu_id:
1595 case R.id.window_four_menu_id:
1596 case R.id.window_five_menu_id:
1597 case R.id.window_six_menu_id:
1598 case R.id.window_seven_menu_id:
1599 case R.id.window_eight_menu_id:
1600 {
1601 int menuid = item.getItemId();
1602 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1603 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1604 Tab desiredTab = mTabControl.getTab(id);
1605 if (desiredTab != null &&
1606 desiredTab != mTabControl.getCurrentTab()) {
1607 switchToTab(id);
1608 }
1609 break;
1610 }
1611 }
1612 }
1613 break;
1614
1615 default:
1616 return false;
1617 }
1618 mCanChord = false;
1619 return true;
1620 }
1621
1622 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001623 // Let the History and Bookmark fragments handle menus they created.
1624 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1625 return false;
1626 }
1627
Michael Kolb8233fac2010-10-26 16:08:53 -07001628 // chording is not an issue with context menus, but we use the same
1629 // options selector, so set mCanChord to true so we can access them.
1630 mCanChord = true;
1631 int id = item.getItemId();
1632 boolean result = true;
1633 switch (id) {
1634 // For the context menu from the title bar
1635 case R.id.title_bar_copy_page_url:
1636 Tab currentTab = mTabControl.getCurrentTab();
1637 if (null == currentTab) {
1638 result = false;
1639 break;
1640 }
1641 WebView mainView = currentTab.getWebView();
1642 if (null == mainView) {
1643 result = false;
1644 break;
1645 }
1646 copy(mainView.getUrl());
1647 break;
1648 // -- Browser context menu
1649 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001650 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001651 case R.id.copy_link_context_menu_id:
1652 final WebView webView = getCurrentTopWebView();
1653 if (null == webView) {
1654 result = false;
1655 break;
1656 }
1657 final HashMap<String, WebView> hrefMap =
1658 new HashMap<String, WebView>();
1659 hrefMap.put("webview", webView);
1660 final Message msg = mHandler.obtainMessage(
1661 FOCUS_NODE_HREF, id, 0, hrefMap);
1662 webView.requestFocusNodeHref(msg);
1663 break;
1664
1665 default:
1666 // For other context menus
1667 result = onOptionsItemSelected(item);
1668 }
1669 mCanChord = false;
1670 return result;
1671 }
1672
1673 /**
1674 * support programmatically opening the context menu
1675 */
1676 public void openContextMenu(View view) {
1677 mActivity.openContextMenu(view);
1678 }
1679
1680 /**
1681 * programmatically open the options menu
1682 */
1683 public void openOptionsMenu() {
1684 mActivity.openOptionsMenu();
1685 }
1686
1687 public boolean onMenuOpened(int featureId, Menu menu) {
1688 if (mOptionsMenuOpen) {
1689 if (mConfigChanged) {
1690 // We do not need to make any changes to the state of the
1691 // title bar, since the only thing that happened was a
1692 // change in orientation
1693 mConfigChanged = false;
1694 } else {
1695 if (!mExtendedMenuOpen) {
1696 mExtendedMenuOpen = true;
1697 mUi.onExtendedMenuOpened();
1698 } else {
1699 // Switching the menu back to icon view, so show the
1700 // title bar once again.
1701 mExtendedMenuOpen = false;
1702 mUi.onExtendedMenuClosed(mInLoad);
1703 mUi.onOptionsMenuOpened();
1704 }
1705 }
1706 } else {
1707 // The options menu is closed, so open it, and show the title
1708 mOptionsMenuOpen = true;
1709 mConfigChanged = false;
1710 mExtendedMenuOpen = false;
1711 mUi.onOptionsMenuOpened();
1712 }
1713 return true;
1714 }
1715
1716 public void onOptionsMenuClosed(Menu menu) {
1717 mOptionsMenuOpen = false;
1718 mUi.onOptionsMenuClosed(mInLoad);
1719 }
1720
1721 public void onContextMenuClosed(Menu menu) {
1722 mUi.onContextMenuClosed(menu, mInLoad);
1723 }
1724
1725 // Helper method for getting the top window.
1726 @Override
1727 public WebView getCurrentTopWebView() {
1728 return mTabControl.getCurrentTopWebView();
1729 }
1730
1731 @Override
1732 public WebView getCurrentWebView() {
1733 return mTabControl.getCurrentWebView();
1734 }
1735
1736 /*
1737 * This method is called as a result of the user selecting the options
1738 * menu to see the download window. It shows the download window on top of
1739 * the current window.
1740 */
1741 void viewDownloads() {
1742 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1743 mActivity.startActivity(intent);
1744 }
1745
1746 // action mode
1747
1748 void onActionModeStarted(ActionMode mode) {
1749 mUi.onActionModeStarted(mode);
1750 mActionMode = mode;
1751 }
1752
1753 /*
1754 * True if a custom ActionMode (i.e. find or select) is in use.
1755 */
1756 @Override
1757 public boolean isInCustomActionMode() {
1758 return mActionMode != null;
1759 }
1760
1761 /*
1762 * End the current ActionMode.
1763 */
1764 @Override
1765 public void endActionMode() {
1766 if (mActionMode != null) {
1767 mActionMode.finish();
1768 }
1769 }
1770
1771 /*
1772 * Called by find and select when they are finished. Replace title bars
1773 * as necessary.
1774 */
1775 public void onActionModeFinished(ActionMode mode) {
1776 if (!isInCustomActionMode()) return;
1777 mUi.onActionModeFinished(mInLoad);
1778 mActionMode = null;
1779 }
1780
1781 boolean isInLoad() {
1782 return mInLoad;
1783 }
1784
1785 // bookmark handling
1786
1787 /**
1788 * add the current page as a bookmark to the given folder id
1789 * @param folderId use -1 for the default folder
1790 */
1791 @Override
1792 public void bookmarkCurrentPage(long folderId) {
1793 Intent i = new Intent(mActivity,
1794 AddBookmarkPage.class);
1795 WebView w = getCurrentTopWebView();
1796 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1797 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1798 String touchIconUrl = w.getTouchIconUrl();
1799 if (touchIconUrl != null) {
1800 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1801 WebSettings settings = w.getSettings();
1802 if (settings != null) {
1803 i.putExtra(AddBookmarkPage.USER_AGENT,
1804 settings.getUserAgentString());
1805 }
1806 }
1807 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1808 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1809 getDesiredThumbnailHeight(mActivity)));
1810 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1811 i.putExtra(BrowserContract.Bookmarks.PARENT,
1812 folderId);
1813 // Put the dialog at the upper right of the screen, covering the
1814 // star on the title bar.
1815 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1816 mActivity.startActivity(i);
1817 }
1818
1819 // file chooser
1820 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1821 mUploadHandler = new UploadHandler(this);
1822 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1823 }
1824
1825 // thumbnails
1826
1827 /**
1828 * Return the desired width for thumbnail screenshots, which are stored in
1829 * the database, and used on the bookmarks screen.
1830 * @param context Context for finding out the density of the screen.
1831 * @return desired width for thumbnail screenshot.
1832 */
1833 static int getDesiredThumbnailWidth(Context context) {
1834 return context.getResources().getDimensionPixelOffset(
1835 R.dimen.bookmarkThumbnailWidth);
1836 }
1837
1838 /**
1839 * Return the desired height for thumbnail screenshots, which are stored in
1840 * the database, and used on the bookmarks screen.
1841 * @param context Context for finding out the density of the screen.
1842 * @return desired height for thumbnail screenshot.
1843 */
1844 static int getDesiredThumbnailHeight(Context context) {
1845 return context.getResources().getDimensionPixelOffset(
1846 R.dimen.bookmarkThumbnailHeight);
1847 }
1848
1849 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001850 // We render to a bitmap 2x the desired size so that we can then
1851 // re-scale it with filtering since canvas.scale doesn't filter
1852 // This helps reduce aliasing at the cost of being slightly blurry
1853 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001854 Picture thumbnail = view.capturePicture();
1855 if (thumbnail == null) {
1856 return null;
1857 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001858 width *= filter_scale;
1859 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001860 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1861 Canvas canvas = new Canvas(bm);
1862 // May need to tweak these values to determine what is the
1863 // best scale factor
1864 int thumbnailWidth = thumbnail.getWidth();
1865 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001866 float scaleFactor = 1.0f;
Michael Kolb8233fac2010-10-26 16:08:53 -07001867 if (thumbnailWidth > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001868 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001869 } else {
1870 return null;
1871 }
John Reckfe49ab42010-11-16 17:09:37 -08001872
Michael Kolb8233fac2010-10-26 16:08:53 -07001873 if (view.getWidth() > view.getHeight() &&
1874 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
1875 // If the device is in landscape and the page is shorter
John Reckfe49ab42010-11-16 17:09:37 -08001876 // than the height of the view, center the thumnail and crop the sides
1877 scaleFactor = (float) height / (float)thumbnailHeight;
1878 float wx = (thumbnailWidth * scaleFactor) - width;
1879 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001880 }
1881
John Reckfe49ab42010-11-16 17:09:37 -08001882 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001883
1884 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001885 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
1886 height / filter_scale, true);
1887 bm.recycle();
1888 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001889 }
1890
1891 private void updateScreenshot(WebView view) {
1892 // If this is a bookmarked site, add a screenshot to the database.
1893 // FIXME: When should we update? Every time?
1894 // FIXME: Would like to make sure there is actually something to
1895 // draw, but the API for that (WebViewCore.pictureReady()) is not
1896 // currently accessible here.
1897
1898 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1899 getDesiredThumbnailHeight(mActivity));
1900 if (bm == null) {
1901 return;
1902 }
1903
1904 final ContentResolver cr = mActivity.getContentResolver();
1905 final String url = view.getUrl();
1906 final String originalUrl = view.getOriginalUrl();
1907
John Recka00cbbd2010-12-16 12:38:19 -08001908 // Only update thumbnails for web urls (http(s)://), not for
1909 // about:, javascript:, data:, etc...
John Reck9d038482011-01-04 17:02:09 -08001910 if (url != null && Patterns.WEB_URL.matcher(url).matches()) {
John Recka00cbbd2010-12-16 12:38:19 -08001911 new AsyncTask<Void, Void, Void>() {
1912 @Override
1913 protected Void doInBackground(Void... unused) {
1914 Cursor cursor = null;
1915 try {
1916 // TODO: Clean this up
1917 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
1918 if (cursor != null && cursor.moveToFirst()) {
1919 final ByteArrayOutputStream os =
1920 new ByteArrayOutputStream();
1921 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07001922
John Recka00cbbd2010-12-16 12:38:19 -08001923 ContentValues values = new ContentValues();
1924 values.put(Images.THUMBNAIL, os.toByteArray());
1925 values.put(Images.URL, cursor.getString(0));
Michael Kolb8233fac2010-10-26 16:08:53 -07001926
John Recka00cbbd2010-12-16 12:38:19 -08001927 do {
1928 cr.update(Images.CONTENT_URI, values, null, null);
1929 } while (cursor.moveToNext());
1930 }
1931 } catch (IllegalStateException e) {
1932 // Ignore
1933 } finally {
1934 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07001935 }
John Recka00cbbd2010-12-16 12:38:19 -08001936 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07001937 }
John Recka00cbbd2010-12-16 12:38:19 -08001938 }.execute();
1939 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001940 }
1941
1942 private class Copy implements OnMenuItemClickListener {
1943 private CharSequence mText;
1944
1945 public boolean onMenuItemClick(MenuItem item) {
1946 copy(mText);
1947 return true;
1948 }
1949
1950 public Copy(CharSequence toCopy) {
1951 mText = toCopy;
1952 }
1953 }
1954
Leon Scroggins63c02662010-11-18 15:16:27 -05001955 private static class Download implements OnMenuItemClickListener {
1956 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001957 private String mText;
1958
1959 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05001960 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
1961 null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001962 return true;
1963 }
1964
Leon Scroggins63c02662010-11-18 15:16:27 -05001965 public Download(Activity activity, String toDownload) {
1966 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001967 mText = toDownload;
1968 }
1969 }
1970
Cary Clark8974d282010-11-22 10:46:05 -05001971 private static class SelectText implements OnMenuItemClickListener {
1972 private WebView mWebView;
1973
1974 public boolean onMenuItemClick(MenuItem item) {
1975 if (mWebView != null) {
1976 return mWebView.selectText();
1977 }
1978 return false;
1979 }
1980
1981 public SelectText(WebView webView) {
1982 mWebView = webView;
1983 }
1984
1985 }
1986
Michael Kolb8233fac2010-10-26 16:08:53 -07001987 /********************** TODO: UI stuff *****************************/
1988
1989 // these methods have been copied, they still need to be cleaned up
1990
1991 /****************** tabs ***************************************************/
1992
1993 // basic tab interactions:
1994
1995 // it is assumed that tabcontrol already knows about the tab
1996 protected void addTab(Tab tab) {
1997 mUi.addTab(tab);
1998 }
1999
2000 protected void removeTab(Tab tab) {
2001 mUi.removeTab(tab);
2002 mTabControl.removeTab(tab);
2003 }
2004
2005 protected void setActiveTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002006 mTabControl.setCurrentTab(tab);
Michael Kolb77df4562010-11-19 14:49:34 -08002007 // the tab is guaranteed to have a webview after setCurrentTab
2008 mUi.setActiveTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002009 }
2010
2011 protected void closeEmptyChildTab() {
2012 Tab current = mTabControl.getCurrentTab();
2013 if (current != null
2014 && current.getWebView().copyBackForwardList().getSize() == 0) {
2015 Tab parent = current.getParentTab();
2016 if (parent != null) {
2017 switchToTab(mTabControl.getTabIndex(parent));
2018 closeTab(current);
2019 }
2020 }
2021 }
2022
2023 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002024 // Dismiss the subwindow if applicable.
2025 dismissSubWindow(appTab);
2026 // Since we might kill the WebView, remove it from the
2027 // content view first.
2028 mUi.detachTab(appTab);
2029 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002030 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002031 // TODO: analyze why the remove and add are necessary
2032 mUi.attachTab(appTab);
2033 if (mTabControl.getCurrentTab() != appTab) {
2034 switchToTab(mTabControl.getTabIndex(appTab));
John Reck30c714c2010-12-16 17:30:34 -08002035 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002036 } else {
2037 // If the tab was the current tab, we have to attach
2038 // it to the view system again.
2039 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002040 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002041 }
2042 }
2043
2044 // Remove the sub window if it exists. Also called by TabControl when the
2045 // user clicks the 'X' to dismiss a sub window.
2046 public void dismissSubWindow(Tab tab) {
2047 removeSubWindow(tab);
2048 // dismiss the subwindow. This will destroy the WebView.
2049 tab.dismissSubWindow();
2050 getCurrentTopWebView().requestFocus();
2051 }
2052
2053 @Override
2054 public void removeSubWindow(Tab t) {
2055 if (t.getSubWebView() != null) {
2056 mUi.removeSubWindow(t.getSubViewContainer());
2057 }
2058 }
2059
2060 @Override
2061 public void attachSubWindow(Tab tab) {
2062 if (tab.getSubWebView() != null) {
2063 mUi.attachSubWindow(tab.getSubViewContainer());
2064 getCurrentTopWebView().requestFocus();
2065 }
2066 }
2067
Michael Kolb843510f2010-12-09 10:51:49 -08002068 @Override
2069 public Tab openTabToHomePage() {
2070 // check for max tabs
2071 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002072 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2073 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002074 } else {
2075 mUi.showMaxTabsWarning();
2076 return null;
2077 }
2078 }
2079
Michael Kolb18eb3772010-12-10 14:29:51 -08002080 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2081 if (mSettings.openInBackground() && !forceForeground) {
2082 Tab tab = mTabControl.createNewTab(false, null, null,
2083 (parent != null) && parent.isPrivateBrowsingEnabled());
2084 if (tab != null) {
2085 addTab(tab);
2086 WebView view = tab.getWebView();
2087 loadUrl(view, url);
2088 }
2089 return tab;
2090 } else {
2091 return openTabAndShow(parent, new UrlData(url), false, null);
2092 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002093 }
2094
Michael Kolb18eb3772010-12-10 14:29:51 -08002095
Michael Kolb8233fac2010-10-26 16:08:53 -07002096 // This method does a ton of stuff. It will attempt to create a new tab
2097 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2098 // url isn't null, it will load the given url.
Patrick Scottcd135082011-01-31 18:21:58 -05002099 public Tab openTabAndShow(Tab parent, final UrlData urlData,
2100 boolean closeOnExit, String appId) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002101 final Tab currentTab = mTabControl.getCurrentTab();
2102 if (mTabControl.canCreateNewTab()) {
2103 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Michael Kolb18eb3772010-12-10 14:29:51 -08002104 urlData.mUrl,
2105 (parent != null) && parent.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -07002106 WebView webview = tab.getWebView();
2107 // We must set the new tab as the current tab to reflect the old
2108 // animation behavior.
2109 addTab(tab);
2110 setActiveTab(tab);
Patrick Scottcd135082011-01-31 18:21:58 -05002111
2112 // Callback to load the url data.
2113 final Runnable load = new Runnable() {
2114 @Override public void run() {
2115 if (!urlData.isEmpty()) {
2116 loadUrlDataIn(tab, urlData);
2117 }
2118 }
2119 };
2120
2121 GoogleAccountLogin.startLoginIfNeeded(mActivity, mSettings, load);
Michael Kolb8233fac2010-10-26 16:08:53 -07002122 return tab;
2123 } else {
2124 // Get rid of the subwindow if it exists
2125 dismissSubWindow(currentTab);
2126 if (!urlData.isEmpty()) {
2127 // Load the given url.
2128 loadUrlDataIn(currentTab, urlData);
2129 }
2130 return currentTab;
2131 }
2132 }
2133
Michael Kolb8233fac2010-10-26 16:08:53 -07002134 @Override
2135 public Tab openIncognitoTab() {
2136 if (mTabControl.canCreateNewTab()) {
2137 Tab currentTab = mTabControl.getCurrentTab();
Michael Kolb8e7178d2011-01-26 19:13:36 -08002138 Tab tab = mTabControl.createNewTab(false, null,
John Reck4bfc0db2011-01-27 17:47:12 -08002139 null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07002140 addTab(tab);
2141 setActiveTab(tab);
John Reck4bfc0db2011-01-27 17:47:12 -08002142 loadUrlDataIn(tab, new UrlData("browser:incognito"));
Michael Kolb8233fac2010-10-26 16:08:53 -07002143 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002144 } else {
2145 mUi.showMaxTabsWarning();
2146 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002147 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002148 }
2149
2150 /**
2151 * @param index Index of the tab to change to, as defined by
2152 * mTabControl.getTabIndex(Tab t).
2153 * @return boolean True if we successfully switched to a different tab. If
2154 * the indexth tab is null, or if that tab is the same as
2155 * the current one, return false.
2156 */
2157 @Override
2158 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002159 // hide combo view if open
2160 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002161 Tab tab = mTabControl.getTab(index);
2162 Tab currentTab = mTabControl.getCurrentTab();
2163 if (tab == null || tab == currentTab) {
2164 return false;
2165 }
2166 setActiveTab(tab);
2167 return true;
2168 }
2169
2170 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002171 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002172 // hide combo view if open
2173 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002174 final Tab current = mTabControl.getCurrentTab();
2175 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002176 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002177 return;
2178 }
2179 final Tab parent = current.getParentTab();
2180 int indexToShow = -1;
2181 if (parent != null) {
2182 indexToShow = mTabControl.getTabIndex(parent);
2183 } else {
2184 final int currentIndex = mTabControl.getCurrentIndex();
2185 // Try to move to the tab to the right
2186 indexToShow = currentIndex + 1;
2187 if (indexToShow > mTabControl.getTabCount() - 1) {
2188 // Try to move to the tab to the left
2189 indexToShow = currentIndex - 1;
2190 }
2191 }
2192 if (switchToTab(indexToShow)) {
2193 // Close window
2194 closeTab(current);
2195 }
2196 }
2197
2198 /**
2199 * Close the tab, remove its associated title bar, and adjust mTabControl's
2200 * current tab to a valid value.
2201 */
2202 @Override
2203 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002204 // hide combo view if open
2205 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002206 int currentIndex = mTabControl.getCurrentIndex();
2207 int removeIndex = mTabControl.getTabIndex(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002208 Tab newtab = mTabControl.getTab(currentIndex);
2209 setActiveTab(newtab);
Michael Kolb2d59c322011-01-25 13:18:55 -08002210 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002211 }
2212
2213 /**************** TODO: Url loading clean up *******************************/
2214
2215 // Called when loading from context menu or LOAD_URL message
2216 protected void loadUrlFromContext(WebView view, String url) {
2217 // In case the user enters nothing.
2218 if (url != null && url.length() != 0 && view != null) {
2219 url = UrlUtils.smartUrlFilter(url);
2220 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2221 loadUrl(view, url);
2222 }
2223 }
2224 }
2225
2226 /**
2227 * Load the URL into the given WebView and update the title bar
2228 * to reflect the new load. Call this instead of WebView.loadUrl
2229 * directly.
2230 * @param view The WebView used to load url.
2231 * @param url The URL to load.
2232 */
2233 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002234 view.loadUrl(url);
2235 }
2236
2237 /**
2238 * Load UrlData into a Tab and update the title bar to reflect the new
2239 * load. Call this instead of UrlData.loadIn directly.
2240 * @param t The Tab used to load.
2241 * @param data The UrlData being loaded.
2242 */
2243 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002244 data.loadIn(t);
2245 }
2246
John Reck30c714c2010-12-16 17:30:34 -08002247 @Override
2248 public void onUserCanceledSsl(Tab tab) {
2249 WebView web = tab.getWebView();
2250 // TODO: Figure out the "right" behavior
2251 if (web.canGoBack()) {
2252 web.goBack();
2253 } else {
2254 web.loadUrl(mSettings.getHomePage());
2255 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002256 }
2257
2258 void goBackOnePageOrQuit() {
2259 Tab current = mTabControl.getCurrentTab();
2260 if (current == null) {
2261 /*
2262 * Instead of finishing the activity, simply push this to the back
2263 * of the stack and let ActivityManager to choose the foreground
2264 * activity. As BrowserActivity is singleTask, it will be always the
2265 * root of the task. So we can use either true or false for
2266 * moveTaskToBack().
2267 */
2268 mActivity.moveTaskToBack(true);
2269 return;
2270 }
2271 WebView w = current.getWebView();
2272 if (w.canGoBack()) {
2273 w.goBack();
2274 } else {
2275 // Check to see if we are closing a window that was created by
2276 // another window. If so, we switch back to that window.
2277 Tab parent = current.getParentTab();
2278 if (parent != null) {
2279 switchToTab(mTabControl.getTabIndex(parent));
2280 // Now we close the other tab
2281 closeTab(current);
2282 } else {
2283 if (current.closeOnExit()) {
2284 // force the tab's inLoad() to be false as we are going to
2285 // either finish the activity or remove the tab. This will
2286 // ensure pauseWebViewTimers() taking action.
Michael Kolb70976932010-11-30 11:34:01 -08002287 current.clearInPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07002288 if (mTabControl.getTabCount() == 1) {
2289 mActivity.finish();
2290 return;
2291 }
2292 if (mActivityPaused) {
2293 Log.e(LOGTAG, "BrowserActivity is already paused "
2294 + "while handing goBackOnePageOrQuit.");
2295 }
Michael Kolb70976932010-11-30 11:34:01 -08002296 pauseWebViewTimers(current);
Michael Kolb8233fac2010-10-26 16:08:53 -07002297 removeTab(current);
2298 }
2299 /*
2300 * Instead of finishing the activity, simply push this to the back
2301 * of the stack and let ActivityManager to choose the foreground
2302 * activity. As BrowserActivity is singleTask, it will be always the
2303 * root of the task. So we can use either true or false for
2304 * moveTaskToBack().
2305 */
2306 mActivity.moveTaskToBack(true);
2307 }
2308 }
2309 }
2310
2311 /**
2312 * Feed the previously stored results strings to the BrowserProvider so that
2313 * the SearchDialog will show them instead of the standard searches.
2314 * @param result String to show on the editable line of the SearchDialog.
2315 */
2316 @Override
2317 public void showVoiceSearchResults(String result) {
2318 ContentProviderClient client = mActivity.getContentResolver()
2319 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2320 ContentProvider prov = client.getLocalContentProvider();
2321 BrowserProvider bp = (BrowserProvider) prov;
2322 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2323 client.release();
2324
2325 Bundle bundle = createGoogleSearchSourceBundle(
2326 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2327 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2328 startSearch(result, false, bundle, false);
2329 }
2330
2331 private void startSearch(String initialQuery, boolean selectInitialQuery,
2332 Bundle appSearchData, boolean globalSearch) {
2333 if (appSearchData == null) {
2334 appSearchData = createGoogleSearchSourceBundle(
2335 GOOGLE_SEARCH_SOURCE_TYPE);
2336 }
2337
2338 SearchEngine searchEngine = mSettings.getSearchEngine();
2339 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2340 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2341 }
2342 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2343 globalSearch);
2344 }
2345
2346 private Bundle createGoogleSearchSourceBundle(String source) {
2347 Bundle bundle = new Bundle();
2348 bundle.putString(Search.SOURCE, source);
2349 return bundle;
2350 }
2351
2352 /**
2353 * handle key events in browser
2354 *
2355 * @param keyCode
2356 * @param event
2357 * @return true if handled, false to pass to super
2358 */
2359 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002360 boolean noModifiers = event.hasNoModifiers();
2361
Michael Kolb8233fac2010-10-26 16:08:53 -07002362 // Even if MENU is already held down, we need to call to super to open
2363 // the IME on long press.
Cary Clark160bbb92011-01-10 11:17:07 -05002364 if (!noModifiers && KeyEvent.KEYCODE_MENU == keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002365 mMenuIsDown = true;
2366 return false;
2367 }
2368 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2369 // still down, we don't want to trigger the search. Pretend to consume
2370 // the key and do nothing.
2371 if (mMenuIsDown) return true;
2372
Cary Clark8ff8c662010-12-29 15:03:05 -05002373 WebView webView = getCurrentTopWebView();
2374 if (webView == null) return false;
2375
Cary Clark160bbb92011-01-10 11:17:07 -05002376 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2377 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002378
Michael Kolb8233fac2010-10-26 16:08:53 -07002379 switch(keyCode) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002380 case KeyEvent.KEYCODE_ESCAPE:
Cary Clark160bbb92011-01-10 11:17:07 -05002381 if (!noModifiers) break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002382 stopLoading();
2383 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07002384 case KeyEvent.KEYCODE_SPACE:
2385 // WebView/WebTextView handle the keys in the KeyDown. As
2386 // the Activity's shortcut keys are only handled when WebView
2387 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002388 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002389 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002390 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002391 pageDown();
2392 }
2393 return true;
2394 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002395 if (!noModifiers) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002396 if (event.getRepeatCount() == 0) {
2397 event.startTracking();
2398 return true;
2399 } else if (mUi.showsWeb()
2400 && event.isLongPress()) {
2401 bookmarksOrHistoryPicker(true);
2402 return true;
2403 }
2404 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002405 case KeyEvent.KEYCODE_DPAD_LEFT:
2406 if (ctrl) {
2407 webView.goBack();
2408 return true;
2409 }
2410 break;
2411 case KeyEvent.KEYCODE_DPAD_RIGHT:
2412 if (ctrl) {
2413 webView.goForward();
2414 return true;
2415 }
2416 break;
2417 case KeyEvent.KEYCODE_A:
2418 if (ctrl) {
2419 webView.selectAll();
2420 return true;
2421 }
2422 break;
Michael Kolba4183062011-01-16 10:43:21 -08002423// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002424 case KeyEvent.KEYCODE_C:
2425 if (ctrl) {
2426 webView.copySelection();
2427 return true;
2428 }
2429 break;
Michael Kolba4183062011-01-16 10:43:21 -08002430// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002431// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002432// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002433// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002434// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002435// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002436// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002437// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002438// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002439// case KeyEvent.KEYCODE_M: // unused
2440// case KeyEvent.KEYCODE_N: // in Chrome: new window
2441// case KeyEvent.KEYCODE_O: // in Chrome: open file
2442// case KeyEvent.KEYCODE_P: // in Chrome: print page
2443// case KeyEvent.KEYCODE_Q: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002444// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002445// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2446 case KeyEvent.KEYCODE_T:
2447 if (ctrl) {
2448 if (event.isShiftPressed()) {
2449 openIncognitoTab();
2450 } else {
2451 openTabToHomePage();
2452 }
2453 return true;
2454 }
2455 break;
2456// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2457// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolba4183062011-01-16 10:43:21 -08002458// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002459// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2460// case KeyEvent.KEYCODE_Y: // unused
2461// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002462 }
Michael Kolba4183062011-01-16 10:43:21 -08002463 // if we get here, it is a regular key and webview is not null
2464 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002465 }
2466
2467 boolean onKeyUp(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002468 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002469 switch(keyCode) {
2470 case KeyEvent.KEYCODE_MENU:
2471 mMenuIsDown = false;
2472 break;
2473 case KeyEvent.KEYCODE_BACK:
2474 if (event.isTracking() && !event.isCanceled()) {
2475 onBackKey();
2476 return true;
2477 }
2478 break;
2479 }
2480 return false;
2481 }
2482
2483 public boolean isMenuDown() {
2484 return mMenuIsDown;
2485 }
2486
Ben Murdoch8029a772010-11-16 11:58:21 +00002487 public void setupAutoFill(Message message) {
2488 // Open the settings activity at the AutoFill profile fragment so that
2489 // the user can create a new profile. When they return, we will dispatch
2490 // the message so that we can autofill the form using their new profile.
2491 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2492 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2493 AutoFillSettingsFragment.class.getName());
2494 mAutoFillSetupMessage = message;
2495 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2496 }
John Reckb3417f02011-01-14 11:01:05 -08002497
2498 @Override
2499 public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
2500 mOptionsMenuHandler = handler;
2501 }
2502
2503 @Override
2504 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
2505 if (mOptionsMenuHandler == handler) {
2506 mOptionsMenuHandler = null;
2507 }
2508 }
2509
Michael Kolb8233fac2010-10-26 16:08:53 -07002510}