blob: 3e0b7f06cbc149e946aac760e52f6e1f1355311e [file] [log] [blame]
Michael Kolb8233fac2010-10-26 16:08:53 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
19import com.android.browser.IntentHandler.UrlData;
20import com.android.browser.search.SearchEngine;
21import com.android.common.Search;
22
23import android.app.Activity;
24import android.app.DownloadManager;
25import android.app.SearchManager;
26import android.content.ClipboardManager;
27import android.content.ContentProvider;
28import android.content.ContentProviderClient;
29import android.content.ContentResolver;
30import android.content.ContentValues;
31import android.content.Context;
32import android.content.Intent;
33import android.content.pm.PackageManager;
34import android.content.pm.ResolveInfo;
35import android.content.res.Configuration;
Leon Scroggins1961ed22010-12-07 15:22:21 -050036import android.database.ContentObserver;
Michael Kolb8233fac2010-10-26 16:08:53 -070037import android.database.Cursor;
38import android.database.sqlite.SQLiteDatabase;
Michael Kolb8233fac2010-10-26 16:08:53 -070039import android.graphics.Bitmap;
40import android.graphics.Canvas;
41import android.graphics.Picture;
42import android.net.Uri;
43import android.net.http.SslError;
44import android.os.AsyncTask;
45import android.os.Bundle;
46import android.os.Handler;
47import android.os.Message;
48import android.os.PowerManager;
49import android.os.PowerManager.WakeLock;
Ben Murdoch8029a772010-11-16 11:58:21 +000050import android.preference.PreferenceActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -070051import android.provider.Browser;
52import android.provider.BrowserContract;
Michael Kolb8233fac2010-10-26 16:08:53 -070053import android.provider.BrowserContract.Images;
54import android.provider.ContactsContract;
55import android.provider.ContactsContract.Intents.Insert;
Michael Kolbcfa3af52010-12-14 10:36:11 -080056import android.speech.RecognizerIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070057import android.speech.RecognizerResultsIntent;
58import android.text.TextUtils;
59import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080060import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070061import android.view.ActionMode;
62import android.view.ContextMenu;
63import android.view.ContextMenu.ContextMenuInfo;
64import android.view.Gravity;
65import android.view.KeyEvent;
66import android.view.LayoutInflater;
67import android.view.Menu;
68import android.view.MenuInflater;
69import android.view.MenuItem;
70import android.view.MenuItem.OnMenuItemClickListener;
71import android.view.View;
72import android.webkit.CookieManager;
73import android.webkit.CookieSyncManager;
74import android.webkit.HttpAuthHandler;
75import android.webkit.SslErrorHandler;
76import android.webkit.ValueCallback;
77import android.webkit.WebChromeClient;
78import android.webkit.WebIconDatabase;
79import android.webkit.WebSettings;
80import android.webkit.WebView;
81import android.widget.TextView;
82
83import java.io.ByteArrayOutputStream;
84import java.io.File;
85import java.net.URLEncoder;
86import java.util.Calendar;
87import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -080088import java.util.List;
Michael Kolb8233fac2010-10-26 16:08:53 -070089
90/**
91 * Controller for browser
92 */
93public class Controller
94 implements WebViewController, UiController {
95
96 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -080097 private static final String SEND_APP_ID_EXTRA =
98 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
99
Michael Kolb8233fac2010-10-26 16:08:53 -0700100
101 // public message ids
102 public final static int LOAD_URL = 1001;
103 public final static int STOP_LOAD = 1002;
104
105 // Message Ids
106 private static final int FOCUS_NODE_HREF = 102;
107 private static final int RELEASE_WAKELOCK = 107;
108
109 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
110
111 private static final int OPEN_BOOKMARKS = 201;
112
113 private static final int EMPTY_MENU = -1;
114
Michael Kolb8233fac2010-10-26 16:08:53 -0700115 // activity requestCode
116 final static int PREFERENCES_PAGE = 3;
117 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000118 final static int AUTOFILL_SETUP = 5;
119
Michael Kolb8233fac2010-10-26 16:08:53 -0700120 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
121
122 // As the ids are dynamically created, we can't guarantee that they will
123 // be in sequence, so this static array maps ids to a window number.
124 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
125 { R.id.window_one_menu_id, R.id.window_two_menu_id,
126 R.id.window_three_menu_id, R.id.window_four_menu_id,
127 R.id.window_five_menu_id, R.id.window_six_menu_id,
128 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
129
130 // "source" parameter for Google search through search key
131 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
132 // "source" parameter for Google search through simplily type
133 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
134
135 private Activity mActivity;
136 private UI mUi;
137 private TabControl mTabControl;
138 private BrowserSettings mSettings;
139 private WebViewFactory mFactory;
140
141 private WakeLock mWakeLock;
142
143 private UrlHandler mUrlHandler;
144 private UploadHandler mUploadHandler;
145 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700146 private PageDialogsHandler mPageDialogsHandler;
147 private NetworkStateHandler mNetworkHandler;
148
Ben Murdoch8029a772010-11-16 11:58:21 +0000149 private Message mAutoFillSetupMessage;
150
Michael Kolb8233fac2010-10-26 16:08:53 -0700151 private boolean mShouldShowErrorConsole;
152
153 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
154
155 // FIXME, temp address onPrepareMenu performance problem.
156 // When we move everything out of view, we should rewrite this.
157 private int mCurrentMenuState = 0;
158 private int mMenuState = R.id.MAIN_MENU;
159 private int mOldMenuState = EMPTY_MENU;
160 private Menu mCachedMenu;
161
162 // Used to prevent chording to result in firing two shortcuts immediately
163 // one after another. Fixes bug 1211714.
164 boolean mCanChord;
165 private boolean mMenuIsDown;
166
167 // For select and find, we keep track of the ActionMode so that
168 // finish() can be called as desired.
169 private ActionMode mActionMode;
170
171 /**
172 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
173 * of whether the configuration has changed. The first onMenuOpened call
174 * after a configuration change is simply a reopening of the same menu
175 * (i.e. mIconView did not change).
176 */
177 private boolean mConfigChanged;
178
179 /**
180 * Keeps track of whether the options menu is open. This is important in
181 * determining whether to show or hide the title bar overlay
182 */
183 private boolean mOptionsMenuOpen;
184
185 /**
186 * Whether or not the options menu is in its bigger, popup menu form. When
187 * true, we want the title bar overlay to be gone. When false, we do not.
188 * Only meaningful if mOptionsMenuOpen is true.
189 */
190 private boolean mExtendedMenuOpen;
191
192 private boolean mInLoad;
193
194 private boolean mActivityPaused = true;
195 private boolean mLoadStopped;
196
197 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500198 // Checks to see when the bookmarks database has changed, and updates the
199 // Tabs' notion of whether they represent bookmarked sites.
200 private ContentObserver mBookmarksObserver;
John Reck0ebd3ac2010-12-09 11:14:04 -0800201 private DataController mDataController;
Michael Kolb8233fac2010-10-26 16:08:53 -0700202
203 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
204 @Override
205 public Void doInBackground(File... files) {
206 if (files != null) {
207 for (File f : files) {
208 if (!f.delete()) {
209 Log.e(LOGTAG, f.getPath() + " was not deleted");
210 }
211 }
212 }
213 return null;
214 }
215 }
216
217 public Controller(Activity browser) {
218 mActivity = browser;
219 mSettings = BrowserSettings.getInstance();
John Reck0ebd3ac2010-12-09 11:14:04 -0800220 mDataController = DataController.getInstance(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700221 mTabControl = new TabControl(this);
222 mSettings.setController(this);
223
224 mUrlHandler = new UrlHandler(this);
225 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700226 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
227
228 PowerManager pm = (PowerManager) mActivity
229 .getSystemService(Context.POWER_SERVICE);
230 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
231
232 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500233 mBookmarksObserver = new ContentObserver(mHandler) {
234 @Override
235 public void onChange(boolean selfChange) {
236 int size = mTabControl.getTabCount();
237 for (int i = 0; i < size; i++) {
238 mTabControl.getTab(i).updateBookmarkedStatus();
239 }
240 }
241
242 };
243 browser.getContentResolver().registerContentObserver(
244 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700245
246 mNetworkHandler = new NetworkStateHandler(mActivity, this);
247 // Start watching the default geolocation permissions
248 mSystemAllowGeolocationOrigins =
249 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
250 mSystemAllowGeolocationOrigins.start();
251
252 retainIconsOnStartup();
253 }
254
255 void start(Bundle icicle, Intent intent) {
256 // Unless the last browser usage was within 24 hours, destroy any
257 // remaining incognito tabs.
258
259 Calendar lastActiveDate = icicle != null ?
260 (Calendar) icicle.getSerializable("lastActiveDate") : null;
261 Calendar today = Calendar.getInstance();
262 Calendar yesterday = Calendar.getInstance();
263 yesterday.add(Calendar.DATE, -1);
264
Michael Kolb1bf23132010-11-19 12:55:12 -0800265 boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700266 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800267 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700268
Michael Kolb1bf23132010-11-19 12:55:12 -0800269 if (!mTabControl.restoreState(icicle, restoreIncognitoTabs,
270 mUi.needsRestoreAllTabs())) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700271 // there is no quit on Android. But if we can't restore the state,
272 // we can treat it as a new Browser, remove the old session cookies.
Kristian Monsen3a4e8092010-12-08 11:09:25 +0000273 // This is done async in the CookieManager.
274 CookieManager.getInstance().removeSessionCookie();
Kristian Monsen2cd97012010-12-07 11:11:40 +0000275
Michael Kolb8233fac2010-10-26 16:08:53 -0700276 final Bundle extra = intent.getExtras();
277 // Create an initial tab.
278 // If the intent is ACTION_VIEW and data is not null, the Browser is
279 // invoked to view the content by another application. In this case,
280 // the tab will be close when exit.
281 UrlData urlData = mIntentHandler.getUrlDataFromIntent(intent);
282
283 String action = intent.getAction();
284 final Tab t = mTabControl.createNewTab(
285 (Intent.ACTION_VIEW.equals(action) &&
286 intent.getData() != null)
287 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
288 .equals(action),
289 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
290 urlData.mUrl, false);
291 addTab(t);
292 setActiveTab(t);
293 WebView webView = t.getWebView();
294 if (extra != null) {
295 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
296 if (scale > 0 && scale <= 1000) {
297 webView.setInitialScale(scale);
298 }
299 }
300
301 if (urlData.isEmpty()) {
302 loadUrl(webView, mSettings.getHomePage());
303 } else {
304 loadUrlDataIn(t, urlData);
305 }
306 } else {
Michael Kolb1bf23132010-11-19 12:55:12 -0800307 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700308 // TabControl.restoreState() will create a new tab even if
309 // restoring the state fails.
310 setActiveTab(mTabControl.getCurrentTab());
311 }
312 // clear up the thumbnail directory, which is no longer used;
313 // ideally this should only be run once after an upgrade from
314 // a previous version of the browser
315 new ClearThumbnails().execute(mTabControl.getThumbnailDir()
316 .listFiles());
317 // Read JavaScript flags if it exists.
318 String jsFlags = getSettings().getJsFlags();
319 if (jsFlags.trim().length() != 0) {
320 getCurrentWebView().setJsFlags(jsFlags);
321 }
John Reck439c9a52010-12-14 10:04:39 -0800322 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
323 bookmarksOrHistoryPicker(false);
324 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700325 }
326
327 void setWebViewFactory(WebViewFactory factory) {
328 mFactory = factory;
329 }
330
Michael Kolb1514bb72010-11-22 09:11:48 -0800331 @Override
332 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700333 return mFactory;
334 }
335
336 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800337 public void onSetWebView(Tab tab, WebView view) {
338 mUi.onSetWebView(tab, view);
339 }
340
341 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800342 public void createSubWindow(Tab tab) {
343 endActionMode();
344 WebView mainView = tab.getWebView();
345 WebView subView = mFactory.createWebView((mainView == null)
346 ? false
347 : mainView.isPrivateBrowsingEnabled());
348 mUi.createSubWindow(tab, subView);
349 }
350
351 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700352 public Activity getActivity() {
353 return mActivity;
354 }
355
356 void setUi(UI ui) {
357 mUi = ui;
358 }
359
360 BrowserSettings getSettings() {
361 return mSettings;
362 }
363
364 IntentHandler getIntentHandler() {
365 return mIntentHandler;
366 }
367
368 @Override
369 public UI getUi() {
370 return mUi;
371 }
372
373 int getMaxTabs() {
374 return mActivity.getResources().getInteger(R.integer.max_tabs);
375 }
376
377 @Override
378 public TabControl getTabControl() {
379 return mTabControl;
380 }
381
Michael Kolb1bf23132010-11-19 12:55:12 -0800382 @Override
383 public List<Tab> getTabs() {
384 return mTabControl.getTabs();
385 }
386
Michael Kolb8233fac2010-10-26 16:08:53 -0700387 // Open the icon database and retain all the icons for visited sites.
Ben Murdoch9446b932010-11-25 16:20:14 +0000388 // This is done on a background thread so as not to stall startup.
Michael Kolb8233fac2010-10-26 16:08:53 -0700389 private void retainIconsOnStartup() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000390 // WebIconDatabase needs to be retrieved on the UI thread so that if
391 // it has not been created successfully yet the Handler is started on the
392 // UI thread.
393 new RetainIconsOnStartupTask(WebIconDatabase.getInstance()).execute();
394 }
395
396 private class RetainIconsOnStartupTask extends AsyncTask<Void, Void, Void> {
397 private WebIconDatabase mDb;
398
399 public RetainIconsOnStartupTask(WebIconDatabase db) {
400 mDb = db;
401 }
402
John Recka00cbbd2010-12-16 12:38:19 -0800403 @Override
Ben Murdoch9446b932010-11-25 16:20:14 +0000404 protected Void doInBackground(Void... unused) {
405 mDb.open(mActivity.getDir("icons", 0).getPath());
406 Cursor c = null;
407 try {
408 c = Browser.getAllBookmarks(mActivity.getContentResolver());
409 if (c.moveToFirst()) {
410 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
411 do {
412 String url = c.getString(urlIndex);
413 mDb.retainIconForPageUrl(url);
414 } while (c.moveToNext());
415 }
416 } catch (IllegalStateException e) {
417 Log.e(LOGTAG, "retainIconsOnStartup", e);
418 } finally {
419 if (c != null) c.close();
Michael Kolb8233fac2010-10-26 16:08:53 -0700420 }
Ben Murdoch9446b932010-11-25 16:20:14 +0000421
422 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700423 }
424 }
425
426 private void startHandler() {
427 mHandler = new Handler() {
428
429 @Override
430 public void handleMessage(Message msg) {
431 switch (msg.what) {
432 case OPEN_BOOKMARKS:
433 bookmarksOrHistoryPicker(false);
434 break;
435 case FOCUS_NODE_HREF:
436 {
437 String url = (String) msg.getData().get("url");
438 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500439 String src = (String) msg.getData().get("src");
440 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700441 if (TextUtils.isEmpty(url)) {
442 break;
443 }
444 HashMap focusNodeMap = (HashMap) msg.obj;
445 WebView view = (WebView) focusNodeMap.get("webview");
446 // Only apply the action if the top window did not change.
447 if (getCurrentTopWebView() != view) {
448 break;
449 }
450 switch (msg.arg1) {
451 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -0700452 loadUrlFromContext(getCurrentTopWebView(), url);
453 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500454 case R.id.view_image_context_menu_id:
455 loadUrlFromContext(getCurrentTopWebView(), src);
456 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500457 case R.id.open_newtab_context_menu_id:
458 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -0800459 final Tab newTab = openTab(parent, url, false);
Leon Scroggins026f2542010-11-22 13:26:12 -0500460 if (newTab != null && newTab != parent) {
461 parent.addChildTab(newTab);
462 }
463 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700464 case R.id.bookmark_context_menu_id:
465 Intent intent = new Intent(mActivity,
466 AddBookmarkPage.class);
467 intent.putExtra(BrowserContract.Bookmarks.URL, url);
468 intent.putExtra(BrowserContract.Bookmarks.TITLE,
469 title);
470 mActivity.startActivity(intent);
471 break;
472 case R.id.share_link_context_menu_id:
473 sharePage(mActivity, title, url, null,
474 null);
475 break;
476 case R.id.copy_link_context_menu_id:
477 copy(url);
478 break;
479 case R.id.save_link_context_menu_id:
480 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500481 DownloadHandler.onDownloadStartNoStream(
482 mActivity, url, null, null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -0700483 break;
484 }
485 break;
486 }
487
488 case LOAD_URL:
489 loadUrlFromContext(getCurrentTopWebView(), (String) msg.obj);
490 break;
491
492 case STOP_LOAD:
493 stopLoading();
494 break;
495
496 case RELEASE_WAKELOCK:
497 if (mWakeLock.isHeld()) {
498 mWakeLock.release();
499 // if we reach here, Browser should be still in the
500 // background loading after WAKELOCK_TIMEOUT (5-min).
501 // To avoid burning the battery, stop loading.
502 mTabControl.stopAllLoading();
503 }
504 break;
505
506 case UPDATE_BOOKMARK_THUMBNAIL:
507 WebView view = (WebView) msg.obj;
508 if (view != null) {
509 updateScreenshot(view);
510 }
511 break;
512 }
513 }
514 };
515
516 }
517
Michael Kolbba99c5d2010-11-29 14:57:41 -0800518 @Override
519 public void shareCurrentPage() {
520 shareCurrentPage(mTabControl.getCurrentTab());
521 }
522
523 private void shareCurrentPage(Tab tab) {
524 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800525 sharePage(mActivity, tab.getTitle(),
526 tab.getUrl(), tab.getFavicon(),
527 createScreenshot(tab.getWebView(),
528 getDesiredThumbnailWidth(mActivity),
529 getDesiredThumbnailHeight(mActivity)));
530 }
531 }
532
Michael Kolb8233fac2010-10-26 16:08:53 -0700533 /**
534 * Share a page, providing the title, url, favicon, and a screenshot. Uses
535 * an {@link Intent} to launch the Activity chooser.
536 * @param c Context used to launch a new Activity.
537 * @param title Title of the page. Stored in the Intent with
538 * {@link Intent#EXTRA_SUBJECT}
539 * @param url URL of the page. Stored in the Intent with
540 * {@link Intent#EXTRA_TEXT}
541 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
542 * with {@link Browser#EXTRA_SHARE_FAVICON}
543 * @param screenshot Bitmap of a screenshot of the page. Stored in the
544 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
545 */
546 static final void sharePage(Context c, String title, String url,
547 Bitmap favicon, Bitmap screenshot) {
548 Intent send = new Intent(Intent.ACTION_SEND);
549 send.setType("text/plain");
550 send.putExtra(Intent.EXTRA_TEXT, url);
551 send.putExtra(Intent.EXTRA_SUBJECT, title);
552 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
553 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
554 try {
555 c.startActivity(Intent.createChooser(send, c.getString(
556 R.string.choosertitle_sharevia)));
557 } catch(android.content.ActivityNotFoundException ex) {
558 // if no app handles it, do nothing
559 }
560 }
561
562 private void copy(CharSequence text) {
563 ClipboardManager cm = (ClipboardManager) mActivity
564 .getSystemService(Context.CLIPBOARD_SERVICE);
565 cm.setText(text);
566 }
567
568 // lifecycle
569
570 protected void onConfgurationChanged(Configuration config) {
571 mConfigChanged = true;
572 if (mPageDialogsHandler != null) {
573 mPageDialogsHandler.onConfigurationChanged(config);
574 }
575 mUi.onConfigurationChanged(config);
576 }
577
578 @Override
579 public void handleNewIntent(Intent intent) {
580 mIntentHandler.onNewIntent(intent);
581 }
582
583 protected void onPause() {
584 if (mActivityPaused) {
585 Log.e(LOGTAG, "BrowserActivity is already paused.");
586 return;
587 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700588 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800589 Tab tab = mTabControl.getCurrentTab();
590 if (tab != null) {
591 tab.pause();
592 if (!pauseWebViewTimers(tab)) {
593 mWakeLock.acquire();
594 mHandler.sendMessageDelayed(mHandler
595 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
596 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700597 }
598 mUi.onPause();
599 mNetworkHandler.onPause();
600
601 WebView.disablePlatformNotifications();
602 }
603
604 void onSaveInstanceState(Bundle outState) {
605 // the default implementation requires each view to have an id. As the
606 // browser handles the state itself and it doesn't use id for the views,
607 // don't call the default implementation. Otherwise it will trigger the
608 // warning like this, "couldn't save which view has focus because the
609 // focused view XXX has no id".
610
611 // Save all the tabs
612 mTabControl.saveState(outState);
613 // Save time so that we know how old incognito tabs (if any) are.
614 outState.putSerializable("lastActiveDate", Calendar.getInstance());
615 }
616
617 void onResume() {
618 if (!mActivityPaused) {
619 Log.e(LOGTAG, "BrowserActivity is already resumed.");
620 return;
621 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700622 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800623 Tab current = mTabControl.getCurrentTab();
624 if (current != null) {
625 current.resume();
626 resumeWebViewTimers(current);
627 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700628 if (mWakeLock.isHeld()) {
629 mHandler.removeMessages(RELEASE_WAKELOCK);
630 mWakeLock.release();
631 }
632 mUi.onResume();
633 mNetworkHandler.onResume();
634 WebView.enablePlatformNotifications();
635 }
636
Michael Kolb70976932010-11-30 11:34:01 -0800637 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800638 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800639 * @param tab guaranteed non-null
640 */
641 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700642 boolean inLoad = tab.inPageLoad();
643 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
644 CookieSyncManager.getInstance().startSync();
645 WebView w = tab.getWebView();
646 if (w != null) {
647 w.resumeTimers();
648 }
649 }
650 }
651
Michael Kolb70976932010-11-30 11:34:01 -0800652 /**
653 * Pause all WebView timers using the WebView of the given tab
654 * @param tab
655 * @return true if the timers are paused or tab is null
656 */
657 private boolean pauseWebViewTimers(Tab tab) {
658 if (tab == null) {
659 return true;
660 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700661 CookieSyncManager.getInstance().stopSync();
662 WebView w = getCurrentWebView();
663 if (w != null) {
664 w.pauseTimers();
665 }
666 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700667 }
Michael Kolb70976932010-11-30 11:34:01 -0800668 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700669 }
670
671 void onDestroy() {
672 if (mUploadHandler != null) {
673 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
674 mUploadHandler = null;
675 }
676 if (mTabControl == null) return;
677 mUi.onDestroy();
678 // Remove the current tab and sub window
679 Tab t = mTabControl.getCurrentTab();
680 if (t != null) {
681 dismissSubWindow(t);
682 removeTab(t);
683 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500684 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700685 // Destroy all the tabs
686 mTabControl.destroy();
687 WebIconDatabase.getInstance().close();
688 // Stop watching the default geolocation permissions
689 mSystemAllowGeolocationOrigins.stop();
690 mSystemAllowGeolocationOrigins = null;
691 }
692
693 protected boolean isActivityPaused() {
694 return mActivityPaused;
695 }
696
697 protected void onLowMemory() {
698 mTabControl.freeMemory();
699 }
700
701 @Override
702 public boolean shouldShowErrorConsole() {
703 return mShouldShowErrorConsole;
704 }
705
706 protected void setShouldShowErrorConsole(boolean show) {
707 if (show == mShouldShowErrorConsole) {
708 // Nothing to do.
709 return;
710 }
711 mShouldShowErrorConsole = show;
712 Tab t = mTabControl.getCurrentTab();
713 if (t == null) {
714 // There is no current tab so we cannot toggle the error console
715 return;
716 }
717 mUi.setShouldShowErrorConsole(t, show);
718 }
719
720 @Override
721 public void stopLoading() {
722 mLoadStopped = true;
723 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700724 WebView w = getCurrentTopWebView();
725 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700726 mUi.onPageStopped(tab);
727 }
728
729 boolean didUserStopLoading() {
730 return mLoadStopped;
731 }
732
733 // WebViewController
734
735 @Override
John Reck324d4402011-01-11 16:56:42 -0800736 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700737
738 // We've started to load a new page. If there was a pending message
739 // to save a screenshot then we will now take the new page and save
740 // an incorrect screenshot. Therefore, remove any pending thumbnail
741 // messages from the queue.
742 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
743 view);
744
745 // reset sync timer to avoid sync starts during loading a page
746 CookieSyncManager.getInstance().resetSync();
747
748 if (!mNetworkHandler.isNetworkUp()) {
749 view.setNetworkAvailable(false);
750 }
751
752 // when BrowserActivity just starts, onPageStarted may be called before
753 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
754 // to start the timer. As we won't switch tabs while an activity is in
755 // pause state, we can ensure calling resume and pause in pair.
756 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800757 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700758 }
759 mLoadStopped = false;
760 if (!mNetworkHandler.isNetworkUp()) {
761 mNetworkHandler.createAndShowNetworkDialog();
762 }
763 endActionMode();
764
John Reck30c714c2010-12-16 17:30:34 -0800765 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700766
John Reck324d4402011-01-11 16:56:42 -0800767 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700768 // update the bookmark database for favicon
769 maybeUpdateFavicon(tab, null, url, favicon);
770
771 Performance.tracePageStart(url);
772
773 // Performance probe
774 if (false) {
775 Performance.onPageStarted();
776 }
777
778 }
779
780 @Override
John Reck324d4402011-01-11 16:56:42 -0800781 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800782 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800783 if (!tab.isPrivateBrowsingEnabled()
784 && !TextUtils.isEmpty(tab.getUrl())) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700785 if (tab.inForeground() && !didUserStopLoading()
786 || !tab.inForeground()) {
787 // Only update the bookmark screenshot if the user did not
788 // cancel the load early.
789 mHandler.sendMessageDelayed(mHandler.obtainMessage(
790 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab.getWebView()),
791 500);
792 }
793 }
794 // pause the WebView timer and release the wake lock if it is finished
795 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800796 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700797 if (mWakeLock.isHeld()) {
798 mHandler.removeMessages(RELEASE_WAKELOCK);
799 mWakeLock.release();
800 }
801 }
802 // Performance probe
803 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800804 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700805 }
806
807 Performance.tracePageFinished();
808 }
809
810 @Override
John Reck30c714c2010-12-16 17:30:34 -0800811 public void onProgressChanged(Tab tab) {
812 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700813
814 if (newProgress == 100) {
815 CookieSyncManager.getInstance().sync();
816 // onProgressChanged() may continue to be called after the main
817 // frame has finished loading, as any remaining sub frames continue
818 // to load. We'll only get called once though with newProgress as
819 // 100 when everything is loaded. (onPageFinished is called once
820 // when the main frame completes loading regardless of the state of
821 // any sub frames so calls to onProgressChanges may continue after
822 // onPageFinished has executed)
823 if (mInLoad) {
824 mInLoad = false;
825 updateInLoadMenuItems(mCachedMenu);
826 }
827 } else {
828 if (!mInLoad) {
829 // onPageFinished may have already been called but a subframe is
830 // still loading and updating the progress. Reset mInLoad and
831 // update the menu items.
832 mInLoad = true;
833 updateInLoadMenuItems(mCachedMenu);
834 }
835 }
John Reck30c714c2010-12-16 17:30:34 -0800836 mUi.onProgressChanged(tab);
837 }
838
839 @Override
840 public void onUpdatedLockIcon(Tab tab) {
841 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700842 }
843
844 @Override
845 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800846 mUi.onTabDataChanged(tab);
847 final String pageUrl = tab.getUrl();
John Reck324d4402011-01-11 16:56:42 -0800848 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700849 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
850 return;
851 }
852 // Update the title in the history database if not in private browsing mode
853 if (!tab.isPrivateBrowsingEnabled()) {
John Reck0ebd3ac2010-12-09 11:14:04 -0800854 mDataController.updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700855 }
856 }
857
858 @Override
859 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800860 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700861 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
862 }
863
864 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800865 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
866 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700867 }
868
869 @Override
870 public boolean shouldOverrideKeyEvent(KeyEvent event) {
871 if (mMenuIsDown) {
872 // only check shortcut key when MENU is held
873 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
874 event);
875 } else {
876 return false;
877 }
878 }
879
880 @Override
881 public void onUnhandledKeyEvent(KeyEvent event) {
882 if (!isActivityPaused()) {
883 if (event.getAction() == KeyEvent.ACTION_DOWN) {
884 mActivity.onKeyDown(event.getKeyCode(), event);
885 } else {
886 mActivity.onKeyUp(event.getKeyCode(), event);
887 }
888 }
889 }
890
891 @Override
John Reck324d4402011-01-11 16:56:42 -0800892 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700893 // Don't save anything in private browsing mode
894 if (tab.isPrivateBrowsingEnabled()) return;
John Reck324d4402011-01-11 16:56:42 -0800895 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700896
John Reck324d4402011-01-11 16:56:42 -0800897 if (TextUtils.isEmpty(url)
898 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700899 return;
900 }
John Reck0ebd3ac2010-12-09 11:14:04 -0800901 mDataController.updateVisitedHistory(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700902 WebIconDatabase.getInstance().retainIconForPageUrl(url);
903 }
904
905 @Override
906 public void getVisitedHistory(final ValueCallback<String[]> callback) {
907 AsyncTask<Void, Void, String[]> task =
908 new AsyncTask<Void, Void, String[]>() {
909 @Override
910 public String[] doInBackground(Void... unused) {
911 return Browser.getVisitedHistory(mActivity.getContentResolver());
912 }
913 @Override
914 public void onPostExecute(String[] result) {
915 callback.onReceiveValue(result);
916 }
917 };
918 task.execute();
919 }
920
921 @Override
922 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
923 final HttpAuthHandler handler, final String host,
924 final String realm) {
925 String username = null;
926 String password = null;
927
928 boolean reuseHttpAuthUsernamePassword
929 = handler.useHttpAuthUsernamePassword();
930
931 if (reuseHttpAuthUsernamePassword && view != null) {
932 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
933 if (credentials != null && credentials.length == 2) {
934 username = credentials[0];
935 password = credentials[1];
936 }
937 }
938
939 if (username != null && password != null) {
940 handler.proceed(username, password);
941 } else {
942 if (tab.inForeground()) {
943 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
944 } else {
945 handler.cancel();
946 }
947 }
948 }
949
950 @Override
951 public void onDownloadStart(Tab tab, String url, String userAgent,
952 String contentDisposition, String mimetype, long contentLength) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500953 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
954 contentDisposition, mimetype);
Michael Kolb8233fac2010-10-26 16:08:53 -0700955 if (tab.getWebView().copyBackForwardList().getSize() == 0) {
956 // This Tab was opened for the sole purpose of downloading a
957 // file. Remove it.
958 if (tab == mTabControl.getCurrentTab()) {
959 // In this case, the Tab is still on top.
960 goBackOnePageOrQuit();
961 } else {
962 // In this case, it is not.
963 closeTab(tab);
964 }
965 }
966 }
967
968 @Override
969 public Bitmap getDefaultVideoPoster() {
970 return mUi.getDefaultVideoPoster();
971 }
972
973 @Override
974 public View getVideoLoadingProgressView() {
975 return mUi.getVideoLoadingProgressView();
976 }
977
978 @Override
979 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
980 SslError error) {
981 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
982 }
983
984 // helper method
985
986 /*
987 * Update the favorites icon if the private browsing isn't enabled and the
988 * icon is valid.
989 */
990 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
991 final String url, Bitmap favicon) {
992 if (favicon == null) {
993 return;
994 }
995 if (!tab.isPrivateBrowsingEnabled()) {
996 Bookmarks.updateFavicon(mActivity
997 .getContentResolver(), originalUrl, url, favicon);
998 }
999 }
1000
Leon Scroggins4cd97792010-12-03 15:31:56 -05001001 @Override
1002 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001003 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001004 mUi.bookmarkedStatusHasChanged(tab);
1005 }
1006
Michael Kolb8233fac2010-10-26 16:08:53 -07001007 // end WebViewController
1008
1009 protected void pageUp() {
1010 getCurrentTopWebView().pageUp(false);
1011 }
1012
1013 protected void pageDown() {
1014 getCurrentTopWebView().pageDown(false);
1015 }
1016
1017 // callback from phone title bar
1018 public void editUrl() {
1019 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
1020 String url = (getCurrentTopWebView() == null) ? null : getCurrentTopWebView().getUrl();
1021 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1022 null, false);
1023 }
1024
Michael Kolbcfa3af52010-12-14 10:36:11 -08001025 public void startVoiceSearch() {
1026 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1027 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1028 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1029 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1030 mActivity.getComponentName().flattenToString());
1031 intent.putExtra(SEND_APP_ID_EXTRA, false);
1032 mActivity.startActivity(intent);
1033 }
1034
Michael Kolb8233fac2010-10-26 16:08:53 -07001035 public void activateVoiceSearchMode(String title) {
1036 mUi.showVoiceTitleBar(title);
1037 }
1038
1039 public void revertVoiceSearchMode(Tab tab) {
1040 mUi.revertVoiceTitleBar(tab);
1041 }
1042
1043 public void showCustomView(Tab tab, View view,
1044 WebChromeClient.CustomViewCallback callback) {
1045 if (tab.inForeground()) {
1046 if (mUi.isCustomViewShowing()) {
1047 callback.onCustomViewHidden();
1048 return;
1049 }
1050 mUi.showCustomView(view, callback);
1051 // Save the menu state and set it to empty while the custom
1052 // view is showing.
1053 mOldMenuState = mMenuState;
1054 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001055 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001056 }
1057 }
1058
1059 @Override
1060 public void hideCustomView() {
1061 if (mUi.isCustomViewShowing()) {
1062 mUi.onHideCustomView();
1063 // Reset the old menu state.
1064 mMenuState = mOldMenuState;
1065 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001066 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001067 }
1068 }
1069
1070 protected void onActivityResult(int requestCode, int resultCode,
1071 Intent intent) {
1072 if (getCurrentTopWebView() == null) return;
1073 switch (requestCode) {
1074 case PREFERENCES_PAGE:
1075 if (resultCode == Activity.RESULT_OK && intent != null) {
1076 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
1077 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
1078 mTabControl.removeParentChildRelationShips();
1079 }
1080 }
1081 break;
1082 case FILE_SELECTED:
1083 // Choose a file from the file picker.
1084 if (null == mUploadHandler) break;
1085 mUploadHandler.onResult(resultCode, intent);
1086 mUploadHandler = null;
1087 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001088 case AUTOFILL_SETUP:
1089 // Determine whether a profile was actually set up or not
1090 // and if so, send the message back to the WebTextView to
1091 // fill the form with the new profile.
1092 if (getSettings().getAutoFillProfile() != null) {
1093 mAutoFillSetupMessage.sendToTarget();
1094 mAutoFillSetupMessage = null;
1095 }
1096 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001097 default:
1098 break;
1099 }
1100 getCurrentTopWebView().requestFocus();
1101 }
1102
1103 /**
1104 * Open the Go page.
1105 * @param startWithHistory If true, open starting on the history tab.
1106 * Otherwise, start with the bookmarks tab.
1107 */
1108 @Override
1109 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1110 if (mTabControl.getCurrentWebView() == null) {
1111 return;
1112 }
1113 Bundle extras = new Bundle();
1114 // Disable opening in a new window if we have maxed out the windows
1115 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1116 !mTabControl.canCreateNewTab());
1117 mUi.showComboView(startWithHistory, extras);
1118 }
1119
1120 // combo view callbacks
1121
1122 /**
1123 * callback from ComboPage when clear history is requested
1124 */
1125 public void onRemoveParentChildRelationships() {
1126 mTabControl.removeParentChildRelationShips();
1127 }
1128
1129 /**
1130 * callback from ComboPage when bookmark/history selection
1131 */
1132 @Override
1133 public void onUrlSelected(String url, boolean newTab) {
1134 removeComboView();
1135 if (!TextUtils.isEmpty(url)) {
1136 if (newTab) {
Michael Kolb18eb3772010-12-10 14:29:51 -08001137 openTab(mTabControl.getCurrentTab(), url, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001138 } else {
1139 final Tab currentTab = mTabControl.getCurrentTab();
1140 dismissSubWindow(currentTab);
1141 loadUrl(getCurrentTopWebView(), url);
1142 }
1143 }
1144 }
1145
1146 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07001147 * dismiss the ComboPage
1148 */
1149 @Override
1150 public void removeComboView() {
1151 mUi.hideComboView();
1152 }
1153
1154 // active tabs page handling
1155
1156 protected void showActiveTabsPage() {
1157 mMenuState = EMPTY_MENU;
1158 mUi.showActiveTabsPage();
1159 }
1160
1161 /**
1162 * Remove the active tabs page.
1163 * @param needToAttach If true, the active tabs page did not attach a tab
1164 * to the content view, so we need to do that here.
1165 */
1166 @Override
1167 public void removeActiveTabsPage(boolean needToAttach) {
1168 mMenuState = R.id.MAIN_MENU;
1169 mUi.removeActiveTabsPage();
1170 if (needToAttach) {
1171 setActiveTab(mTabControl.getCurrentTab());
1172 }
1173 getCurrentTopWebView().requestFocus();
1174 }
1175
1176 // key handling
1177 protected void onBackKey() {
1178 if (!mUi.onBackKey()) {
1179 WebView subwindow = mTabControl.getCurrentSubWindow();
1180 if (subwindow != null) {
1181 if (subwindow.canGoBack()) {
1182 subwindow.goBack();
1183 } else {
1184 dismissSubWindow(mTabControl.getCurrentTab());
1185 }
1186 } else {
1187 goBackOnePageOrQuit();
1188 }
1189 }
1190 }
1191
1192 // menu handling and state
1193 // TODO: maybe put into separate handler
1194
1195 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckd73c5a22010-12-22 10:22:50 -08001196 if (mMenuState == EMPTY_MENU) {
1197 return false;
1198 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001199 MenuInflater inflater = mActivity.getMenuInflater();
1200 inflater.inflate(R.menu.browser, menu);
1201 updateInLoadMenuItems(menu);
1202 // hold on to the menu reference here; it is used by the page callbacks
1203 // to update the menu based on loading state
1204 mCachedMenu = menu;
1205 return true;
1206 }
1207
1208 protected void onCreateContextMenu(ContextMenu menu, View v,
1209 ContextMenuInfo menuInfo) {
1210 if (v instanceof TitleBarBase) {
1211 return;
1212 }
1213 if (!(v instanceof WebView)) {
1214 return;
1215 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001216 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001217 WebView.HitTestResult result = webview.getHitTestResult();
1218 if (result == null) {
1219 return;
1220 }
1221
1222 int type = result.getType();
1223 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1224 Log.w(LOGTAG,
1225 "We should not show context menu when nothing is touched");
1226 return;
1227 }
1228 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1229 // let TextView handles context menu
1230 return;
1231 }
1232
1233 // Note, http://b/issue?id=1106666 is requesting that
1234 // an inflated menu can be used again. This is not available
1235 // yet, so inflate each time (yuk!)
1236 MenuInflater inflater = mActivity.getMenuInflater();
1237 inflater.inflate(R.menu.browsercontext, menu);
1238
1239 // Show the correct menu group
1240 final String extra = result.getExtra();
1241 menu.setGroupVisible(R.id.PHONE_MENU,
1242 type == WebView.HitTestResult.PHONE_TYPE);
1243 menu.setGroupVisible(R.id.EMAIL_MENU,
1244 type == WebView.HitTestResult.EMAIL_TYPE);
1245 menu.setGroupVisible(R.id.GEO_MENU,
1246 type == WebView.HitTestResult.GEO_TYPE);
1247 menu.setGroupVisible(R.id.IMAGE_MENU,
1248 type == WebView.HitTestResult.IMAGE_TYPE
1249 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1250 menu.setGroupVisible(R.id.ANCHOR_MENU,
1251 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1252 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001253 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1254 || type == WebView.HitTestResult.PHONE_TYPE
1255 || type == WebView.HitTestResult.EMAIL_TYPE
1256 || type == WebView.HitTestResult.GEO_TYPE;
1257 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1258 if (hitText) {
1259 menu.findItem(R.id.select_text_menu_id)
1260 .setOnMenuItemClickListener(new SelectText(webview));
1261 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001262 // Setup custom handling depending on the type
1263 switch (type) {
1264 case WebView.HitTestResult.PHONE_TYPE:
1265 menu.setHeaderTitle(Uri.decode(extra));
1266 menu.findItem(R.id.dial_context_menu_id).setIntent(
1267 new Intent(Intent.ACTION_VIEW, Uri
1268 .parse(WebView.SCHEME_TEL + extra)));
1269 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1270 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1271 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1272 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1273 addIntent);
1274 menu.findItem(R.id.copy_phone_context_menu_id)
1275 .setOnMenuItemClickListener(
1276 new Copy(extra));
1277 break;
1278
1279 case WebView.HitTestResult.EMAIL_TYPE:
1280 menu.setHeaderTitle(extra);
1281 menu.findItem(R.id.email_context_menu_id).setIntent(
1282 new Intent(Intent.ACTION_VIEW, Uri
1283 .parse(WebView.SCHEME_MAILTO + extra)));
1284 menu.findItem(R.id.copy_mail_context_menu_id)
1285 .setOnMenuItemClickListener(
1286 new Copy(extra));
1287 break;
1288
1289 case WebView.HitTestResult.GEO_TYPE:
1290 menu.setHeaderTitle(extra);
1291 menu.findItem(R.id.map_context_menu_id).setIntent(
1292 new Intent(Intent.ACTION_VIEW, Uri
1293 .parse(WebView.SCHEME_GEO
1294 + URLEncoder.encode(extra))));
1295 menu.findItem(R.id.copy_geo_context_menu_id)
1296 .setOnMenuItemClickListener(
1297 new Copy(extra));
1298 break;
1299
1300 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1301 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1302 TextView titleView = (TextView) LayoutInflater.from(mActivity)
1303 .inflate(android.R.layout.browser_link_context_header,
1304 null);
1305 titleView.setText(extra);
1306 menu.setHeaderView(titleView);
1307 // decide whether to show the open link in new tab option
1308 boolean showNewTab = mTabControl.canCreateNewTab();
1309 MenuItem newTabItem
1310 = menu.findItem(R.id.open_newtab_context_menu_id);
1311 newTabItem.setVisible(showNewTab);
1312 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001313 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1314 newTabItem.setOnMenuItemClickListener(
1315 new MenuItem.OnMenuItemClickListener() {
1316 @Override
1317 public boolean onMenuItemClick(MenuItem item) {
1318 final HashMap<String, WebView> hrefMap =
1319 new HashMap<String, WebView>();
1320 hrefMap.put("webview", webview);
1321 final Message msg = mHandler.obtainMessage(
1322 FOCUS_NODE_HREF,
1323 R.id.open_newtab_context_menu_id,
1324 0, hrefMap);
1325 webview.requestFocusNodeHref(msg);
1326 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001327 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001328 });
1329 } else {
1330 newTabItem.setOnMenuItemClickListener(
1331 new MenuItem.OnMenuItemClickListener() {
1332 @Override
1333 public boolean onMenuItemClick(MenuItem item) {
1334 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -08001335 final Tab newTab = openTab(parent,
1336 extra, false);
Leon Scroggins026f2542010-11-22 13:26:12 -05001337 if (newTab != parent) {
1338 parent.addChildTab(newTab);
1339 }
1340 return true;
1341 }
1342 });
1343 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001344 }
1345 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1346 Bookmarks.urlHasAcceptableScheme(extra));
1347 PackageManager pm = mActivity.getPackageManager();
1348 Intent send = new Intent(Intent.ACTION_SEND);
1349 send.setType("text/plain");
1350 ResolveInfo ri = pm.resolveActivity(send,
1351 PackageManager.MATCH_DEFAULT_ONLY);
1352 menu.findItem(R.id.share_link_context_menu_id)
1353 .setVisible(ri != null);
1354 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1355 break;
1356 }
1357 // otherwise fall through to handle image part
1358 case WebView.HitTestResult.IMAGE_TYPE:
1359 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1360 menu.setHeaderTitle(extra);
1361 }
1362 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1363 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1364 menu.findItem(R.id.download_context_menu_id).
Leon Scroggins63c02662010-11-18 15:16:27 -05001365 setOnMenuItemClickListener(new Download(mActivity, extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001366 menu.findItem(R.id.set_wallpaper_context_menu_id).
1367 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1368 extra));
1369 break;
1370
1371 default:
1372 Log.w(LOGTAG, "We should not get here.");
1373 break;
1374 }
1375 //update the ui
1376 mUi.onContextMenuCreated(menu);
1377 }
1378
1379 /**
1380 * As the menu can be open when loading state changes
1381 * we must manually update the state of the stop/reload menu
1382 * item
1383 */
1384 private void updateInLoadMenuItems(Menu menu) {
1385 if (menu == null) {
1386 return;
1387 }
1388 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1389 MenuItem src = mInLoad ?
1390 menu.findItem(R.id.stop_menu_id):
1391 menu.findItem(R.id.reload_menu_id);
1392 if (src != null) {
1393 dest.setIcon(src.getIcon());
1394 dest.setTitle(src.getTitle());
1395 }
1396 }
1397
1398 boolean prepareOptionsMenu(Menu menu) {
1399 // This happens when the user begins to hold down the menu key, so
1400 // allow them to chord to get a shortcut.
1401 mCanChord = true;
1402 // Note: setVisible will decide whether an item is visible; while
1403 // setEnabled() will decide whether an item is enabled, which also means
1404 // whether the matching shortcut key will function.
1405 switch (mMenuState) {
1406 case EMPTY_MENU:
1407 if (mCurrentMenuState != mMenuState) {
1408 menu.setGroupVisible(R.id.MAIN_MENU, false);
1409 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1410 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1411 }
1412 break;
1413 default:
1414 if (mCurrentMenuState != mMenuState) {
1415 menu.setGroupVisible(R.id.MAIN_MENU, true);
1416 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1417 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1418 }
1419 final WebView w = getCurrentTopWebView();
1420 boolean canGoBack = false;
1421 boolean canGoForward = false;
1422 boolean isHome = false;
1423 if (w != null) {
1424 canGoBack = w.canGoBack();
1425 canGoForward = w.canGoForward();
1426 isHome = mSettings.getHomePage().equals(w.getUrl());
1427 }
1428 final MenuItem back = menu.findItem(R.id.back_menu_id);
1429 back.setEnabled(canGoBack);
1430
1431 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1432 home.setEnabled(!isHome);
1433
1434 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1435 forward.setEnabled(canGoForward);
1436
1437 // decide whether to show the share link option
1438 PackageManager pm = mActivity.getPackageManager();
1439 Intent send = new Intent(Intent.ACTION_SEND);
1440 send.setType("text/plain");
1441 ResolveInfo ri = pm.resolveActivity(send,
1442 PackageManager.MATCH_DEFAULT_ONLY);
1443 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1444
1445 boolean isNavDump = mSettings.isNavDump();
1446 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1447 nav.setVisible(isNavDump);
1448 nav.setEnabled(isNavDump);
1449
1450 boolean showDebugSettings = mSettings.showDebugSettings();
1451 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1452 counter.setVisible(showDebugSettings);
1453 counter.setEnabled(showDebugSettings);
1454
1455 // allow the ui to adjust state based settings
1456 mUi.onPrepareOptionsMenu(menu);
1457
1458 break;
1459 }
1460 mCurrentMenuState = mMenuState;
1461 return true;
1462 }
1463
1464 public boolean onOptionsItemSelected(MenuItem item) {
1465 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1466 // menu remains active, so ensure comboview is dismissed
1467 // if main menu option is selected
1468 removeComboView();
1469 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001470 if (!mCanChord) {
1471 // The user has already fired a shortcut with this hold down of the
1472 // menu key.
1473 return false;
1474 }
1475 if (null == getCurrentTopWebView()) {
1476 return false;
1477 }
1478 if (mMenuIsDown) {
1479 // The shortcut action consumes the MENU. Even if it is still down,
1480 // it won't trigger the next shortcut action. In the case of the
1481 // shortcut action triggering a new activity, like Bookmarks, we
1482 // won't get onKeyUp for MENU. So it is important to reset it here.
1483 mMenuIsDown = false;
1484 }
1485 switch (item.getItemId()) {
1486 // -- Main menu
1487 case R.id.new_tab_menu_id:
1488 openTabToHomePage();
1489 break;
1490
1491 case R.id.incognito_menu_id:
1492 openIncognitoTab();
1493 break;
1494
1495 case R.id.goto_menu_id:
1496 editUrl();
1497 break;
1498
1499 case R.id.bookmarks_menu_id:
1500 bookmarksOrHistoryPicker(false);
1501 break;
1502
1503 case R.id.active_tabs_menu_id:
1504 showActiveTabsPage();
1505 break;
1506
1507 case R.id.add_bookmark_menu_id:
1508 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
1509 break;
1510
1511 case R.id.stop_reload_menu_id:
1512 if (mInLoad) {
1513 stopLoading();
1514 } else {
1515 getCurrentTopWebView().reload();
1516 }
1517 break;
1518
1519 case R.id.back_menu_id:
1520 getCurrentTopWebView().goBack();
1521 break;
1522
1523 case R.id.forward_menu_id:
1524 getCurrentTopWebView().goForward();
1525 break;
1526
1527 case R.id.close_menu_id:
1528 // Close the subwindow if it exists.
1529 if (mTabControl.getCurrentSubWindow() != null) {
1530 dismissSubWindow(mTabControl.getCurrentTab());
1531 break;
1532 }
1533 closeCurrentTab();
1534 break;
1535
1536 case R.id.homepage_menu_id:
1537 Tab current = mTabControl.getCurrentTab();
1538 if (current != null) {
1539 dismissSubWindow(current);
1540 loadUrl(current.getWebView(), mSettings.getHomePage());
1541 }
1542 break;
1543
1544 case R.id.preferences_menu_id:
1545 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1546 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1547 getCurrentTopWebView().getUrl());
1548 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1549 break;
1550
1551 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001552 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001553 break;
1554
1555 case R.id.page_info_menu_id:
1556 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1557 false);
1558 break;
1559
1560 case R.id.classic_history_menu_id:
1561 bookmarksOrHistoryPicker(true);
1562 break;
1563
1564 case R.id.title_bar_share_page_url:
1565 case R.id.share_page_menu_id:
1566 Tab currentTab = mTabControl.getCurrentTab();
1567 if (null == currentTab) {
1568 mCanChord = false;
1569 return false;
1570 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001571 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001572 break;
1573
1574 case R.id.dump_nav_menu_id:
1575 getCurrentTopWebView().debugDump();
1576 break;
1577
1578 case R.id.dump_counters_menu_id:
1579 getCurrentTopWebView().dumpV8Counters();
1580 break;
1581
1582 case R.id.zoom_in_menu_id:
1583 getCurrentTopWebView().zoomIn();
1584 break;
1585
1586 case R.id.zoom_out_menu_id:
1587 getCurrentTopWebView().zoomOut();
1588 break;
1589
1590 case R.id.view_downloads_menu_id:
1591 viewDownloads();
1592 break;
1593
1594 case R.id.window_one_menu_id:
1595 case R.id.window_two_menu_id:
1596 case R.id.window_three_menu_id:
1597 case R.id.window_four_menu_id:
1598 case R.id.window_five_menu_id:
1599 case R.id.window_six_menu_id:
1600 case R.id.window_seven_menu_id:
1601 case R.id.window_eight_menu_id:
1602 {
1603 int menuid = item.getItemId();
1604 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1605 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1606 Tab desiredTab = mTabControl.getTab(id);
1607 if (desiredTab != null &&
1608 desiredTab != mTabControl.getCurrentTab()) {
1609 switchToTab(id);
1610 }
1611 break;
1612 }
1613 }
1614 }
1615 break;
1616
1617 default:
1618 return false;
1619 }
1620 mCanChord = false;
1621 return true;
1622 }
1623
1624 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001625 // Let the History and Bookmark fragments handle menus they created.
1626 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1627 return false;
1628 }
1629
Michael Kolb8233fac2010-10-26 16:08:53 -07001630 // chording is not an issue with context menus, but we use the same
1631 // options selector, so set mCanChord to true so we can access them.
1632 mCanChord = true;
1633 int id = item.getItemId();
1634 boolean result = true;
1635 switch (id) {
1636 // For the context menu from the title bar
1637 case R.id.title_bar_copy_page_url:
1638 Tab currentTab = mTabControl.getCurrentTab();
1639 if (null == currentTab) {
1640 result = false;
1641 break;
1642 }
1643 WebView mainView = currentTab.getWebView();
1644 if (null == mainView) {
1645 result = false;
1646 break;
1647 }
1648 copy(mainView.getUrl());
1649 break;
1650 // -- Browser context menu
1651 case R.id.open_context_menu_id:
1652 case R.id.bookmark_context_menu_id:
1653 case R.id.save_link_context_menu_id:
1654 case R.id.share_link_context_menu_id:
1655 case R.id.copy_link_context_menu_id:
1656 final WebView webView = getCurrentTopWebView();
1657 if (null == webView) {
1658 result = false;
1659 break;
1660 }
1661 final HashMap<String, WebView> hrefMap =
1662 new HashMap<String, WebView>();
1663 hrefMap.put("webview", webView);
1664 final Message msg = mHandler.obtainMessage(
1665 FOCUS_NODE_HREF, id, 0, hrefMap);
1666 webView.requestFocusNodeHref(msg);
1667 break;
1668
1669 default:
1670 // For other context menus
1671 result = onOptionsItemSelected(item);
1672 }
1673 mCanChord = false;
1674 return result;
1675 }
1676
1677 /**
1678 * support programmatically opening the context menu
1679 */
1680 public void openContextMenu(View view) {
1681 mActivity.openContextMenu(view);
1682 }
1683
1684 /**
1685 * programmatically open the options menu
1686 */
1687 public void openOptionsMenu() {
1688 mActivity.openOptionsMenu();
1689 }
1690
1691 public boolean onMenuOpened(int featureId, Menu menu) {
1692 if (mOptionsMenuOpen) {
1693 if (mConfigChanged) {
1694 // We do not need to make any changes to the state of the
1695 // title bar, since the only thing that happened was a
1696 // change in orientation
1697 mConfigChanged = false;
1698 } else {
1699 if (!mExtendedMenuOpen) {
1700 mExtendedMenuOpen = true;
1701 mUi.onExtendedMenuOpened();
1702 } else {
1703 // Switching the menu back to icon view, so show the
1704 // title bar once again.
1705 mExtendedMenuOpen = false;
1706 mUi.onExtendedMenuClosed(mInLoad);
1707 mUi.onOptionsMenuOpened();
1708 }
1709 }
1710 } else {
1711 // The options menu is closed, so open it, and show the title
1712 mOptionsMenuOpen = true;
1713 mConfigChanged = false;
1714 mExtendedMenuOpen = false;
1715 mUi.onOptionsMenuOpened();
1716 }
1717 return true;
1718 }
1719
1720 public void onOptionsMenuClosed(Menu menu) {
1721 mOptionsMenuOpen = false;
1722 mUi.onOptionsMenuClosed(mInLoad);
1723 }
1724
1725 public void onContextMenuClosed(Menu menu) {
1726 mUi.onContextMenuClosed(menu, mInLoad);
1727 }
1728
1729 // Helper method for getting the top window.
1730 @Override
1731 public WebView getCurrentTopWebView() {
1732 return mTabControl.getCurrentTopWebView();
1733 }
1734
1735 @Override
1736 public WebView getCurrentWebView() {
1737 return mTabControl.getCurrentWebView();
1738 }
1739
1740 /*
1741 * This method is called as a result of the user selecting the options
1742 * menu to see the download window. It shows the download window on top of
1743 * the current window.
1744 */
1745 void viewDownloads() {
1746 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1747 mActivity.startActivity(intent);
1748 }
1749
1750 // action mode
1751
1752 void onActionModeStarted(ActionMode mode) {
1753 mUi.onActionModeStarted(mode);
1754 mActionMode = mode;
1755 }
1756
1757 /*
1758 * True if a custom ActionMode (i.e. find or select) is in use.
1759 */
1760 @Override
1761 public boolean isInCustomActionMode() {
1762 return mActionMode != null;
1763 }
1764
1765 /*
1766 * End the current ActionMode.
1767 */
1768 @Override
1769 public void endActionMode() {
1770 if (mActionMode != null) {
1771 mActionMode.finish();
1772 }
1773 }
1774
1775 /*
1776 * Called by find and select when they are finished. Replace title bars
1777 * as necessary.
1778 */
1779 public void onActionModeFinished(ActionMode mode) {
1780 if (!isInCustomActionMode()) return;
1781 mUi.onActionModeFinished(mInLoad);
1782 mActionMode = null;
1783 }
1784
1785 boolean isInLoad() {
1786 return mInLoad;
1787 }
1788
1789 // bookmark handling
1790
1791 /**
1792 * add the current page as a bookmark to the given folder id
1793 * @param folderId use -1 for the default folder
1794 */
1795 @Override
1796 public void bookmarkCurrentPage(long folderId) {
1797 Intent i = new Intent(mActivity,
1798 AddBookmarkPage.class);
1799 WebView w = getCurrentTopWebView();
1800 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1801 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1802 String touchIconUrl = w.getTouchIconUrl();
1803 if (touchIconUrl != null) {
1804 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1805 WebSettings settings = w.getSettings();
1806 if (settings != null) {
1807 i.putExtra(AddBookmarkPage.USER_AGENT,
1808 settings.getUserAgentString());
1809 }
1810 }
1811 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1812 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1813 getDesiredThumbnailHeight(mActivity)));
1814 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1815 i.putExtra(BrowserContract.Bookmarks.PARENT,
1816 folderId);
1817 // Put the dialog at the upper right of the screen, covering the
1818 // star on the title bar.
1819 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1820 mActivity.startActivity(i);
1821 }
1822
1823 // file chooser
1824 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1825 mUploadHandler = new UploadHandler(this);
1826 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1827 }
1828
1829 // thumbnails
1830
1831 /**
1832 * Return the desired width for thumbnail screenshots, which are stored in
1833 * the database, and used on the bookmarks screen.
1834 * @param context Context for finding out the density of the screen.
1835 * @return desired width for thumbnail screenshot.
1836 */
1837 static int getDesiredThumbnailWidth(Context context) {
1838 return context.getResources().getDimensionPixelOffset(
1839 R.dimen.bookmarkThumbnailWidth);
1840 }
1841
1842 /**
1843 * Return the desired height for thumbnail screenshots, which are stored in
1844 * the database, and used on the bookmarks screen.
1845 * @param context Context for finding out the density of the screen.
1846 * @return desired height for thumbnail screenshot.
1847 */
1848 static int getDesiredThumbnailHeight(Context context) {
1849 return context.getResources().getDimensionPixelOffset(
1850 R.dimen.bookmarkThumbnailHeight);
1851 }
1852
1853 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001854 // We render to a bitmap 2x the desired size so that we can then
1855 // re-scale it with filtering since canvas.scale doesn't filter
1856 // This helps reduce aliasing at the cost of being slightly blurry
1857 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001858 Picture thumbnail = view.capturePicture();
1859 if (thumbnail == null) {
1860 return null;
1861 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001862 width *= filter_scale;
1863 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001864 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1865 Canvas canvas = new Canvas(bm);
1866 // May need to tweak these values to determine what is the
1867 // best scale factor
1868 int thumbnailWidth = thumbnail.getWidth();
1869 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001870 float scaleFactor = 1.0f;
Michael Kolb8233fac2010-10-26 16:08:53 -07001871 if (thumbnailWidth > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001872 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001873 } else {
1874 return null;
1875 }
John Reckfe49ab42010-11-16 17:09:37 -08001876
Michael Kolb8233fac2010-10-26 16:08:53 -07001877 if (view.getWidth() > view.getHeight() &&
1878 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
1879 // If the device is in landscape and the page is shorter
John Reckfe49ab42010-11-16 17:09:37 -08001880 // than the height of the view, center the thumnail and crop the sides
1881 scaleFactor = (float) height / (float)thumbnailHeight;
1882 float wx = (thumbnailWidth * scaleFactor) - width;
1883 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001884 }
1885
John Reckfe49ab42010-11-16 17:09:37 -08001886 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001887
1888 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001889 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
1890 height / filter_scale, true);
1891 bm.recycle();
1892 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001893 }
1894
1895 private void updateScreenshot(WebView view) {
1896 // If this is a bookmarked site, add a screenshot to the database.
1897 // FIXME: When should we update? Every time?
1898 // FIXME: Would like to make sure there is actually something to
1899 // draw, but the API for that (WebViewCore.pictureReady()) is not
1900 // currently accessible here.
1901
1902 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1903 getDesiredThumbnailHeight(mActivity));
1904 if (bm == null) {
1905 return;
1906 }
1907
1908 final ContentResolver cr = mActivity.getContentResolver();
1909 final String url = view.getUrl();
1910 final String originalUrl = view.getOriginalUrl();
1911
John Recka00cbbd2010-12-16 12:38:19 -08001912 // Only update thumbnails for web urls (http(s)://), not for
1913 // about:, javascript:, data:, etc...
John Reck9d038482011-01-04 17:02:09 -08001914 if (url != null && Patterns.WEB_URL.matcher(url).matches()) {
John Recka00cbbd2010-12-16 12:38:19 -08001915 new AsyncTask<Void, Void, Void>() {
1916 @Override
1917 protected Void doInBackground(Void... unused) {
1918 Cursor cursor = null;
1919 try {
1920 // TODO: Clean this up
1921 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
1922 if (cursor != null && cursor.moveToFirst()) {
1923 final ByteArrayOutputStream os =
1924 new ByteArrayOutputStream();
1925 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07001926
John Recka00cbbd2010-12-16 12:38:19 -08001927 ContentValues values = new ContentValues();
1928 values.put(Images.THUMBNAIL, os.toByteArray());
1929 values.put(Images.URL, cursor.getString(0));
Michael Kolb8233fac2010-10-26 16:08:53 -07001930
John Recka00cbbd2010-12-16 12:38:19 -08001931 do {
1932 cr.update(Images.CONTENT_URI, values, null, null);
1933 } while (cursor.moveToNext());
1934 }
1935 } catch (IllegalStateException e) {
1936 // Ignore
1937 } finally {
1938 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07001939 }
John Recka00cbbd2010-12-16 12:38:19 -08001940 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07001941 }
John Recka00cbbd2010-12-16 12:38:19 -08001942 }.execute();
1943 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001944 }
1945
1946 private class Copy implements OnMenuItemClickListener {
1947 private CharSequence mText;
1948
1949 public boolean onMenuItemClick(MenuItem item) {
1950 copy(mText);
1951 return true;
1952 }
1953
1954 public Copy(CharSequence toCopy) {
1955 mText = toCopy;
1956 }
1957 }
1958
Leon Scroggins63c02662010-11-18 15:16:27 -05001959 private static class Download implements OnMenuItemClickListener {
1960 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001961 private String mText;
1962
1963 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05001964 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
1965 null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001966 return true;
1967 }
1968
Leon Scroggins63c02662010-11-18 15:16:27 -05001969 public Download(Activity activity, String toDownload) {
1970 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001971 mText = toDownload;
1972 }
1973 }
1974
Cary Clark8974d282010-11-22 10:46:05 -05001975 private static class SelectText implements OnMenuItemClickListener {
1976 private WebView mWebView;
1977
1978 public boolean onMenuItemClick(MenuItem item) {
1979 if (mWebView != null) {
1980 return mWebView.selectText();
1981 }
1982 return false;
1983 }
1984
1985 public SelectText(WebView webView) {
1986 mWebView = webView;
1987 }
1988
1989 }
1990
Michael Kolb8233fac2010-10-26 16:08:53 -07001991 /********************** TODO: UI stuff *****************************/
1992
1993 // these methods have been copied, they still need to be cleaned up
1994
1995 /****************** tabs ***************************************************/
1996
1997 // basic tab interactions:
1998
1999 // it is assumed that tabcontrol already knows about the tab
2000 protected void addTab(Tab tab) {
2001 mUi.addTab(tab);
2002 }
2003
2004 protected void removeTab(Tab tab) {
2005 mUi.removeTab(tab);
2006 mTabControl.removeTab(tab);
2007 }
2008
2009 protected void setActiveTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002010 mTabControl.setCurrentTab(tab);
Michael Kolb77df4562010-11-19 14:49:34 -08002011 // the tab is guaranteed to have a webview after setCurrentTab
2012 mUi.setActiveTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002013 }
2014
2015 protected void closeEmptyChildTab() {
2016 Tab current = mTabControl.getCurrentTab();
2017 if (current != null
2018 && current.getWebView().copyBackForwardList().getSize() == 0) {
2019 Tab parent = current.getParentTab();
2020 if (parent != null) {
2021 switchToTab(mTabControl.getTabIndex(parent));
2022 closeTab(current);
2023 }
2024 }
2025 }
2026
2027 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
2028 Log.i(LOGTAG, "Reusing tab for " + appId);
2029 // Dismiss the subwindow if applicable.
2030 dismissSubWindow(appTab);
2031 // Since we might kill the WebView, remove it from the
2032 // content view first.
2033 mUi.detachTab(appTab);
2034 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002035 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002036 // TODO: analyze why the remove and add are necessary
2037 mUi.attachTab(appTab);
2038 if (mTabControl.getCurrentTab() != appTab) {
2039 switchToTab(mTabControl.getTabIndex(appTab));
John Reck30c714c2010-12-16 17:30:34 -08002040 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002041 } else {
2042 // If the tab was the current tab, we have to attach
2043 // it to the view system again.
2044 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002045 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002046 }
2047 }
2048
2049 // Remove the sub window if it exists. Also called by TabControl when the
2050 // user clicks the 'X' to dismiss a sub window.
2051 public void dismissSubWindow(Tab tab) {
2052 removeSubWindow(tab);
2053 // dismiss the subwindow. This will destroy the WebView.
2054 tab.dismissSubWindow();
2055 getCurrentTopWebView().requestFocus();
2056 }
2057
2058 @Override
2059 public void removeSubWindow(Tab t) {
2060 if (t.getSubWebView() != null) {
2061 mUi.removeSubWindow(t.getSubViewContainer());
2062 }
2063 }
2064
2065 @Override
2066 public void attachSubWindow(Tab tab) {
2067 if (tab.getSubWebView() != null) {
2068 mUi.attachSubWindow(tab.getSubViewContainer());
2069 getCurrentTopWebView().requestFocus();
2070 }
2071 }
2072
Michael Kolb843510f2010-12-09 10:51:49 -08002073 @Override
2074 public Tab openTabToHomePage() {
2075 // check for max tabs
2076 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002077 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2078 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002079 } else {
2080 mUi.showMaxTabsWarning();
2081 return null;
2082 }
2083 }
2084
Michael Kolb18eb3772010-12-10 14:29:51 -08002085 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2086 if (mSettings.openInBackground() && !forceForeground) {
2087 Tab tab = mTabControl.createNewTab(false, null, null,
2088 (parent != null) && parent.isPrivateBrowsingEnabled());
2089 if (tab != null) {
2090 addTab(tab);
2091 WebView view = tab.getWebView();
2092 loadUrl(view, url);
2093 }
2094 return tab;
2095 } else {
2096 return openTabAndShow(parent, new UrlData(url), false, null);
2097 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002098 }
2099
Michael Kolb18eb3772010-12-10 14:29:51 -08002100
Michael Kolb8233fac2010-10-26 16:08:53 -07002101 // This method does a ton of stuff. It will attempt to create a new tab
2102 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2103 // url isn't null, it will load the given url.
Michael Kolb18eb3772010-12-10 14:29:51 -08002104 public Tab openTabAndShow(Tab parent, UrlData urlData, boolean closeOnExit,
Michael Kolb8233fac2010-10-26 16:08:53 -07002105 String appId) {
2106 final Tab currentTab = mTabControl.getCurrentTab();
2107 if (mTabControl.canCreateNewTab()) {
2108 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Michael Kolb18eb3772010-12-10 14:29:51 -08002109 urlData.mUrl,
2110 (parent != null) && parent.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -07002111 WebView webview = tab.getWebView();
2112 // We must set the new tab as the current tab to reflect the old
2113 // animation behavior.
2114 addTab(tab);
2115 setActiveTab(tab);
2116 if (!urlData.isEmpty()) {
2117 loadUrlDataIn(tab, urlData);
2118 }
2119 return tab;
2120 } else {
2121 // Get rid of the subwindow if it exists
2122 dismissSubWindow(currentTab);
2123 if (!urlData.isEmpty()) {
2124 // Load the given url.
2125 loadUrlDataIn(currentTab, urlData);
2126 }
2127 return currentTab;
2128 }
2129 }
2130
Michael Kolb8233fac2010-10-26 16:08:53 -07002131 @Override
2132 public Tab openIncognitoTab() {
2133 if (mTabControl.canCreateNewTab()) {
2134 Tab currentTab = mTabControl.getCurrentTab();
2135 Tab tab = mTabControl.createNewTab(false, null, null, true);
2136 addTab(tab);
2137 setActiveTab(tab);
2138 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002139 } else {
2140 mUi.showMaxTabsWarning();
2141 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002142 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002143 }
2144
2145 /**
2146 * @param index Index of the tab to change to, as defined by
2147 * mTabControl.getTabIndex(Tab t).
2148 * @return boolean True if we successfully switched to a different tab. If
2149 * the indexth tab is null, or if that tab is the same as
2150 * the current one, return false.
2151 */
2152 @Override
2153 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002154 // hide combo view if open
2155 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002156 Tab tab = mTabControl.getTab(index);
2157 Tab currentTab = mTabControl.getCurrentTab();
2158 if (tab == null || tab == currentTab) {
2159 return false;
2160 }
2161 setActiveTab(tab);
2162 return true;
2163 }
2164
2165 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002166 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002167 // hide combo view if open
2168 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002169 final Tab current = mTabControl.getCurrentTab();
2170 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002171 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002172 return;
2173 }
2174 final Tab parent = current.getParentTab();
2175 int indexToShow = -1;
2176 if (parent != null) {
2177 indexToShow = mTabControl.getTabIndex(parent);
2178 } else {
2179 final int currentIndex = mTabControl.getCurrentIndex();
2180 // Try to move to the tab to the right
2181 indexToShow = currentIndex + 1;
2182 if (indexToShow > mTabControl.getTabCount() - 1) {
2183 // Try to move to the tab to the left
2184 indexToShow = currentIndex - 1;
2185 }
2186 }
2187 if (switchToTab(indexToShow)) {
2188 // Close window
2189 closeTab(current);
2190 }
2191 }
2192
2193 /**
2194 * Close the tab, remove its associated title bar, and adjust mTabControl's
2195 * current tab to a valid value.
2196 */
2197 @Override
2198 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002199 // hide combo view if open
2200 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002201 int currentIndex = mTabControl.getCurrentIndex();
2202 int removeIndex = mTabControl.getTabIndex(tab);
2203 removeTab(tab);
2204 if (currentIndex >= removeIndex && currentIndex != 0) {
2205 currentIndex--;
2206 }
2207 Tab newtab = mTabControl.getTab(currentIndex);
2208 setActiveTab(newtab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002209 }
2210
2211 /**************** TODO: Url loading clean up *******************************/
2212
2213 // Called when loading from context menu or LOAD_URL message
2214 protected void loadUrlFromContext(WebView view, String url) {
2215 // In case the user enters nothing.
2216 if (url != null && url.length() != 0 && view != null) {
2217 url = UrlUtils.smartUrlFilter(url);
2218 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2219 loadUrl(view, url);
2220 }
2221 }
2222 }
2223
2224 /**
2225 * Load the URL into the given WebView and update the title bar
2226 * to reflect the new load. Call this instead of WebView.loadUrl
2227 * directly.
2228 * @param view The WebView used to load url.
2229 * @param url The URL to load.
2230 */
2231 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002232 view.loadUrl(url);
2233 }
2234
2235 /**
2236 * Load UrlData into a Tab and update the title bar to reflect the new
2237 * load. Call this instead of UrlData.loadIn directly.
2238 * @param t The Tab used to load.
2239 * @param data The UrlData being loaded.
2240 */
2241 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002242 data.loadIn(t);
2243 }
2244
John Reck30c714c2010-12-16 17:30:34 -08002245 @Override
2246 public void onUserCanceledSsl(Tab tab) {
2247 WebView web = tab.getWebView();
2248 // TODO: Figure out the "right" behavior
2249 if (web.canGoBack()) {
2250 web.goBack();
2251 } else {
2252 web.loadUrl(mSettings.getHomePage());
2253 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002254 }
2255
2256 void goBackOnePageOrQuit() {
2257 Tab current = mTabControl.getCurrentTab();
2258 if (current == null) {
2259 /*
2260 * Instead of finishing the activity, simply push this to the back
2261 * of the stack and let ActivityManager to choose the foreground
2262 * activity. As BrowserActivity is singleTask, it will be always the
2263 * root of the task. So we can use either true or false for
2264 * moveTaskToBack().
2265 */
2266 mActivity.moveTaskToBack(true);
2267 return;
2268 }
2269 WebView w = current.getWebView();
2270 if (w.canGoBack()) {
2271 w.goBack();
2272 } else {
2273 // Check to see if we are closing a window that was created by
2274 // another window. If so, we switch back to that window.
2275 Tab parent = current.getParentTab();
2276 if (parent != null) {
2277 switchToTab(mTabControl.getTabIndex(parent));
2278 // Now we close the other tab
2279 closeTab(current);
2280 } else {
2281 if (current.closeOnExit()) {
2282 // force the tab's inLoad() to be false as we are going to
2283 // either finish the activity or remove the tab. This will
2284 // ensure pauseWebViewTimers() taking action.
Michael Kolb70976932010-11-30 11:34:01 -08002285 current.clearInPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07002286 if (mTabControl.getTabCount() == 1) {
2287 mActivity.finish();
2288 return;
2289 }
2290 if (mActivityPaused) {
2291 Log.e(LOGTAG, "BrowserActivity is already paused "
2292 + "while handing goBackOnePageOrQuit.");
2293 }
Michael Kolb70976932010-11-30 11:34:01 -08002294 pauseWebViewTimers(current);
Michael Kolb8233fac2010-10-26 16:08:53 -07002295 removeTab(current);
2296 }
2297 /*
2298 * Instead of finishing the activity, simply push this to the back
2299 * of the stack and let ActivityManager to choose the foreground
2300 * activity. As BrowserActivity is singleTask, it will be always the
2301 * root of the task. So we can use either true or false for
2302 * moveTaskToBack().
2303 */
2304 mActivity.moveTaskToBack(true);
2305 }
2306 }
2307 }
2308
2309 /**
2310 * Feed the previously stored results strings to the BrowserProvider so that
2311 * the SearchDialog will show them instead of the standard searches.
2312 * @param result String to show on the editable line of the SearchDialog.
2313 */
2314 @Override
2315 public void showVoiceSearchResults(String result) {
2316 ContentProviderClient client = mActivity.getContentResolver()
2317 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2318 ContentProvider prov = client.getLocalContentProvider();
2319 BrowserProvider bp = (BrowserProvider) prov;
2320 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2321 client.release();
2322
2323 Bundle bundle = createGoogleSearchSourceBundle(
2324 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2325 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2326 startSearch(result, false, bundle, false);
2327 }
2328
2329 private void startSearch(String initialQuery, boolean selectInitialQuery,
2330 Bundle appSearchData, boolean globalSearch) {
2331 if (appSearchData == null) {
2332 appSearchData = createGoogleSearchSourceBundle(
2333 GOOGLE_SEARCH_SOURCE_TYPE);
2334 }
2335
2336 SearchEngine searchEngine = mSettings.getSearchEngine();
2337 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2338 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2339 }
2340 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2341 globalSearch);
2342 }
2343
2344 private Bundle createGoogleSearchSourceBundle(String source) {
2345 Bundle bundle = new Bundle();
2346 bundle.putString(Search.SOURCE, source);
2347 return bundle;
2348 }
2349
2350 /**
2351 * handle key events in browser
2352 *
2353 * @param keyCode
2354 * @param event
2355 * @return true if handled, false to pass to super
2356 */
2357 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002358 boolean noModifiers = event.hasNoModifiers();
2359
Michael Kolb8233fac2010-10-26 16:08:53 -07002360 // Even if MENU is already held down, we need to call to super to open
2361 // the IME on long press.
Cary Clark160bbb92011-01-10 11:17:07 -05002362 if (!noModifiers && KeyEvent.KEYCODE_MENU == keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002363 mMenuIsDown = true;
2364 return false;
2365 }
2366 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2367 // still down, we don't want to trigger the search. Pretend to consume
2368 // the key and do nothing.
2369 if (mMenuIsDown) return true;
2370
Cary Clark8ff8c662010-12-29 15:03:05 -05002371 WebView webView = getCurrentTopWebView();
2372 if (webView == null) return false;
2373
Cary Clark160bbb92011-01-10 11:17:07 -05002374 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2375 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002376
Michael Kolb8233fac2010-10-26 16:08:53 -07002377 switch(keyCode) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002378 case KeyEvent.KEYCODE_ESCAPE:
Cary Clark160bbb92011-01-10 11:17:07 -05002379 if (!noModifiers) break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002380 stopLoading();
2381 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07002382 case KeyEvent.KEYCODE_SPACE:
2383 // WebView/WebTextView handle the keys in the KeyDown. As
2384 // the Activity's shortcut keys are only handled when WebView
2385 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002386 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002387 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002388 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002389 pageDown();
2390 }
2391 return true;
2392 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002393 if (!noModifiers) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002394 if (event.getRepeatCount() == 0) {
2395 event.startTracking();
2396 return true;
2397 } else if (mUi.showsWeb()
2398 && event.isLongPress()) {
2399 bookmarksOrHistoryPicker(true);
2400 return true;
2401 }
2402 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002403 case KeyEvent.KEYCODE_DPAD_LEFT:
2404 if (ctrl) {
2405 webView.goBack();
2406 return true;
2407 }
2408 break;
2409 case KeyEvent.KEYCODE_DPAD_RIGHT:
2410 if (ctrl) {
2411 webView.goForward();
2412 return true;
2413 }
2414 break;
2415 case KeyEvent.KEYCODE_A:
2416 if (ctrl) {
2417 webView.selectAll();
2418 return true;
2419 }
2420 break;
2421 case KeyEvent.KEYCODE_B:
2422 if (ctrl) {
2423 bookmarksOrHistoryPicker(false);
2424 return true;
2425 }
2426 break;
2427 case KeyEvent.KEYCODE_C:
2428 if (ctrl) {
2429 webView.copySelection();
2430 return true;
2431 }
2432 break;
2433 case KeyEvent.KEYCODE_D:
2434 if (ctrl) {
2435 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
2436 return true;
2437 }
2438 break;
2439// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
2440 case KeyEvent.KEYCODE_F:
2441 if (ctrl) {
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05002442 webView.showFindDialog(null, true);
Cary Clark8ff8c662010-12-29 15:03:05 -05002443 return true;
2444 }
2445 break;
2446// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
2447 case KeyEvent.KEYCODE_H:
2448 if (ctrl) {
2449 bookmarksOrHistoryPicker(true);
2450 return true;
2451 }
2452 break;
2453// case KeyEvent.KEYCODE_I: // unused
2454 case KeyEvent.KEYCODE_J:
2455 if (ctrl) {
2456 viewDownloads();
2457 return true;
2458 }
2459 break;
2460// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
2461 case KeyEvent.KEYCODE_L:
2462 if (ctrl) {
2463 editUrl();
2464 return true;
2465 }
2466 break;
2467// case KeyEvent.KEYCODE_M: // unused
2468// case KeyEvent.KEYCODE_N: // in Chrome: new window
2469// case KeyEvent.KEYCODE_O: // in Chrome: open file
2470// case KeyEvent.KEYCODE_P: // in Chrome: print page
2471// case KeyEvent.KEYCODE_Q: // unused
2472 case KeyEvent.KEYCODE_R:
2473 if (ctrl) {
2474 if (mInLoad) {
2475 stopLoading();
2476 } else {
2477 webView.reload();
2478 }
2479 return true;
2480 }
2481 break;
2482// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2483 case KeyEvent.KEYCODE_T:
2484 if (ctrl) {
2485 if (event.isShiftPressed()) {
2486 openIncognitoTab();
2487 } else {
2488 openTabToHomePage();
2489 }
2490 return true;
2491 }
2492 break;
2493// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2494// case KeyEvent.KEYCODE_V: // text view intercepts to paste
2495 case KeyEvent.KEYCODE_W:
2496 if (ctrl) {
2497 closeCurrentTab();
2498 return true;
2499 }
2500 break;
2501// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2502// case KeyEvent.KEYCODE_Y: // unused
2503// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002504 }
2505 return false;
2506 }
2507
2508 boolean onKeyUp(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002509 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002510 switch(keyCode) {
2511 case KeyEvent.KEYCODE_MENU:
2512 mMenuIsDown = false;
2513 break;
2514 case KeyEvent.KEYCODE_BACK:
2515 if (event.isTracking() && !event.isCanceled()) {
2516 onBackKey();
2517 return true;
2518 }
2519 break;
2520 }
2521 return false;
2522 }
2523
2524 public boolean isMenuDown() {
2525 return mMenuIsDown;
2526 }
2527
Ben Murdoch8029a772010-11-16 11:58:21 +00002528 public void setupAutoFill(Message message) {
2529 // Open the settings activity at the AutoFill profile fragment so that
2530 // the user can create a new profile. When they return, we will dispatch
2531 // the message so that we can autofill the form using their new profile.
2532 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2533 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2534 AutoFillSettingsFragment.class.getName());
2535 mAutoFillSetupMessage = message;
2536 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2537 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002538}