blob: e707e3649dea2dec31080deaf1c525dc7b4dee09 [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
736 public void onPageStarted(Tab tab, WebView view, String url, Bitmap favicon) {
737
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
Michael Kolb8233fac2010-10-26 16:08:53 -0700767 // update the bookmark database for favicon
768 maybeUpdateFavicon(tab, null, url, favicon);
769
770 Performance.tracePageStart(url);
771
772 // Performance probe
773 if (false) {
774 Performance.onPageStarted();
775 }
776
777 }
778
779 @Override
780 public void onPageFinished(Tab tab, String url) {
John Reck30c714c2010-12-16 17:30:34 -0800781 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700782 if (!tab.isPrivateBrowsingEnabled()) {
783 if (tab.inForeground() && !didUserStopLoading()
784 || !tab.inForeground()) {
785 // Only update the bookmark screenshot if the user did not
786 // cancel the load early.
787 mHandler.sendMessageDelayed(mHandler.obtainMessage(
788 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab.getWebView()),
789 500);
790 }
791 }
792 // pause the WebView timer and release the wake lock if it is finished
793 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800794 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700795 if (mWakeLock.isHeld()) {
796 mHandler.removeMessages(RELEASE_WAKELOCK);
797 mWakeLock.release();
798 }
799 }
800 // Performance probe
801 if (false) {
802 Performance.onPageFinished(url);
803 }
804
805 Performance.tracePageFinished();
806 }
807
808 @Override
John Reck30c714c2010-12-16 17:30:34 -0800809 public void onProgressChanged(Tab tab) {
810 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700811
812 if (newProgress == 100) {
813 CookieSyncManager.getInstance().sync();
814 // onProgressChanged() may continue to be called after the main
815 // frame has finished loading, as any remaining sub frames continue
816 // to load. We'll only get called once though with newProgress as
817 // 100 when everything is loaded. (onPageFinished is called once
818 // when the main frame completes loading regardless of the state of
819 // any sub frames so calls to onProgressChanges may continue after
820 // onPageFinished has executed)
821 if (mInLoad) {
822 mInLoad = false;
823 updateInLoadMenuItems(mCachedMenu);
824 }
825 } else {
826 if (!mInLoad) {
827 // onPageFinished may have already been called but a subframe is
828 // still loading and updating the progress. Reset mInLoad and
829 // update the menu items.
830 mInLoad = true;
831 updateInLoadMenuItems(mCachedMenu);
832 }
833 }
John Reck30c714c2010-12-16 17:30:34 -0800834 mUi.onProgressChanged(tab);
835 }
836
837 @Override
838 public void onUpdatedLockIcon(Tab tab) {
839 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700840 }
841
842 @Override
843 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800844 mUi.onTabDataChanged(tab);
845 final String pageUrl = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700846 if (pageUrl == null || pageUrl.length()
847 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
848 return;
849 }
850 // Update the title in the history database if not in private browsing mode
851 if (!tab.isPrivateBrowsingEnabled()) {
John Reck0ebd3ac2010-12-09 11:14:04 -0800852 mDataController.updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700853 }
854 }
855
856 @Override
857 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800858 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700859 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
860 }
861
862 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800863 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
864 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700865 }
866
867 @Override
868 public boolean shouldOverrideKeyEvent(KeyEvent event) {
869 if (mMenuIsDown) {
870 // only check shortcut key when MENU is held
871 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
872 event);
873 } else {
874 return false;
875 }
876 }
877
878 @Override
879 public void onUnhandledKeyEvent(KeyEvent event) {
880 if (!isActivityPaused()) {
881 if (event.getAction() == KeyEvent.ACTION_DOWN) {
882 mActivity.onKeyDown(event.getKeyCode(), event);
883 } else {
884 mActivity.onKeyUp(event.getKeyCode(), event);
885 }
886 }
887 }
888
889 @Override
890 public void doUpdateVisitedHistory(Tab tab, String url,
891 boolean isReload) {
892 // Don't save anything in private browsing mode
893 if (tab.isPrivateBrowsingEnabled()) return;
894
895 if (url.regionMatches(true, 0, "about:", 0, 6)) {
896 return;
897 }
John Reck0ebd3ac2010-12-09 11:14:04 -0800898 mDataController.updateVisitedHistory(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700899 WebIconDatabase.getInstance().retainIconForPageUrl(url);
900 }
901
902 @Override
903 public void getVisitedHistory(final ValueCallback<String[]> callback) {
904 AsyncTask<Void, Void, String[]> task =
905 new AsyncTask<Void, Void, String[]>() {
906 @Override
907 public String[] doInBackground(Void... unused) {
908 return Browser.getVisitedHistory(mActivity.getContentResolver());
909 }
910 @Override
911 public void onPostExecute(String[] result) {
912 callback.onReceiveValue(result);
913 }
914 };
915 task.execute();
916 }
917
918 @Override
919 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
920 final HttpAuthHandler handler, final String host,
921 final String realm) {
922 String username = null;
923 String password = null;
924
925 boolean reuseHttpAuthUsernamePassword
926 = handler.useHttpAuthUsernamePassword();
927
928 if (reuseHttpAuthUsernamePassword && view != null) {
929 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
930 if (credentials != null && credentials.length == 2) {
931 username = credentials[0];
932 password = credentials[1];
933 }
934 }
935
936 if (username != null && password != null) {
937 handler.proceed(username, password);
938 } else {
939 if (tab.inForeground()) {
940 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
941 } else {
942 handler.cancel();
943 }
944 }
945 }
946
947 @Override
948 public void onDownloadStart(Tab tab, String url, String userAgent,
949 String contentDisposition, String mimetype, long contentLength) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500950 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
951 contentDisposition, mimetype);
Michael Kolb8233fac2010-10-26 16:08:53 -0700952 if (tab.getWebView().copyBackForwardList().getSize() == 0) {
953 // This Tab was opened for the sole purpose of downloading a
954 // file. Remove it.
955 if (tab == mTabControl.getCurrentTab()) {
956 // In this case, the Tab is still on top.
957 goBackOnePageOrQuit();
958 } else {
959 // In this case, it is not.
960 closeTab(tab);
961 }
962 }
963 }
964
965 @Override
966 public Bitmap getDefaultVideoPoster() {
967 return mUi.getDefaultVideoPoster();
968 }
969
970 @Override
971 public View getVideoLoadingProgressView() {
972 return mUi.getVideoLoadingProgressView();
973 }
974
975 @Override
976 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
977 SslError error) {
978 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
979 }
980
981 // helper method
982
983 /*
984 * Update the favorites icon if the private browsing isn't enabled and the
985 * icon is valid.
986 */
987 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
988 final String url, Bitmap favicon) {
989 if (favicon == null) {
990 return;
991 }
992 if (!tab.isPrivateBrowsingEnabled()) {
993 Bookmarks.updateFavicon(mActivity
994 .getContentResolver(), originalUrl, url, favicon);
995 }
996 }
997
Leon Scroggins4cd97792010-12-03 15:31:56 -0500998 @Override
999 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001000 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001001 mUi.bookmarkedStatusHasChanged(tab);
1002 }
1003
Michael Kolb8233fac2010-10-26 16:08:53 -07001004 // end WebViewController
1005
1006 protected void pageUp() {
1007 getCurrentTopWebView().pageUp(false);
1008 }
1009
1010 protected void pageDown() {
1011 getCurrentTopWebView().pageDown(false);
1012 }
1013
1014 // callback from phone title bar
1015 public void editUrl() {
1016 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
1017 String url = (getCurrentTopWebView() == null) ? null : getCurrentTopWebView().getUrl();
1018 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1019 null, false);
1020 }
1021
Michael Kolbcfa3af52010-12-14 10:36:11 -08001022 public void startVoiceSearch() {
1023 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1024 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1025 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1026 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1027 mActivity.getComponentName().flattenToString());
1028 intent.putExtra(SEND_APP_ID_EXTRA, false);
1029 mActivity.startActivity(intent);
1030 }
1031
Michael Kolb8233fac2010-10-26 16:08:53 -07001032 public void activateVoiceSearchMode(String title) {
1033 mUi.showVoiceTitleBar(title);
1034 }
1035
1036 public void revertVoiceSearchMode(Tab tab) {
1037 mUi.revertVoiceTitleBar(tab);
1038 }
1039
1040 public void showCustomView(Tab tab, View view,
1041 WebChromeClient.CustomViewCallback callback) {
1042 if (tab.inForeground()) {
1043 if (mUi.isCustomViewShowing()) {
1044 callback.onCustomViewHidden();
1045 return;
1046 }
1047 mUi.showCustomView(view, callback);
1048 // Save the menu state and set it to empty while the custom
1049 // view is showing.
1050 mOldMenuState = mMenuState;
1051 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001052 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001053 }
1054 }
1055
1056 @Override
1057 public void hideCustomView() {
1058 if (mUi.isCustomViewShowing()) {
1059 mUi.onHideCustomView();
1060 // Reset the old menu state.
1061 mMenuState = mOldMenuState;
1062 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001063 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001064 }
1065 }
1066
1067 protected void onActivityResult(int requestCode, int resultCode,
1068 Intent intent) {
1069 if (getCurrentTopWebView() == null) return;
1070 switch (requestCode) {
1071 case PREFERENCES_PAGE:
1072 if (resultCode == Activity.RESULT_OK && intent != null) {
1073 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
1074 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
1075 mTabControl.removeParentChildRelationShips();
1076 }
1077 }
1078 break;
1079 case FILE_SELECTED:
1080 // Choose a file from the file picker.
1081 if (null == mUploadHandler) break;
1082 mUploadHandler.onResult(resultCode, intent);
1083 mUploadHandler = null;
1084 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001085 case AUTOFILL_SETUP:
1086 // Determine whether a profile was actually set up or not
1087 // and if so, send the message back to the WebTextView to
1088 // fill the form with the new profile.
1089 if (getSettings().getAutoFillProfile() != null) {
1090 mAutoFillSetupMessage.sendToTarget();
1091 mAutoFillSetupMessage = null;
1092 }
1093 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001094 default:
1095 break;
1096 }
1097 getCurrentTopWebView().requestFocus();
1098 }
1099
1100 /**
1101 * Open the Go page.
1102 * @param startWithHistory If true, open starting on the history tab.
1103 * Otherwise, start with the bookmarks tab.
1104 */
1105 @Override
1106 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1107 if (mTabControl.getCurrentWebView() == null) {
1108 return;
1109 }
1110 Bundle extras = new Bundle();
1111 // Disable opening in a new window if we have maxed out the windows
1112 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1113 !mTabControl.canCreateNewTab());
1114 mUi.showComboView(startWithHistory, extras);
1115 }
1116
1117 // combo view callbacks
1118
1119 /**
1120 * callback from ComboPage when clear history is requested
1121 */
1122 public void onRemoveParentChildRelationships() {
1123 mTabControl.removeParentChildRelationShips();
1124 }
1125
1126 /**
1127 * callback from ComboPage when bookmark/history selection
1128 */
1129 @Override
1130 public void onUrlSelected(String url, boolean newTab) {
1131 removeComboView();
1132 if (!TextUtils.isEmpty(url)) {
1133 if (newTab) {
Michael Kolb18eb3772010-12-10 14:29:51 -08001134 openTab(mTabControl.getCurrentTab(), url, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001135 } else {
1136 final Tab currentTab = mTabControl.getCurrentTab();
1137 dismissSubWindow(currentTab);
1138 loadUrl(getCurrentTopWebView(), url);
1139 }
1140 }
1141 }
1142
1143 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07001144 * dismiss the ComboPage
1145 */
1146 @Override
1147 public void removeComboView() {
1148 mUi.hideComboView();
1149 }
1150
1151 // active tabs page handling
1152
1153 protected void showActiveTabsPage() {
1154 mMenuState = EMPTY_MENU;
1155 mUi.showActiveTabsPage();
1156 }
1157
1158 /**
1159 * Remove the active tabs page.
1160 * @param needToAttach If true, the active tabs page did not attach a tab
1161 * to the content view, so we need to do that here.
1162 */
1163 @Override
1164 public void removeActiveTabsPage(boolean needToAttach) {
1165 mMenuState = R.id.MAIN_MENU;
1166 mUi.removeActiveTabsPage();
1167 if (needToAttach) {
1168 setActiveTab(mTabControl.getCurrentTab());
1169 }
1170 getCurrentTopWebView().requestFocus();
1171 }
1172
1173 // key handling
1174 protected void onBackKey() {
1175 if (!mUi.onBackKey()) {
1176 WebView subwindow = mTabControl.getCurrentSubWindow();
1177 if (subwindow != null) {
1178 if (subwindow.canGoBack()) {
1179 subwindow.goBack();
1180 } else {
1181 dismissSubWindow(mTabControl.getCurrentTab());
1182 }
1183 } else {
1184 goBackOnePageOrQuit();
1185 }
1186 }
1187 }
1188
1189 // menu handling and state
1190 // TODO: maybe put into separate handler
1191
1192 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckd73c5a22010-12-22 10:22:50 -08001193 if (mMenuState == EMPTY_MENU) {
1194 return false;
1195 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001196 MenuInflater inflater = mActivity.getMenuInflater();
1197 inflater.inflate(R.menu.browser, menu);
1198 updateInLoadMenuItems(menu);
1199 // hold on to the menu reference here; it is used by the page callbacks
1200 // to update the menu based on loading state
1201 mCachedMenu = menu;
1202 return true;
1203 }
1204
1205 protected void onCreateContextMenu(ContextMenu menu, View v,
1206 ContextMenuInfo menuInfo) {
1207 if (v instanceof TitleBarBase) {
1208 return;
1209 }
1210 if (!(v instanceof WebView)) {
1211 return;
1212 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001213 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001214 WebView.HitTestResult result = webview.getHitTestResult();
1215 if (result == null) {
1216 return;
1217 }
1218
1219 int type = result.getType();
1220 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1221 Log.w(LOGTAG,
1222 "We should not show context menu when nothing is touched");
1223 return;
1224 }
1225 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1226 // let TextView handles context menu
1227 return;
1228 }
1229
1230 // Note, http://b/issue?id=1106666 is requesting that
1231 // an inflated menu can be used again. This is not available
1232 // yet, so inflate each time (yuk!)
1233 MenuInflater inflater = mActivity.getMenuInflater();
1234 inflater.inflate(R.menu.browsercontext, menu);
1235
1236 // Show the correct menu group
1237 final String extra = result.getExtra();
1238 menu.setGroupVisible(R.id.PHONE_MENU,
1239 type == WebView.HitTestResult.PHONE_TYPE);
1240 menu.setGroupVisible(R.id.EMAIL_MENU,
1241 type == WebView.HitTestResult.EMAIL_TYPE);
1242 menu.setGroupVisible(R.id.GEO_MENU,
1243 type == WebView.HitTestResult.GEO_TYPE);
1244 menu.setGroupVisible(R.id.IMAGE_MENU,
1245 type == WebView.HitTestResult.IMAGE_TYPE
1246 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1247 menu.setGroupVisible(R.id.ANCHOR_MENU,
1248 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1249 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001250 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1251 || type == WebView.HitTestResult.PHONE_TYPE
1252 || type == WebView.HitTestResult.EMAIL_TYPE
1253 || type == WebView.HitTestResult.GEO_TYPE;
1254 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1255 if (hitText) {
1256 menu.findItem(R.id.select_text_menu_id)
1257 .setOnMenuItemClickListener(new SelectText(webview));
1258 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001259 // Setup custom handling depending on the type
1260 switch (type) {
1261 case WebView.HitTestResult.PHONE_TYPE:
1262 menu.setHeaderTitle(Uri.decode(extra));
1263 menu.findItem(R.id.dial_context_menu_id).setIntent(
1264 new Intent(Intent.ACTION_VIEW, Uri
1265 .parse(WebView.SCHEME_TEL + extra)));
1266 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1267 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1268 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1269 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1270 addIntent);
1271 menu.findItem(R.id.copy_phone_context_menu_id)
1272 .setOnMenuItemClickListener(
1273 new Copy(extra));
1274 break;
1275
1276 case WebView.HitTestResult.EMAIL_TYPE:
1277 menu.setHeaderTitle(extra);
1278 menu.findItem(R.id.email_context_menu_id).setIntent(
1279 new Intent(Intent.ACTION_VIEW, Uri
1280 .parse(WebView.SCHEME_MAILTO + extra)));
1281 menu.findItem(R.id.copy_mail_context_menu_id)
1282 .setOnMenuItemClickListener(
1283 new Copy(extra));
1284 break;
1285
1286 case WebView.HitTestResult.GEO_TYPE:
1287 menu.setHeaderTitle(extra);
1288 menu.findItem(R.id.map_context_menu_id).setIntent(
1289 new Intent(Intent.ACTION_VIEW, Uri
1290 .parse(WebView.SCHEME_GEO
1291 + URLEncoder.encode(extra))));
1292 menu.findItem(R.id.copy_geo_context_menu_id)
1293 .setOnMenuItemClickListener(
1294 new Copy(extra));
1295 break;
1296
1297 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1298 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1299 TextView titleView = (TextView) LayoutInflater.from(mActivity)
1300 .inflate(android.R.layout.browser_link_context_header,
1301 null);
1302 titleView.setText(extra);
1303 menu.setHeaderView(titleView);
1304 // decide whether to show the open link in new tab option
1305 boolean showNewTab = mTabControl.canCreateNewTab();
1306 MenuItem newTabItem
1307 = menu.findItem(R.id.open_newtab_context_menu_id);
1308 newTabItem.setVisible(showNewTab);
1309 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001310 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1311 newTabItem.setOnMenuItemClickListener(
1312 new MenuItem.OnMenuItemClickListener() {
1313 @Override
1314 public boolean onMenuItemClick(MenuItem item) {
1315 final HashMap<String, WebView> hrefMap =
1316 new HashMap<String, WebView>();
1317 hrefMap.put("webview", webview);
1318 final Message msg = mHandler.obtainMessage(
1319 FOCUS_NODE_HREF,
1320 R.id.open_newtab_context_menu_id,
1321 0, hrefMap);
1322 webview.requestFocusNodeHref(msg);
1323 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001324 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001325 });
1326 } else {
1327 newTabItem.setOnMenuItemClickListener(
1328 new MenuItem.OnMenuItemClickListener() {
1329 @Override
1330 public boolean onMenuItemClick(MenuItem item) {
1331 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -08001332 final Tab newTab = openTab(parent,
1333 extra, false);
Leon Scroggins026f2542010-11-22 13:26:12 -05001334 if (newTab != parent) {
1335 parent.addChildTab(newTab);
1336 }
1337 return true;
1338 }
1339 });
1340 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001341 }
1342 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1343 Bookmarks.urlHasAcceptableScheme(extra));
1344 PackageManager pm = mActivity.getPackageManager();
1345 Intent send = new Intent(Intent.ACTION_SEND);
1346 send.setType("text/plain");
1347 ResolveInfo ri = pm.resolveActivity(send,
1348 PackageManager.MATCH_DEFAULT_ONLY);
1349 menu.findItem(R.id.share_link_context_menu_id)
1350 .setVisible(ri != null);
1351 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1352 break;
1353 }
1354 // otherwise fall through to handle image part
1355 case WebView.HitTestResult.IMAGE_TYPE:
1356 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1357 menu.setHeaderTitle(extra);
1358 }
1359 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1360 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1361 menu.findItem(R.id.download_context_menu_id).
Leon Scroggins63c02662010-11-18 15:16:27 -05001362 setOnMenuItemClickListener(new Download(mActivity, extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001363 menu.findItem(R.id.set_wallpaper_context_menu_id).
1364 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1365 extra));
1366 break;
1367
1368 default:
1369 Log.w(LOGTAG, "We should not get here.");
1370 break;
1371 }
1372 //update the ui
1373 mUi.onContextMenuCreated(menu);
1374 }
1375
1376 /**
1377 * As the menu can be open when loading state changes
1378 * we must manually update the state of the stop/reload menu
1379 * item
1380 */
1381 private void updateInLoadMenuItems(Menu menu) {
1382 if (menu == null) {
1383 return;
1384 }
1385 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1386 MenuItem src = mInLoad ?
1387 menu.findItem(R.id.stop_menu_id):
1388 menu.findItem(R.id.reload_menu_id);
1389 if (src != null) {
1390 dest.setIcon(src.getIcon());
1391 dest.setTitle(src.getTitle());
1392 }
1393 }
1394
1395 boolean prepareOptionsMenu(Menu menu) {
1396 // This happens when the user begins to hold down the menu key, so
1397 // allow them to chord to get a shortcut.
1398 mCanChord = true;
1399 // Note: setVisible will decide whether an item is visible; while
1400 // setEnabled() will decide whether an item is enabled, which also means
1401 // whether the matching shortcut key will function.
1402 switch (mMenuState) {
1403 case EMPTY_MENU:
1404 if (mCurrentMenuState != mMenuState) {
1405 menu.setGroupVisible(R.id.MAIN_MENU, false);
1406 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1407 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1408 }
1409 break;
1410 default:
1411 if (mCurrentMenuState != mMenuState) {
1412 menu.setGroupVisible(R.id.MAIN_MENU, true);
1413 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1414 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1415 }
1416 final WebView w = getCurrentTopWebView();
1417 boolean canGoBack = false;
1418 boolean canGoForward = false;
1419 boolean isHome = false;
1420 if (w != null) {
1421 canGoBack = w.canGoBack();
1422 canGoForward = w.canGoForward();
1423 isHome = mSettings.getHomePage().equals(w.getUrl());
1424 }
1425 final MenuItem back = menu.findItem(R.id.back_menu_id);
1426 back.setEnabled(canGoBack);
1427
1428 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1429 home.setEnabled(!isHome);
1430
1431 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1432 forward.setEnabled(canGoForward);
1433
1434 // decide whether to show the share link option
1435 PackageManager pm = mActivity.getPackageManager();
1436 Intent send = new Intent(Intent.ACTION_SEND);
1437 send.setType("text/plain");
1438 ResolveInfo ri = pm.resolveActivity(send,
1439 PackageManager.MATCH_DEFAULT_ONLY);
1440 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1441
1442 boolean isNavDump = mSettings.isNavDump();
1443 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1444 nav.setVisible(isNavDump);
1445 nav.setEnabled(isNavDump);
1446
1447 boolean showDebugSettings = mSettings.showDebugSettings();
1448 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1449 counter.setVisible(showDebugSettings);
1450 counter.setEnabled(showDebugSettings);
1451
1452 // allow the ui to adjust state based settings
1453 mUi.onPrepareOptionsMenu(menu);
1454
1455 break;
1456 }
1457 mCurrentMenuState = mMenuState;
1458 return true;
1459 }
1460
1461 public boolean onOptionsItemSelected(MenuItem item) {
1462 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1463 // menu remains active, so ensure comboview is dismissed
1464 // if main menu option is selected
1465 removeComboView();
1466 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001467 if (!mCanChord) {
1468 // The user has already fired a shortcut with this hold down of the
1469 // menu key.
1470 return false;
1471 }
1472 if (null == getCurrentTopWebView()) {
1473 return false;
1474 }
1475 if (mMenuIsDown) {
1476 // The shortcut action consumes the MENU. Even if it is still down,
1477 // it won't trigger the next shortcut action. In the case of the
1478 // shortcut action triggering a new activity, like Bookmarks, we
1479 // won't get onKeyUp for MENU. So it is important to reset it here.
1480 mMenuIsDown = false;
1481 }
1482 switch (item.getItemId()) {
1483 // -- Main menu
1484 case R.id.new_tab_menu_id:
1485 openTabToHomePage();
1486 break;
1487
1488 case R.id.incognito_menu_id:
1489 openIncognitoTab();
1490 break;
1491
1492 case R.id.goto_menu_id:
1493 editUrl();
1494 break;
1495
1496 case R.id.bookmarks_menu_id:
1497 bookmarksOrHistoryPicker(false);
1498 break;
1499
1500 case R.id.active_tabs_menu_id:
1501 showActiveTabsPage();
1502 break;
1503
1504 case R.id.add_bookmark_menu_id:
1505 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
1506 break;
1507
1508 case R.id.stop_reload_menu_id:
1509 if (mInLoad) {
1510 stopLoading();
1511 } else {
1512 getCurrentTopWebView().reload();
1513 }
1514 break;
1515
1516 case R.id.back_menu_id:
1517 getCurrentTopWebView().goBack();
1518 break;
1519
1520 case R.id.forward_menu_id:
1521 getCurrentTopWebView().goForward();
1522 break;
1523
1524 case R.id.close_menu_id:
1525 // Close the subwindow if it exists.
1526 if (mTabControl.getCurrentSubWindow() != null) {
1527 dismissSubWindow(mTabControl.getCurrentTab());
1528 break;
1529 }
1530 closeCurrentTab();
1531 break;
1532
1533 case R.id.homepage_menu_id:
1534 Tab current = mTabControl.getCurrentTab();
1535 if (current != null) {
1536 dismissSubWindow(current);
1537 loadUrl(current.getWebView(), mSettings.getHomePage());
1538 }
1539 break;
1540
1541 case R.id.preferences_menu_id:
1542 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1543 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1544 getCurrentTopWebView().getUrl());
1545 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1546 break;
1547
1548 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001549 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001550 break;
1551
1552 case R.id.page_info_menu_id:
1553 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1554 false);
1555 break;
1556
1557 case R.id.classic_history_menu_id:
1558 bookmarksOrHistoryPicker(true);
1559 break;
1560
1561 case R.id.title_bar_share_page_url:
1562 case R.id.share_page_menu_id:
1563 Tab currentTab = mTabControl.getCurrentTab();
1564 if (null == currentTab) {
1565 mCanChord = false;
1566 return false;
1567 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001568 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001569 break;
1570
1571 case R.id.dump_nav_menu_id:
1572 getCurrentTopWebView().debugDump();
1573 break;
1574
1575 case R.id.dump_counters_menu_id:
1576 getCurrentTopWebView().dumpV8Counters();
1577 break;
1578
1579 case R.id.zoom_in_menu_id:
1580 getCurrentTopWebView().zoomIn();
1581 break;
1582
1583 case R.id.zoom_out_menu_id:
1584 getCurrentTopWebView().zoomOut();
1585 break;
1586
1587 case R.id.view_downloads_menu_id:
1588 viewDownloads();
1589 break;
1590
1591 case R.id.window_one_menu_id:
1592 case R.id.window_two_menu_id:
1593 case R.id.window_three_menu_id:
1594 case R.id.window_four_menu_id:
1595 case R.id.window_five_menu_id:
1596 case R.id.window_six_menu_id:
1597 case R.id.window_seven_menu_id:
1598 case R.id.window_eight_menu_id:
1599 {
1600 int menuid = item.getItemId();
1601 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1602 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1603 Tab desiredTab = mTabControl.getTab(id);
1604 if (desiredTab != null &&
1605 desiredTab != mTabControl.getCurrentTab()) {
1606 switchToTab(id);
1607 }
1608 break;
1609 }
1610 }
1611 }
1612 break;
1613
1614 default:
1615 return false;
1616 }
1617 mCanChord = false;
1618 return true;
1619 }
1620
1621 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001622 // Let the History and Bookmark fragments handle menus they created.
1623 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1624 return false;
1625 }
1626
Michael Kolb8233fac2010-10-26 16:08:53 -07001627 // chording is not an issue with context menus, but we use the same
1628 // options selector, so set mCanChord to true so we can access them.
1629 mCanChord = true;
1630 int id = item.getItemId();
1631 boolean result = true;
1632 switch (id) {
1633 // For the context menu from the title bar
1634 case R.id.title_bar_copy_page_url:
1635 Tab currentTab = mTabControl.getCurrentTab();
1636 if (null == currentTab) {
1637 result = false;
1638 break;
1639 }
1640 WebView mainView = currentTab.getWebView();
1641 if (null == mainView) {
1642 result = false;
1643 break;
1644 }
1645 copy(mainView.getUrl());
1646 break;
1647 // -- Browser context menu
1648 case R.id.open_context_menu_id:
1649 case R.id.bookmark_context_menu_id:
1650 case R.id.save_link_context_menu_id:
1651 case R.id.share_link_context_menu_id:
1652 case R.id.copy_link_context_menu_id:
1653 final WebView webView = getCurrentTopWebView();
1654 if (null == webView) {
1655 result = false;
1656 break;
1657 }
1658 final HashMap<String, WebView> hrefMap =
1659 new HashMap<String, WebView>();
1660 hrefMap.put("webview", webView);
1661 final Message msg = mHandler.obtainMessage(
1662 FOCUS_NODE_HREF, id, 0, hrefMap);
1663 webView.requestFocusNodeHref(msg);
1664 break;
1665
1666 default:
1667 // For other context menus
1668 result = onOptionsItemSelected(item);
1669 }
1670 mCanChord = false;
1671 return result;
1672 }
1673
1674 /**
1675 * support programmatically opening the context menu
1676 */
1677 public void openContextMenu(View view) {
1678 mActivity.openContextMenu(view);
1679 }
1680
1681 /**
1682 * programmatically open the options menu
1683 */
1684 public void openOptionsMenu() {
1685 mActivity.openOptionsMenu();
1686 }
1687
1688 public boolean onMenuOpened(int featureId, Menu menu) {
1689 if (mOptionsMenuOpen) {
1690 if (mConfigChanged) {
1691 // We do not need to make any changes to the state of the
1692 // title bar, since the only thing that happened was a
1693 // change in orientation
1694 mConfigChanged = false;
1695 } else {
1696 if (!mExtendedMenuOpen) {
1697 mExtendedMenuOpen = true;
1698 mUi.onExtendedMenuOpened();
1699 } else {
1700 // Switching the menu back to icon view, so show the
1701 // title bar once again.
1702 mExtendedMenuOpen = false;
1703 mUi.onExtendedMenuClosed(mInLoad);
1704 mUi.onOptionsMenuOpened();
1705 }
1706 }
1707 } else {
1708 // The options menu is closed, so open it, and show the title
1709 mOptionsMenuOpen = true;
1710 mConfigChanged = false;
1711 mExtendedMenuOpen = false;
1712 mUi.onOptionsMenuOpened();
1713 }
1714 return true;
1715 }
1716
1717 public void onOptionsMenuClosed(Menu menu) {
1718 mOptionsMenuOpen = false;
1719 mUi.onOptionsMenuClosed(mInLoad);
1720 }
1721
1722 public void onContextMenuClosed(Menu menu) {
1723 mUi.onContextMenuClosed(menu, mInLoad);
1724 }
1725
1726 // Helper method for getting the top window.
1727 @Override
1728 public WebView getCurrentTopWebView() {
1729 return mTabControl.getCurrentTopWebView();
1730 }
1731
1732 @Override
1733 public WebView getCurrentWebView() {
1734 return mTabControl.getCurrentWebView();
1735 }
1736
1737 /*
1738 * This method is called as a result of the user selecting the options
1739 * menu to see the download window. It shows the download window on top of
1740 * the current window.
1741 */
1742 void viewDownloads() {
1743 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1744 mActivity.startActivity(intent);
1745 }
1746
1747 // action mode
1748
1749 void onActionModeStarted(ActionMode mode) {
1750 mUi.onActionModeStarted(mode);
1751 mActionMode = mode;
1752 }
1753
1754 /*
1755 * True if a custom ActionMode (i.e. find or select) is in use.
1756 */
1757 @Override
1758 public boolean isInCustomActionMode() {
1759 return mActionMode != null;
1760 }
1761
1762 /*
1763 * End the current ActionMode.
1764 */
1765 @Override
1766 public void endActionMode() {
1767 if (mActionMode != null) {
1768 mActionMode.finish();
1769 }
1770 }
1771
1772 /*
1773 * Called by find and select when they are finished. Replace title bars
1774 * as necessary.
1775 */
1776 public void onActionModeFinished(ActionMode mode) {
1777 if (!isInCustomActionMode()) return;
1778 mUi.onActionModeFinished(mInLoad);
1779 mActionMode = null;
1780 }
1781
1782 boolean isInLoad() {
1783 return mInLoad;
1784 }
1785
1786 // bookmark handling
1787
1788 /**
1789 * add the current page as a bookmark to the given folder id
1790 * @param folderId use -1 for the default folder
1791 */
1792 @Override
1793 public void bookmarkCurrentPage(long folderId) {
1794 Intent i = new Intent(mActivity,
1795 AddBookmarkPage.class);
1796 WebView w = getCurrentTopWebView();
1797 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1798 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1799 String touchIconUrl = w.getTouchIconUrl();
1800 if (touchIconUrl != null) {
1801 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1802 WebSettings settings = w.getSettings();
1803 if (settings != null) {
1804 i.putExtra(AddBookmarkPage.USER_AGENT,
1805 settings.getUserAgentString());
1806 }
1807 }
1808 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1809 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1810 getDesiredThumbnailHeight(mActivity)));
1811 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1812 i.putExtra(BrowserContract.Bookmarks.PARENT,
1813 folderId);
1814 // Put the dialog at the upper right of the screen, covering the
1815 // star on the title bar.
1816 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1817 mActivity.startActivity(i);
1818 }
1819
1820 // file chooser
1821 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1822 mUploadHandler = new UploadHandler(this);
1823 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1824 }
1825
1826 // thumbnails
1827
1828 /**
1829 * Return the desired width for thumbnail screenshots, which are stored in
1830 * the database, and used on the bookmarks screen.
1831 * @param context Context for finding out the density of the screen.
1832 * @return desired width for thumbnail screenshot.
1833 */
1834 static int getDesiredThumbnailWidth(Context context) {
1835 return context.getResources().getDimensionPixelOffset(
1836 R.dimen.bookmarkThumbnailWidth);
1837 }
1838
1839 /**
1840 * Return the desired height for thumbnail screenshots, which are stored in
1841 * the database, and used on the bookmarks screen.
1842 * @param context Context for finding out the density of the screen.
1843 * @return desired height for thumbnail screenshot.
1844 */
1845 static int getDesiredThumbnailHeight(Context context) {
1846 return context.getResources().getDimensionPixelOffset(
1847 R.dimen.bookmarkThumbnailHeight);
1848 }
1849
1850 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001851 // We render to a bitmap 2x the desired size so that we can then
1852 // re-scale it with filtering since canvas.scale doesn't filter
1853 // This helps reduce aliasing at the cost of being slightly blurry
1854 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001855 Picture thumbnail = view.capturePicture();
1856 if (thumbnail == null) {
1857 return null;
1858 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001859 width *= filter_scale;
1860 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001861 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1862 Canvas canvas = new Canvas(bm);
1863 // May need to tweak these values to determine what is the
1864 // best scale factor
1865 int thumbnailWidth = thumbnail.getWidth();
1866 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001867 float scaleFactor = 1.0f;
Michael Kolb8233fac2010-10-26 16:08:53 -07001868 if (thumbnailWidth > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001869 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001870 } else {
1871 return null;
1872 }
John Reckfe49ab42010-11-16 17:09:37 -08001873
Michael Kolb8233fac2010-10-26 16:08:53 -07001874 if (view.getWidth() > view.getHeight() &&
1875 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
1876 // If the device is in landscape and the page is shorter
John Reckfe49ab42010-11-16 17:09:37 -08001877 // than the height of the view, center the thumnail and crop the sides
1878 scaleFactor = (float) height / (float)thumbnailHeight;
1879 float wx = (thumbnailWidth * scaleFactor) - width;
1880 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001881 }
1882
John Reckfe49ab42010-11-16 17:09:37 -08001883 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001884
1885 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001886 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
1887 height / filter_scale, true);
1888 bm.recycle();
1889 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001890 }
1891
1892 private void updateScreenshot(WebView view) {
1893 // If this is a bookmarked site, add a screenshot to the database.
1894 // FIXME: When should we update? Every time?
1895 // FIXME: Would like to make sure there is actually something to
1896 // draw, but the API for that (WebViewCore.pictureReady()) is not
1897 // currently accessible here.
1898
1899 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1900 getDesiredThumbnailHeight(mActivity));
1901 if (bm == null) {
1902 return;
1903 }
1904
1905 final ContentResolver cr = mActivity.getContentResolver();
1906 final String url = view.getUrl();
1907 final String originalUrl = view.getOriginalUrl();
1908
John Recka00cbbd2010-12-16 12:38:19 -08001909 // Only update thumbnails for web urls (http(s)://), not for
1910 // about:, javascript:, data:, etc...
John Reck9d038482011-01-04 17:02:09 -08001911 if (url != null && Patterns.WEB_URL.matcher(url).matches()) {
John Recka00cbbd2010-12-16 12:38:19 -08001912 new AsyncTask<Void, Void, Void>() {
1913 @Override
1914 protected Void doInBackground(Void... unused) {
1915 Cursor cursor = null;
1916 try {
1917 // TODO: Clean this up
1918 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
1919 if (cursor != null && cursor.moveToFirst()) {
1920 final ByteArrayOutputStream os =
1921 new ByteArrayOutputStream();
1922 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07001923
John Recka00cbbd2010-12-16 12:38:19 -08001924 ContentValues values = new ContentValues();
1925 values.put(Images.THUMBNAIL, os.toByteArray());
1926 values.put(Images.URL, cursor.getString(0));
Michael Kolb8233fac2010-10-26 16:08:53 -07001927
John Recka00cbbd2010-12-16 12:38:19 -08001928 do {
1929 cr.update(Images.CONTENT_URI, values, null, null);
1930 } while (cursor.moveToNext());
1931 }
1932 } catch (IllegalStateException e) {
1933 // Ignore
1934 } finally {
1935 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07001936 }
John Recka00cbbd2010-12-16 12:38:19 -08001937 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07001938 }
John Recka00cbbd2010-12-16 12:38:19 -08001939 }.execute();
1940 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001941 }
1942
1943 private class Copy implements OnMenuItemClickListener {
1944 private CharSequence mText;
1945
1946 public boolean onMenuItemClick(MenuItem item) {
1947 copy(mText);
1948 return true;
1949 }
1950
1951 public Copy(CharSequence toCopy) {
1952 mText = toCopy;
1953 }
1954 }
1955
Leon Scroggins63c02662010-11-18 15:16:27 -05001956 private static class Download implements OnMenuItemClickListener {
1957 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001958 private String mText;
1959
1960 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05001961 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
1962 null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001963 return true;
1964 }
1965
Leon Scroggins63c02662010-11-18 15:16:27 -05001966 public Download(Activity activity, String toDownload) {
1967 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001968 mText = toDownload;
1969 }
1970 }
1971
Cary Clark8974d282010-11-22 10:46:05 -05001972 private static class SelectText implements OnMenuItemClickListener {
1973 private WebView mWebView;
1974
1975 public boolean onMenuItemClick(MenuItem item) {
1976 if (mWebView != null) {
1977 return mWebView.selectText();
1978 }
1979 return false;
1980 }
1981
1982 public SelectText(WebView webView) {
1983 mWebView = webView;
1984 }
1985
1986 }
1987
Michael Kolb8233fac2010-10-26 16:08:53 -07001988 /********************** TODO: UI stuff *****************************/
1989
1990 // these methods have been copied, they still need to be cleaned up
1991
1992 /****************** tabs ***************************************************/
1993
1994 // basic tab interactions:
1995
1996 // it is assumed that tabcontrol already knows about the tab
1997 protected void addTab(Tab tab) {
1998 mUi.addTab(tab);
1999 }
2000
2001 protected void removeTab(Tab tab) {
2002 mUi.removeTab(tab);
2003 mTabControl.removeTab(tab);
2004 }
2005
2006 protected void setActiveTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002007 mTabControl.setCurrentTab(tab);
Michael Kolb77df4562010-11-19 14:49:34 -08002008 // the tab is guaranteed to have a webview after setCurrentTab
2009 mUi.setActiveTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002010 }
2011
2012 protected void closeEmptyChildTab() {
2013 Tab current = mTabControl.getCurrentTab();
2014 if (current != null
2015 && current.getWebView().copyBackForwardList().getSize() == 0) {
2016 Tab parent = current.getParentTab();
2017 if (parent != null) {
2018 switchToTab(mTabControl.getTabIndex(parent));
2019 closeTab(current);
2020 }
2021 }
2022 }
2023
2024 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
2025 Log.i(LOGTAG, "Reusing tab for " + appId);
2026 // Dismiss the subwindow if applicable.
2027 dismissSubWindow(appTab);
2028 // Since we might kill the WebView, remove it from the
2029 // content view first.
2030 mUi.detachTab(appTab);
2031 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002032 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002033 // TODO: analyze why the remove and add are necessary
2034 mUi.attachTab(appTab);
2035 if (mTabControl.getCurrentTab() != appTab) {
2036 switchToTab(mTabControl.getTabIndex(appTab));
John Reck30c714c2010-12-16 17:30:34 -08002037 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002038 } else {
2039 // If the tab was the current tab, we have to attach
2040 // it to the view system again.
2041 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002042 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002043 }
2044 }
2045
2046 // Remove the sub window if it exists. Also called by TabControl when the
2047 // user clicks the 'X' to dismiss a sub window.
2048 public void dismissSubWindow(Tab tab) {
2049 removeSubWindow(tab);
2050 // dismiss the subwindow. This will destroy the WebView.
2051 tab.dismissSubWindow();
2052 getCurrentTopWebView().requestFocus();
2053 }
2054
2055 @Override
2056 public void removeSubWindow(Tab t) {
2057 if (t.getSubWebView() != null) {
2058 mUi.removeSubWindow(t.getSubViewContainer());
2059 }
2060 }
2061
2062 @Override
2063 public void attachSubWindow(Tab tab) {
2064 if (tab.getSubWebView() != null) {
2065 mUi.attachSubWindow(tab.getSubViewContainer());
2066 getCurrentTopWebView().requestFocus();
2067 }
2068 }
2069
Michael Kolb843510f2010-12-09 10:51:49 -08002070 @Override
2071 public Tab openTabToHomePage() {
2072 // check for max tabs
2073 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002074 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2075 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002076 } else {
2077 mUi.showMaxTabsWarning();
2078 return null;
2079 }
2080 }
2081
Michael Kolb18eb3772010-12-10 14:29:51 -08002082 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2083 if (mSettings.openInBackground() && !forceForeground) {
2084 Tab tab = mTabControl.createNewTab(false, null, null,
2085 (parent != null) && parent.isPrivateBrowsingEnabled());
2086 if (tab != null) {
2087 addTab(tab);
2088 WebView view = tab.getWebView();
2089 loadUrl(view, url);
2090 }
2091 return tab;
2092 } else {
2093 return openTabAndShow(parent, new UrlData(url), false, null);
2094 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002095 }
2096
Michael Kolb18eb3772010-12-10 14:29:51 -08002097
Michael Kolb8233fac2010-10-26 16:08:53 -07002098 // This method does a ton of stuff. It will attempt to create a new tab
2099 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2100 // url isn't null, it will load the given url.
Michael Kolb18eb3772010-12-10 14:29:51 -08002101 public Tab openTabAndShow(Tab parent, UrlData urlData, boolean closeOnExit,
Michael Kolb8233fac2010-10-26 16:08:53 -07002102 String appId) {
2103 final Tab currentTab = mTabControl.getCurrentTab();
2104 if (mTabControl.canCreateNewTab()) {
2105 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Michael Kolb18eb3772010-12-10 14:29:51 -08002106 urlData.mUrl,
2107 (parent != null) && parent.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -07002108 WebView webview = tab.getWebView();
2109 // We must set the new tab as the current tab to reflect the old
2110 // animation behavior.
2111 addTab(tab);
2112 setActiveTab(tab);
2113 if (!urlData.isEmpty()) {
2114 loadUrlDataIn(tab, urlData);
2115 }
2116 return tab;
2117 } else {
2118 // Get rid of the subwindow if it exists
2119 dismissSubWindow(currentTab);
2120 if (!urlData.isEmpty()) {
2121 // Load the given url.
2122 loadUrlDataIn(currentTab, urlData);
2123 }
2124 return currentTab;
2125 }
2126 }
2127
Michael Kolb8233fac2010-10-26 16:08:53 -07002128 @Override
2129 public Tab openIncognitoTab() {
2130 if (mTabControl.canCreateNewTab()) {
2131 Tab currentTab = mTabControl.getCurrentTab();
2132 Tab tab = mTabControl.createNewTab(false, null, null, true);
2133 addTab(tab);
2134 setActiveTab(tab);
2135 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002136 } else {
2137 mUi.showMaxTabsWarning();
2138 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002139 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002140 }
2141
2142 /**
2143 * @param index Index of the tab to change to, as defined by
2144 * mTabControl.getTabIndex(Tab t).
2145 * @return boolean True if we successfully switched to a different tab. If
2146 * the indexth tab is null, or if that tab is the same as
2147 * the current one, return false.
2148 */
2149 @Override
2150 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002151 // hide combo view if open
2152 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002153 Tab tab = mTabControl.getTab(index);
2154 Tab currentTab = mTabControl.getCurrentTab();
2155 if (tab == null || tab == currentTab) {
2156 return false;
2157 }
2158 setActiveTab(tab);
2159 return true;
2160 }
2161
2162 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002163 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002164 // hide combo view if open
2165 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002166 final Tab current = mTabControl.getCurrentTab();
2167 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002168 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002169 return;
2170 }
2171 final Tab parent = current.getParentTab();
2172 int indexToShow = -1;
2173 if (parent != null) {
2174 indexToShow = mTabControl.getTabIndex(parent);
2175 } else {
2176 final int currentIndex = mTabControl.getCurrentIndex();
2177 // Try to move to the tab to the right
2178 indexToShow = currentIndex + 1;
2179 if (indexToShow > mTabControl.getTabCount() - 1) {
2180 // Try to move to the tab to the left
2181 indexToShow = currentIndex - 1;
2182 }
2183 }
2184 if (switchToTab(indexToShow)) {
2185 // Close window
2186 closeTab(current);
2187 }
2188 }
2189
2190 /**
2191 * Close the tab, remove its associated title bar, and adjust mTabControl's
2192 * current tab to a valid value.
2193 */
2194 @Override
2195 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002196 // hide combo view if open
2197 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002198 int currentIndex = mTabControl.getCurrentIndex();
2199 int removeIndex = mTabControl.getTabIndex(tab);
2200 removeTab(tab);
2201 if (currentIndex >= removeIndex && currentIndex != 0) {
2202 currentIndex--;
2203 }
2204 Tab newtab = mTabControl.getTab(currentIndex);
2205 setActiveTab(newtab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002206 }
2207
2208 /**************** TODO: Url loading clean up *******************************/
2209
2210 // Called when loading from context menu or LOAD_URL message
2211 protected void loadUrlFromContext(WebView view, String url) {
2212 // In case the user enters nothing.
2213 if (url != null && url.length() != 0 && view != null) {
2214 url = UrlUtils.smartUrlFilter(url);
2215 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2216 loadUrl(view, url);
2217 }
2218 }
2219 }
2220
2221 /**
2222 * Load the URL into the given WebView and update the title bar
2223 * to reflect the new load. Call this instead of WebView.loadUrl
2224 * directly.
2225 * @param view The WebView used to load url.
2226 * @param url The URL to load.
2227 */
2228 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002229 view.loadUrl(url);
2230 }
2231
2232 /**
2233 * Load UrlData into a Tab and update the title bar to reflect the new
2234 * load. Call this instead of UrlData.loadIn directly.
2235 * @param t The Tab used to load.
2236 * @param data The UrlData being loaded.
2237 */
2238 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002239 data.loadIn(t);
2240 }
2241
John Reck30c714c2010-12-16 17:30:34 -08002242 @Override
2243 public void onUserCanceledSsl(Tab tab) {
2244 WebView web = tab.getWebView();
2245 // TODO: Figure out the "right" behavior
2246 if (web.canGoBack()) {
2247 web.goBack();
2248 } else {
2249 web.loadUrl(mSettings.getHomePage());
2250 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002251 }
2252
2253 void goBackOnePageOrQuit() {
2254 Tab current = mTabControl.getCurrentTab();
2255 if (current == null) {
2256 /*
2257 * Instead of finishing the activity, simply push this to the back
2258 * of the stack and let ActivityManager to choose the foreground
2259 * activity. As BrowserActivity is singleTask, it will be always the
2260 * root of the task. So we can use either true or false for
2261 * moveTaskToBack().
2262 */
2263 mActivity.moveTaskToBack(true);
2264 return;
2265 }
2266 WebView w = current.getWebView();
2267 if (w.canGoBack()) {
2268 w.goBack();
2269 } else {
2270 // Check to see if we are closing a window that was created by
2271 // another window. If so, we switch back to that window.
2272 Tab parent = current.getParentTab();
2273 if (parent != null) {
2274 switchToTab(mTabControl.getTabIndex(parent));
2275 // Now we close the other tab
2276 closeTab(current);
2277 } else {
2278 if (current.closeOnExit()) {
2279 // force the tab's inLoad() to be false as we are going to
2280 // either finish the activity or remove the tab. This will
2281 // ensure pauseWebViewTimers() taking action.
Michael Kolb70976932010-11-30 11:34:01 -08002282 current.clearInPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07002283 if (mTabControl.getTabCount() == 1) {
2284 mActivity.finish();
2285 return;
2286 }
2287 if (mActivityPaused) {
2288 Log.e(LOGTAG, "BrowserActivity is already paused "
2289 + "while handing goBackOnePageOrQuit.");
2290 }
Michael Kolb70976932010-11-30 11:34:01 -08002291 pauseWebViewTimers(current);
Michael Kolb8233fac2010-10-26 16:08:53 -07002292 removeTab(current);
2293 }
2294 /*
2295 * Instead of finishing the activity, simply push this to the back
2296 * of the stack and let ActivityManager to choose the foreground
2297 * activity. As BrowserActivity is singleTask, it will be always the
2298 * root of the task. So we can use either true or false for
2299 * moveTaskToBack().
2300 */
2301 mActivity.moveTaskToBack(true);
2302 }
2303 }
2304 }
2305
2306 /**
2307 * Feed the previously stored results strings to the BrowserProvider so that
2308 * the SearchDialog will show them instead of the standard searches.
2309 * @param result String to show on the editable line of the SearchDialog.
2310 */
2311 @Override
2312 public void showVoiceSearchResults(String result) {
2313 ContentProviderClient client = mActivity.getContentResolver()
2314 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2315 ContentProvider prov = client.getLocalContentProvider();
2316 BrowserProvider bp = (BrowserProvider) prov;
2317 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2318 client.release();
2319
2320 Bundle bundle = createGoogleSearchSourceBundle(
2321 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2322 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2323 startSearch(result, false, bundle, false);
2324 }
2325
2326 private void startSearch(String initialQuery, boolean selectInitialQuery,
2327 Bundle appSearchData, boolean globalSearch) {
2328 if (appSearchData == null) {
2329 appSearchData = createGoogleSearchSourceBundle(
2330 GOOGLE_SEARCH_SOURCE_TYPE);
2331 }
2332
2333 SearchEngine searchEngine = mSettings.getSearchEngine();
2334 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2335 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2336 }
2337 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2338 globalSearch);
2339 }
2340
2341 private Bundle createGoogleSearchSourceBundle(String source) {
2342 Bundle bundle = new Bundle();
2343 bundle.putString(Search.SOURCE, source);
2344 return bundle;
2345 }
2346
2347 /**
2348 * handle key events in browser
2349 *
2350 * @param keyCode
2351 * @param event
2352 * @return true if handled, false to pass to super
2353 */
2354 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002355 boolean noModifiers = event.hasNoModifiers();
2356
Michael Kolb8233fac2010-10-26 16:08:53 -07002357 // Even if MENU is already held down, we need to call to super to open
2358 // the IME on long press.
Cary Clark160bbb92011-01-10 11:17:07 -05002359 if (!noModifiers && KeyEvent.KEYCODE_MENU == keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002360 mMenuIsDown = true;
2361 return false;
2362 }
2363 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2364 // still down, we don't want to trigger the search. Pretend to consume
2365 // the key and do nothing.
2366 if (mMenuIsDown) return true;
2367
Cary Clark8ff8c662010-12-29 15:03:05 -05002368 WebView webView = getCurrentTopWebView();
2369 if (webView == null) return false;
2370
Cary Clark160bbb92011-01-10 11:17:07 -05002371 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2372 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002373
Michael Kolb8233fac2010-10-26 16:08:53 -07002374 switch(keyCode) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002375 case KeyEvent.KEYCODE_ESCAPE:
Cary Clark160bbb92011-01-10 11:17:07 -05002376 if (!noModifiers) break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002377 stopLoading();
2378 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07002379 case KeyEvent.KEYCODE_SPACE:
2380 // WebView/WebTextView handle the keys in the KeyDown. As
2381 // the Activity's shortcut keys are only handled when WebView
2382 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002383 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002384 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002385 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002386 pageDown();
2387 }
2388 return true;
2389 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002390 if (!noModifiers) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002391 if (event.getRepeatCount() == 0) {
2392 event.startTracking();
2393 return true;
2394 } else if (mUi.showsWeb()
2395 && event.isLongPress()) {
2396 bookmarksOrHistoryPicker(true);
2397 return true;
2398 }
2399 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002400 case KeyEvent.KEYCODE_DPAD_LEFT:
2401 if (ctrl) {
2402 webView.goBack();
2403 return true;
2404 }
2405 break;
2406 case KeyEvent.KEYCODE_DPAD_RIGHT:
2407 if (ctrl) {
2408 webView.goForward();
2409 return true;
2410 }
2411 break;
2412 case KeyEvent.KEYCODE_A:
2413 if (ctrl) {
2414 webView.selectAll();
2415 return true;
2416 }
2417 break;
2418 case KeyEvent.KEYCODE_B:
2419 if (ctrl) {
2420 bookmarksOrHistoryPicker(false);
2421 return true;
2422 }
2423 break;
2424 case KeyEvent.KEYCODE_C:
2425 if (ctrl) {
2426 webView.copySelection();
2427 return true;
2428 }
2429 break;
2430 case KeyEvent.KEYCODE_D:
2431 if (ctrl) {
2432 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
2433 return true;
2434 }
2435 break;
2436// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
2437 case KeyEvent.KEYCODE_F:
2438 if (ctrl) {
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05002439 webView.showFindDialog(null, true);
Cary Clark8ff8c662010-12-29 15:03:05 -05002440 return true;
2441 }
2442 break;
2443// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
2444 case KeyEvent.KEYCODE_H:
2445 if (ctrl) {
2446 bookmarksOrHistoryPicker(true);
2447 return true;
2448 }
2449 break;
2450// case KeyEvent.KEYCODE_I: // unused
2451 case KeyEvent.KEYCODE_J:
2452 if (ctrl) {
2453 viewDownloads();
2454 return true;
2455 }
2456 break;
2457// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
2458 case KeyEvent.KEYCODE_L:
2459 if (ctrl) {
2460 editUrl();
2461 return true;
2462 }
2463 break;
2464// case KeyEvent.KEYCODE_M: // unused
2465// case KeyEvent.KEYCODE_N: // in Chrome: new window
2466// case KeyEvent.KEYCODE_O: // in Chrome: open file
2467// case KeyEvent.KEYCODE_P: // in Chrome: print page
2468// case KeyEvent.KEYCODE_Q: // unused
2469 case KeyEvent.KEYCODE_R:
2470 if (ctrl) {
2471 if (mInLoad) {
2472 stopLoading();
2473 } else {
2474 webView.reload();
2475 }
2476 return true;
2477 }
2478 break;
2479// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2480 case KeyEvent.KEYCODE_T:
2481 if (ctrl) {
2482 if (event.isShiftPressed()) {
2483 openIncognitoTab();
2484 } else {
2485 openTabToHomePage();
2486 }
2487 return true;
2488 }
2489 break;
2490// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2491// case KeyEvent.KEYCODE_V: // text view intercepts to paste
2492 case KeyEvent.KEYCODE_W:
2493 if (ctrl) {
2494 closeCurrentTab();
2495 return true;
2496 }
2497 break;
2498// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2499// case KeyEvent.KEYCODE_Y: // unused
2500// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002501 }
2502 return false;
2503 }
2504
2505 boolean onKeyUp(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002506 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002507 switch(keyCode) {
2508 case KeyEvent.KEYCODE_MENU:
2509 mMenuIsDown = false;
2510 break;
2511 case KeyEvent.KEYCODE_BACK:
2512 if (event.isTracking() && !event.isCanceled()) {
2513 onBackKey();
2514 return true;
2515 }
2516 break;
2517 }
2518 return false;
2519 }
2520
2521 public boolean isMenuDown() {
2522 return mMenuIsDown;
2523 }
2524
Ben Murdoch8029a772010-11-16 11:58:21 +00002525 public void setupAutoFill(Message message) {
2526 // Open the settings activity at the AutoFill profile fragment so that
2527 // the user can create a new profile. When they return, we will dispatch
2528 // the message so that we can autofill the form using their new profile.
2529 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2530 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2531 AutoFillSettingsFragment.class.getName());
2532 mAutoFillSetupMessage = message;
2533 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2534 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002535}