blob: fe19927bca4a07dcee5b162768f7de462e0d7310 [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.copy_link_context_menu_id:
465 copy(url);
466 break;
467 case R.id.save_link_context_menu_id:
468 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500469 DownloadHandler.onDownloadStartNoStream(
470 mActivity, url, null, null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -0700471 break;
472 }
473 break;
474 }
475
476 case LOAD_URL:
477 loadUrlFromContext(getCurrentTopWebView(), (String) msg.obj);
478 break;
479
480 case STOP_LOAD:
481 stopLoading();
482 break;
483
484 case RELEASE_WAKELOCK:
485 if (mWakeLock.isHeld()) {
486 mWakeLock.release();
487 // if we reach here, Browser should be still in the
488 // background loading after WAKELOCK_TIMEOUT (5-min).
489 // To avoid burning the battery, stop loading.
490 mTabControl.stopAllLoading();
491 }
492 break;
493
494 case UPDATE_BOOKMARK_THUMBNAIL:
495 WebView view = (WebView) msg.obj;
496 if (view != null) {
497 updateScreenshot(view);
498 }
499 break;
500 }
501 }
502 };
503
504 }
505
Michael Kolbba99c5d2010-11-29 14:57:41 -0800506 @Override
507 public void shareCurrentPage() {
508 shareCurrentPage(mTabControl.getCurrentTab());
509 }
510
511 private void shareCurrentPage(Tab tab) {
512 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800513 sharePage(mActivity, tab.getTitle(),
514 tab.getUrl(), tab.getFavicon(),
515 createScreenshot(tab.getWebView(),
516 getDesiredThumbnailWidth(mActivity),
517 getDesiredThumbnailHeight(mActivity)));
518 }
519 }
520
Michael Kolb8233fac2010-10-26 16:08:53 -0700521 /**
522 * Share a page, providing the title, url, favicon, and a screenshot. Uses
523 * an {@link Intent} to launch the Activity chooser.
524 * @param c Context used to launch a new Activity.
525 * @param title Title of the page. Stored in the Intent with
526 * {@link Intent#EXTRA_SUBJECT}
527 * @param url URL of the page. Stored in the Intent with
528 * {@link Intent#EXTRA_TEXT}
529 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
530 * with {@link Browser#EXTRA_SHARE_FAVICON}
531 * @param screenshot Bitmap of a screenshot of the page. Stored in the
532 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
533 */
534 static final void sharePage(Context c, String title, String url,
535 Bitmap favicon, Bitmap screenshot) {
536 Intent send = new Intent(Intent.ACTION_SEND);
537 send.setType("text/plain");
538 send.putExtra(Intent.EXTRA_TEXT, url);
539 send.putExtra(Intent.EXTRA_SUBJECT, title);
540 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
541 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
542 try {
543 c.startActivity(Intent.createChooser(send, c.getString(
544 R.string.choosertitle_sharevia)));
545 } catch(android.content.ActivityNotFoundException ex) {
546 // if no app handles it, do nothing
547 }
548 }
549
550 private void copy(CharSequence text) {
551 ClipboardManager cm = (ClipboardManager) mActivity
552 .getSystemService(Context.CLIPBOARD_SERVICE);
553 cm.setText(text);
554 }
555
556 // lifecycle
557
558 protected void onConfgurationChanged(Configuration config) {
559 mConfigChanged = true;
560 if (mPageDialogsHandler != null) {
561 mPageDialogsHandler.onConfigurationChanged(config);
562 }
563 mUi.onConfigurationChanged(config);
564 }
565
566 @Override
567 public void handleNewIntent(Intent intent) {
568 mIntentHandler.onNewIntent(intent);
569 }
570
571 protected void onPause() {
572 if (mActivityPaused) {
573 Log.e(LOGTAG, "BrowserActivity is already paused.");
574 return;
575 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700576 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800577 Tab tab = mTabControl.getCurrentTab();
578 if (tab != null) {
579 tab.pause();
580 if (!pauseWebViewTimers(tab)) {
581 mWakeLock.acquire();
582 mHandler.sendMessageDelayed(mHandler
583 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
584 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700585 }
586 mUi.onPause();
587 mNetworkHandler.onPause();
588
589 WebView.disablePlatformNotifications();
590 }
591
592 void onSaveInstanceState(Bundle outState) {
593 // the default implementation requires each view to have an id. As the
594 // browser handles the state itself and it doesn't use id for the views,
595 // don't call the default implementation. Otherwise it will trigger the
596 // warning like this, "couldn't save which view has focus because the
597 // focused view XXX has no id".
598
599 // Save all the tabs
600 mTabControl.saveState(outState);
601 // Save time so that we know how old incognito tabs (if any) are.
602 outState.putSerializable("lastActiveDate", Calendar.getInstance());
603 }
604
605 void onResume() {
606 if (!mActivityPaused) {
607 Log.e(LOGTAG, "BrowserActivity is already resumed.");
608 return;
609 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700610 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800611 Tab current = mTabControl.getCurrentTab();
612 if (current != null) {
613 current.resume();
614 resumeWebViewTimers(current);
615 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700616 if (mWakeLock.isHeld()) {
617 mHandler.removeMessages(RELEASE_WAKELOCK);
618 mWakeLock.release();
619 }
620 mUi.onResume();
621 mNetworkHandler.onResume();
622 WebView.enablePlatformNotifications();
623 }
624
Michael Kolb70976932010-11-30 11:34:01 -0800625 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800626 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800627 * @param tab guaranteed non-null
628 */
629 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700630 boolean inLoad = tab.inPageLoad();
631 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
632 CookieSyncManager.getInstance().startSync();
633 WebView w = tab.getWebView();
634 if (w != null) {
635 w.resumeTimers();
636 }
637 }
638 }
639
Michael Kolb70976932010-11-30 11:34:01 -0800640 /**
641 * Pause all WebView timers using the WebView of the given tab
642 * @param tab
643 * @return true if the timers are paused or tab is null
644 */
645 private boolean pauseWebViewTimers(Tab tab) {
646 if (tab == null) {
647 return true;
648 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700649 CookieSyncManager.getInstance().stopSync();
650 WebView w = getCurrentWebView();
651 if (w != null) {
652 w.pauseTimers();
653 }
654 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700655 }
Michael Kolb70976932010-11-30 11:34:01 -0800656 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700657 }
658
659 void onDestroy() {
660 if (mUploadHandler != null) {
661 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
662 mUploadHandler = null;
663 }
664 if (mTabControl == null) return;
665 mUi.onDestroy();
666 // Remove the current tab and sub window
667 Tab t = mTabControl.getCurrentTab();
668 if (t != null) {
669 dismissSubWindow(t);
670 removeTab(t);
671 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500672 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700673 // Destroy all the tabs
674 mTabControl.destroy();
675 WebIconDatabase.getInstance().close();
676 // Stop watching the default geolocation permissions
677 mSystemAllowGeolocationOrigins.stop();
678 mSystemAllowGeolocationOrigins = null;
679 }
680
681 protected boolean isActivityPaused() {
682 return mActivityPaused;
683 }
684
685 protected void onLowMemory() {
686 mTabControl.freeMemory();
687 }
688
689 @Override
690 public boolean shouldShowErrorConsole() {
691 return mShouldShowErrorConsole;
692 }
693
694 protected void setShouldShowErrorConsole(boolean show) {
695 if (show == mShouldShowErrorConsole) {
696 // Nothing to do.
697 return;
698 }
699 mShouldShowErrorConsole = show;
700 Tab t = mTabControl.getCurrentTab();
701 if (t == null) {
702 // There is no current tab so we cannot toggle the error console
703 return;
704 }
705 mUi.setShouldShowErrorConsole(t, show);
706 }
707
708 @Override
709 public void stopLoading() {
710 mLoadStopped = true;
711 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700712 WebView w = getCurrentTopWebView();
713 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700714 mUi.onPageStopped(tab);
715 }
716
717 boolean didUserStopLoading() {
718 return mLoadStopped;
719 }
720
721 // WebViewController
722
723 @Override
John Reck324d4402011-01-11 16:56:42 -0800724 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700725
726 // We've started to load a new page. If there was a pending message
727 // to save a screenshot then we will now take the new page and save
728 // an incorrect screenshot. Therefore, remove any pending thumbnail
729 // messages from the queue.
730 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
731 view);
732
733 // reset sync timer to avoid sync starts during loading a page
734 CookieSyncManager.getInstance().resetSync();
735
736 if (!mNetworkHandler.isNetworkUp()) {
737 view.setNetworkAvailable(false);
738 }
739
740 // when BrowserActivity just starts, onPageStarted may be called before
741 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
742 // to start the timer. As we won't switch tabs while an activity is in
743 // pause state, we can ensure calling resume and pause in pair.
744 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800745 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700746 }
747 mLoadStopped = false;
748 if (!mNetworkHandler.isNetworkUp()) {
749 mNetworkHandler.createAndShowNetworkDialog();
750 }
751 endActionMode();
752
John Reck30c714c2010-12-16 17:30:34 -0800753 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700754
John Reck324d4402011-01-11 16:56:42 -0800755 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700756 // update the bookmark database for favicon
757 maybeUpdateFavicon(tab, null, url, favicon);
758
759 Performance.tracePageStart(url);
760
761 // Performance probe
762 if (false) {
763 Performance.onPageStarted();
764 }
765
766 }
767
768 @Override
John Reck324d4402011-01-11 16:56:42 -0800769 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800770 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800771 if (!tab.isPrivateBrowsingEnabled()
772 && !TextUtils.isEmpty(tab.getUrl())) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700773 if (tab.inForeground() && !didUserStopLoading()
774 || !tab.inForeground()) {
775 // Only update the bookmark screenshot if the user did not
776 // cancel the load early.
777 mHandler.sendMessageDelayed(mHandler.obtainMessage(
778 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab.getWebView()),
779 500);
780 }
781 }
782 // pause the WebView timer and release the wake lock if it is finished
783 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800784 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700785 if (mWakeLock.isHeld()) {
786 mHandler.removeMessages(RELEASE_WAKELOCK);
787 mWakeLock.release();
788 }
789 }
790 // Performance probe
791 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800792 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700793 }
794
795 Performance.tracePageFinished();
796 }
797
798 @Override
John Reck30c714c2010-12-16 17:30:34 -0800799 public void onProgressChanged(Tab tab) {
800 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700801
802 if (newProgress == 100) {
803 CookieSyncManager.getInstance().sync();
804 // onProgressChanged() may continue to be called after the main
805 // frame has finished loading, as any remaining sub frames continue
806 // to load. We'll only get called once though with newProgress as
807 // 100 when everything is loaded. (onPageFinished is called once
808 // when the main frame completes loading regardless of the state of
809 // any sub frames so calls to onProgressChanges may continue after
810 // onPageFinished has executed)
811 if (mInLoad) {
812 mInLoad = false;
813 updateInLoadMenuItems(mCachedMenu);
814 }
815 } else {
816 if (!mInLoad) {
817 // onPageFinished may have already been called but a subframe is
818 // still loading and updating the progress. Reset mInLoad and
819 // update the menu items.
820 mInLoad = true;
821 updateInLoadMenuItems(mCachedMenu);
822 }
823 }
John Reck30c714c2010-12-16 17:30:34 -0800824 mUi.onProgressChanged(tab);
825 }
826
827 @Override
828 public void onUpdatedLockIcon(Tab tab) {
829 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700830 }
831
832 @Override
833 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800834 mUi.onTabDataChanged(tab);
835 final String pageUrl = tab.getUrl();
John Reck324d4402011-01-11 16:56:42 -0800836 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700837 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
838 return;
839 }
840 // Update the title in the history database if not in private browsing mode
841 if (!tab.isPrivateBrowsingEnabled()) {
John Reck0ebd3ac2010-12-09 11:14:04 -0800842 mDataController.updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700843 }
844 }
845
846 @Override
847 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800848 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700849 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
850 }
851
852 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800853 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
854 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700855 }
856
857 @Override
858 public boolean shouldOverrideKeyEvent(KeyEvent event) {
859 if (mMenuIsDown) {
860 // only check shortcut key when MENU is held
861 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
862 event);
863 } else {
864 return false;
865 }
866 }
867
868 @Override
869 public void onUnhandledKeyEvent(KeyEvent event) {
870 if (!isActivityPaused()) {
871 if (event.getAction() == KeyEvent.ACTION_DOWN) {
872 mActivity.onKeyDown(event.getKeyCode(), event);
873 } else {
874 mActivity.onKeyUp(event.getKeyCode(), event);
875 }
876 }
877 }
878
879 @Override
John Reck324d4402011-01-11 16:56:42 -0800880 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700881 // Don't save anything in private browsing mode
882 if (tab.isPrivateBrowsingEnabled()) return;
John Reck324d4402011-01-11 16:56:42 -0800883 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700884
John Reck324d4402011-01-11 16:56:42 -0800885 if (TextUtils.isEmpty(url)
886 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700887 return;
888 }
John Reck0ebd3ac2010-12-09 11:14:04 -0800889 mDataController.updateVisitedHistory(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700890 WebIconDatabase.getInstance().retainIconForPageUrl(url);
891 }
892
893 @Override
894 public void getVisitedHistory(final ValueCallback<String[]> callback) {
895 AsyncTask<Void, Void, String[]> task =
896 new AsyncTask<Void, Void, String[]>() {
897 @Override
898 public String[] doInBackground(Void... unused) {
899 return Browser.getVisitedHistory(mActivity.getContentResolver());
900 }
901 @Override
902 public void onPostExecute(String[] result) {
903 callback.onReceiveValue(result);
904 }
905 };
906 task.execute();
907 }
908
909 @Override
910 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
911 final HttpAuthHandler handler, final String host,
912 final String realm) {
913 String username = null;
914 String password = null;
915
916 boolean reuseHttpAuthUsernamePassword
917 = handler.useHttpAuthUsernamePassword();
918
919 if (reuseHttpAuthUsernamePassword && view != null) {
920 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
921 if (credentials != null && credentials.length == 2) {
922 username = credentials[0];
923 password = credentials[1];
924 }
925 }
926
927 if (username != null && password != null) {
928 handler.proceed(username, password);
929 } else {
930 if (tab.inForeground()) {
931 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
932 } else {
933 handler.cancel();
934 }
935 }
936 }
937
938 @Override
939 public void onDownloadStart(Tab tab, String url, String userAgent,
940 String contentDisposition, String mimetype, long contentLength) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500941 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
942 contentDisposition, mimetype);
Michael Kolb8233fac2010-10-26 16:08:53 -0700943 if (tab.getWebView().copyBackForwardList().getSize() == 0) {
944 // This Tab was opened for the sole purpose of downloading a
945 // file. Remove it.
946 if (tab == mTabControl.getCurrentTab()) {
947 // In this case, the Tab is still on top.
948 goBackOnePageOrQuit();
949 } else {
950 // In this case, it is not.
951 closeTab(tab);
952 }
953 }
954 }
955
956 @Override
957 public Bitmap getDefaultVideoPoster() {
958 return mUi.getDefaultVideoPoster();
959 }
960
961 @Override
962 public View getVideoLoadingProgressView() {
963 return mUi.getVideoLoadingProgressView();
964 }
965
966 @Override
967 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
968 SslError error) {
969 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
970 }
971
972 // helper method
973
974 /*
975 * Update the favorites icon if the private browsing isn't enabled and the
976 * icon is valid.
977 */
978 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
979 final String url, Bitmap favicon) {
980 if (favicon == null) {
981 return;
982 }
983 if (!tab.isPrivateBrowsingEnabled()) {
984 Bookmarks.updateFavicon(mActivity
985 .getContentResolver(), originalUrl, url, favicon);
986 }
987 }
988
Leon Scroggins4cd97792010-12-03 15:31:56 -0500989 @Override
990 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -0800991 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -0500992 mUi.bookmarkedStatusHasChanged(tab);
993 }
994
Michael Kolb8233fac2010-10-26 16:08:53 -0700995 // end WebViewController
996
997 protected void pageUp() {
998 getCurrentTopWebView().pageUp(false);
999 }
1000
1001 protected void pageDown() {
1002 getCurrentTopWebView().pageDown(false);
1003 }
1004
1005 // callback from phone title bar
1006 public void editUrl() {
1007 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
1008 String url = (getCurrentTopWebView() == null) ? null : getCurrentTopWebView().getUrl();
1009 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1010 null, false);
1011 }
1012
Michael Kolbcfa3af52010-12-14 10:36:11 -08001013 public void startVoiceSearch() {
1014 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1015 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1016 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1017 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1018 mActivity.getComponentName().flattenToString());
1019 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001020 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001021 mActivity.startActivity(intent);
1022 }
1023
Michael Kolb8233fac2010-10-26 16:08:53 -07001024 public void activateVoiceSearchMode(String title) {
1025 mUi.showVoiceTitleBar(title);
1026 }
1027
1028 public void revertVoiceSearchMode(Tab tab) {
1029 mUi.revertVoiceTitleBar(tab);
1030 }
1031
1032 public void showCustomView(Tab tab, View view,
1033 WebChromeClient.CustomViewCallback callback) {
1034 if (tab.inForeground()) {
1035 if (mUi.isCustomViewShowing()) {
1036 callback.onCustomViewHidden();
1037 return;
1038 }
1039 mUi.showCustomView(view, callback);
1040 // Save the menu state and set it to empty while the custom
1041 // view is showing.
1042 mOldMenuState = mMenuState;
1043 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001044 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001045 }
1046 }
1047
1048 @Override
1049 public void hideCustomView() {
1050 if (mUi.isCustomViewShowing()) {
1051 mUi.onHideCustomView();
1052 // Reset the old menu state.
1053 mMenuState = mOldMenuState;
1054 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001055 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001056 }
1057 }
1058
1059 protected void onActivityResult(int requestCode, int resultCode,
1060 Intent intent) {
1061 if (getCurrentTopWebView() == null) return;
1062 switch (requestCode) {
1063 case PREFERENCES_PAGE:
1064 if (resultCode == Activity.RESULT_OK && intent != null) {
1065 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
1066 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
1067 mTabControl.removeParentChildRelationShips();
1068 }
1069 }
1070 break;
1071 case FILE_SELECTED:
1072 // Choose a file from the file picker.
1073 if (null == mUploadHandler) break;
1074 mUploadHandler.onResult(resultCode, intent);
1075 mUploadHandler = null;
1076 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001077 case AUTOFILL_SETUP:
1078 // Determine whether a profile was actually set up or not
1079 // and if so, send the message back to the WebTextView to
1080 // fill the form with the new profile.
1081 if (getSettings().getAutoFillProfile() != null) {
1082 mAutoFillSetupMessage.sendToTarget();
1083 mAutoFillSetupMessage = null;
1084 }
1085 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001086 default:
1087 break;
1088 }
1089 getCurrentTopWebView().requestFocus();
1090 }
1091
1092 /**
1093 * Open the Go page.
1094 * @param startWithHistory If true, open starting on the history tab.
1095 * Otherwise, start with the bookmarks tab.
1096 */
1097 @Override
1098 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1099 if (mTabControl.getCurrentWebView() == null) {
1100 return;
1101 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001102 // clear action mode
1103 if (isInCustomActionMode()) {
1104 endActionMode();
1105 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001106 Bundle extras = new Bundle();
1107 // Disable opening in a new window if we have maxed out the windows
1108 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1109 !mTabControl.canCreateNewTab());
1110 mUi.showComboView(startWithHistory, extras);
1111 }
1112
1113 // combo view callbacks
1114
1115 /**
1116 * callback from ComboPage when clear history is requested
1117 */
1118 public void onRemoveParentChildRelationships() {
1119 mTabControl.removeParentChildRelationShips();
1120 }
1121
1122 /**
1123 * callback from ComboPage when bookmark/history selection
1124 */
1125 @Override
1126 public void onUrlSelected(String url, boolean newTab) {
1127 removeComboView();
1128 if (!TextUtils.isEmpty(url)) {
1129 if (newTab) {
Michael Kolb18eb3772010-12-10 14:29:51 -08001130 openTab(mTabControl.getCurrentTab(), url, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001131 } else {
1132 final Tab currentTab = mTabControl.getCurrentTab();
1133 dismissSubWindow(currentTab);
1134 loadUrl(getCurrentTopWebView(), url);
1135 }
1136 }
1137 }
1138
1139 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07001140 * dismiss the ComboPage
1141 */
1142 @Override
1143 public void removeComboView() {
1144 mUi.hideComboView();
1145 }
1146
1147 // active tabs page handling
1148
1149 protected void showActiveTabsPage() {
1150 mMenuState = EMPTY_MENU;
1151 mUi.showActiveTabsPage();
1152 }
1153
1154 /**
1155 * Remove the active tabs page.
1156 * @param needToAttach If true, the active tabs page did not attach a tab
1157 * to the content view, so we need to do that here.
1158 */
1159 @Override
1160 public void removeActiveTabsPage(boolean needToAttach) {
1161 mMenuState = R.id.MAIN_MENU;
1162 mUi.removeActiveTabsPage();
1163 if (needToAttach) {
1164 setActiveTab(mTabControl.getCurrentTab());
1165 }
1166 getCurrentTopWebView().requestFocus();
1167 }
1168
1169 // key handling
1170 protected void onBackKey() {
1171 if (!mUi.onBackKey()) {
1172 WebView subwindow = mTabControl.getCurrentSubWindow();
1173 if (subwindow != null) {
1174 if (subwindow.canGoBack()) {
1175 subwindow.goBack();
1176 } else {
1177 dismissSubWindow(mTabControl.getCurrentTab());
1178 }
1179 } else {
1180 goBackOnePageOrQuit();
1181 }
1182 }
1183 }
1184
1185 // menu handling and state
1186 // TODO: maybe put into separate handler
1187
1188 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckd73c5a22010-12-22 10:22:50 -08001189 if (mMenuState == EMPTY_MENU) {
1190 return false;
1191 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001192 MenuInflater inflater = mActivity.getMenuInflater();
1193 inflater.inflate(R.menu.browser, menu);
1194 updateInLoadMenuItems(menu);
1195 // hold on to the menu reference here; it is used by the page callbacks
1196 // to update the menu based on loading state
1197 mCachedMenu = menu;
1198 return true;
1199 }
1200
1201 protected void onCreateContextMenu(ContextMenu menu, View v,
1202 ContextMenuInfo menuInfo) {
1203 if (v instanceof TitleBarBase) {
1204 return;
1205 }
1206 if (!(v instanceof WebView)) {
1207 return;
1208 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001209 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001210 WebView.HitTestResult result = webview.getHitTestResult();
1211 if (result == null) {
1212 return;
1213 }
1214
1215 int type = result.getType();
1216 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1217 Log.w(LOGTAG,
1218 "We should not show context menu when nothing is touched");
1219 return;
1220 }
1221 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1222 // let TextView handles context menu
1223 return;
1224 }
1225
1226 // Note, http://b/issue?id=1106666 is requesting that
1227 // an inflated menu can be used again. This is not available
1228 // yet, so inflate each time (yuk!)
1229 MenuInflater inflater = mActivity.getMenuInflater();
1230 inflater.inflate(R.menu.browsercontext, menu);
1231
1232 // Show the correct menu group
1233 final String extra = result.getExtra();
1234 menu.setGroupVisible(R.id.PHONE_MENU,
1235 type == WebView.HitTestResult.PHONE_TYPE);
1236 menu.setGroupVisible(R.id.EMAIL_MENU,
1237 type == WebView.HitTestResult.EMAIL_TYPE);
1238 menu.setGroupVisible(R.id.GEO_MENU,
1239 type == WebView.HitTestResult.GEO_TYPE);
1240 menu.setGroupVisible(R.id.IMAGE_MENU,
1241 type == WebView.HitTestResult.IMAGE_TYPE
1242 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1243 menu.setGroupVisible(R.id.ANCHOR_MENU,
1244 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1245 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001246 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1247 || type == WebView.HitTestResult.PHONE_TYPE
1248 || type == WebView.HitTestResult.EMAIL_TYPE
1249 || type == WebView.HitTestResult.GEO_TYPE;
1250 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1251 if (hitText) {
1252 menu.findItem(R.id.select_text_menu_id)
1253 .setOnMenuItemClickListener(new SelectText(webview));
1254 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001255 // Setup custom handling depending on the type
1256 switch (type) {
1257 case WebView.HitTestResult.PHONE_TYPE:
1258 menu.setHeaderTitle(Uri.decode(extra));
1259 menu.findItem(R.id.dial_context_menu_id).setIntent(
1260 new Intent(Intent.ACTION_VIEW, Uri
1261 .parse(WebView.SCHEME_TEL + extra)));
1262 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1263 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1264 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1265 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1266 addIntent);
1267 menu.findItem(R.id.copy_phone_context_menu_id)
1268 .setOnMenuItemClickListener(
1269 new Copy(extra));
1270 break;
1271
1272 case WebView.HitTestResult.EMAIL_TYPE:
1273 menu.setHeaderTitle(extra);
1274 menu.findItem(R.id.email_context_menu_id).setIntent(
1275 new Intent(Intent.ACTION_VIEW, Uri
1276 .parse(WebView.SCHEME_MAILTO + extra)));
1277 menu.findItem(R.id.copy_mail_context_menu_id)
1278 .setOnMenuItemClickListener(
1279 new Copy(extra));
1280 break;
1281
1282 case WebView.HitTestResult.GEO_TYPE:
1283 menu.setHeaderTitle(extra);
1284 menu.findItem(R.id.map_context_menu_id).setIntent(
1285 new Intent(Intent.ACTION_VIEW, Uri
1286 .parse(WebView.SCHEME_GEO
1287 + URLEncoder.encode(extra))));
1288 menu.findItem(R.id.copy_geo_context_menu_id)
1289 .setOnMenuItemClickListener(
1290 new Copy(extra));
1291 break;
1292
1293 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1294 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001295 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001296 // decide whether to show the open link in new tab option
1297 boolean showNewTab = mTabControl.canCreateNewTab();
1298 MenuItem newTabItem
1299 = menu.findItem(R.id.open_newtab_context_menu_id);
Michael Kolb2dd65c82011-01-14 11:07:38 -08001300 newTabItem.setTitle(
1301 BrowserSettings.getInstance().openInBackground()
1302 ? R.string.contextmenu_openlink_newwindow_background
1303 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001304 newTabItem.setVisible(showNewTab);
1305 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001306 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1307 newTabItem.setOnMenuItemClickListener(
1308 new MenuItem.OnMenuItemClickListener() {
1309 @Override
1310 public boolean onMenuItemClick(MenuItem item) {
1311 final HashMap<String, WebView> hrefMap =
1312 new HashMap<String, WebView>();
1313 hrefMap.put("webview", webview);
1314 final Message msg = mHandler.obtainMessage(
1315 FOCUS_NODE_HREF,
1316 R.id.open_newtab_context_menu_id,
1317 0, hrefMap);
1318 webview.requestFocusNodeHref(msg);
1319 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001320 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001321 });
1322 } else {
1323 newTabItem.setOnMenuItemClickListener(
1324 new MenuItem.OnMenuItemClickListener() {
1325 @Override
1326 public boolean onMenuItemClick(MenuItem item) {
1327 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -08001328 final Tab newTab = openTab(parent,
1329 extra, false);
Leon Scroggins026f2542010-11-22 13:26:12 -05001330 if (newTab != parent) {
1331 parent.addChildTab(newTab);
1332 }
1333 return true;
1334 }
1335 });
1336 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001337 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001338 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1339 break;
1340 }
1341 // otherwise fall through to handle image part
1342 case WebView.HitTestResult.IMAGE_TYPE:
1343 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1344 menu.setHeaderTitle(extra);
1345 }
1346 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1347 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1348 menu.findItem(R.id.download_context_menu_id).
Leon Scroggins63c02662010-11-18 15:16:27 -05001349 setOnMenuItemClickListener(new Download(mActivity, extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001350 menu.findItem(R.id.set_wallpaper_context_menu_id).
1351 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1352 extra));
1353 break;
1354
1355 default:
1356 Log.w(LOGTAG, "We should not get here.");
1357 break;
1358 }
1359 //update the ui
1360 mUi.onContextMenuCreated(menu);
1361 }
1362
1363 /**
1364 * As the menu can be open when loading state changes
1365 * we must manually update the state of the stop/reload menu
1366 * item
1367 */
1368 private void updateInLoadMenuItems(Menu menu) {
1369 if (menu == null) {
1370 return;
1371 }
1372 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1373 MenuItem src = mInLoad ?
1374 menu.findItem(R.id.stop_menu_id):
1375 menu.findItem(R.id.reload_menu_id);
1376 if (src != null) {
1377 dest.setIcon(src.getIcon());
1378 dest.setTitle(src.getTitle());
1379 }
1380 }
1381
1382 boolean prepareOptionsMenu(Menu menu) {
1383 // This happens when the user begins to hold down the menu key, so
1384 // allow them to chord to get a shortcut.
1385 mCanChord = true;
1386 // Note: setVisible will decide whether an item is visible; while
1387 // setEnabled() will decide whether an item is enabled, which also means
1388 // whether the matching shortcut key will function.
1389 switch (mMenuState) {
1390 case EMPTY_MENU:
1391 if (mCurrentMenuState != mMenuState) {
1392 menu.setGroupVisible(R.id.MAIN_MENU, false);
1393 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1394 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1395 }
1396 break;
1397 default:
1398 if (mCurrentMenuState != mMenuState) {
1399 menu.setGroupVisible(R.id.MAIN_MENU, true);
1400 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1401 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1402 }
1403 final WebView w = getCurrentTopWebView();
1404 boolean canGoBack = false;
1405 boolean canGoForward = false;
1406 boolean isHome = false;
1407 if (w != null) {
1408 canGoBack = w.canGoBack();
1409 canGoForward = w.canGoForward();
1410 isHome = mSettings.getHomePage().equals(w.getUrl());
1411 }
1412 final MenuItem back = menu.findItem(R.id.back_menu_id);
1413 back.setEnabled(canGoBack);
1414
1415 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1416 home.setEnabled(!isHome);
1417
1418 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1419 forward.setEnabled(canGoForward);
1420
1421 // decide whether to show the share link option
1422 PackageManager pm = mActivity.getPackageManager();
1423 Intent send = new Intent(Intent.ACTION_SEND);
1424 send.setType("text/plain");
1425 ResolveInfo ri = pm.resolveActivity(send,
1426 PackageManager.MATCH_DEFAULT_ONLY);
1427 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1428
1429 boolean isNavDump = mSettings.isNavDump();
1430 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1431 nav.setVisible(isNavDump);
1432 nav.setEnabled(isNavDump);
1433
1434 boolean showDebugSettings = mSettings.showDebugSettings();
1435 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1436 counter.setVisible(showDebugSettings);
1437 counter.setEnabled(showDebugSettings);
1438
1439 // allow the ui to adjust state based settings
1440 mUi.onPrepareOptionsMenu(menu);
1441
1442 break;
1443 }
1444 mCurrentMenuState = mMenuState;
1445 return true;
1446 }
1447
1448 public boolean onOptionsItemSelected(MenuItem item) {
1449 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1450 // menu remains active, so ensure comboview is dismissed
1451 // if main menu option is selected
1452 removeComboView();
1453 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001454 if (!mCanChord) {
1455 // The user has already fired a shortcut with this hold down of the
1456 // menu key.
1457 return false;
1458 }
1459 if (null == getCurrentTopWebView()) {
1460 return false;
1461 }
1462 if (mMenuIsDown) {
1463 // The shortcut action consumes the MENU. Even if it is still down,
1464 // it won't trigger the next shortcut action. In the case of the
1465 // shortcut action triggering a new activity, like Bookmarks, we
1466 // won't get onKeyUp for MENU. So it is important to reset it here.
1467 mMenuIsDown = false;
1468 }
1469 switch (item.getItemId()) {
1470 // -- Main menu
1471 case R.id.new_tab_menu_id:
1472 openTabToHomePage();
1473 break;
1474
1475 case R.id.incognito_menu_id:
1476 openIncognitoTab();
1477 break;
1478
1479 case R.id.goto_menu_id:
1480 editUrl();
1481 break;
1482
1483 case R.id.bookmarks_menu_id:
1484 bookmarksOrHistoryPicker(false);
1485 break;
1486
1487 case R.id.active_tabs_menu_id:
1488 showActiveTabsPage();
1489 break;
1490
1491 case R.id.add_bookmark_menu_id:
1492 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
1493 break;
1494
1495 case R.id.stop_reload_menu_id:
1496 if (mInLoad) {
1497 stopLoading();
1498 } else {
1499 getCurrentTopWebView().reload();
1500 }
1501 break;
1502
1503 case R.id.back_menu_id:
1504 getCurrentTopWebView().goBack();
1505 break;
1506
1507 case R.id.forward_menu_id:
1508 getCurrentTopWebView().goForward();
1509 break;
1510
1511 case R.id.close_menu_id:
1512 // Close the subwindow if it exists.
1513 if (mTabControl.getCurrentSubWindow() != null) {
1514 dismissSubWindow(mTabControl.getCurrentTab());
1515 break;
1516 }
1517 closeCurrentTab();
1518 break;
1519
1520 case R.id.homepage_menu_id:
1521 Tab current = mTabControl.getCurrentTab();
1522 if (current != null) {
1523 dismissSubWindow(current);
1524 loadUrl(current.getWebView(), mSettings.getHomePage());
1525 }
1526 break;
1527
1528 case R.id.preferences_menu_id:
1529 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1530 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1531 getCurrentTopWebView().getUrl());
1532 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1533 break;
1534
1535 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001536 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001537 break;
1538
1539 case R.id.page_info_menu_id:
1540 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1541 false);
1542 break;
1543
1544 case R.id.classic_history_menu_id:
1545 bookmarksOrHistoryPicker(true);
1546 break;
1547
1548 case R.id.title_bar_share_page_url:
1549 case R.id.share_page_menu_id:
1550 Tab currentTab = mTabControl.getCurrentTab();
1551 if (null == currentTab) {
1552 mCanChord = false;
1553 return false;
1554 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001555 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001556 break;
1557
1558 case R.id.dump_nav_menu_id:
1559 getCurrentTopWebView().debugDump();
1560 break;
1561
1562 case R.id.dump_counters_menu_id:
1563 getCurrentTopWebView().dumpV8Counters();
1564 break;
1565
1566 case R.id.zoom_in_menu_id:
1567 getCurrentTopWebView().zoomIn();
1568 break;
1569
1570 case R.id.zoom_out_menu_id:
1571 getCurrentTopWebView().zoomOut();
1572 break;
1573
1574 case R.id.view_downloads_menu_id:
1575 viewDownloads();
1576 break;
1577
1578 case R.id.window_one_menu_id:
1579 case R.id.window_two_menu_id:
1580 case R.id.window_three_menu_id:
1581 case R.id.window_four_menu_id:
1582 case R.id.window_five_menu_id:
1583 case R.id.window_six_menu_id:
1584 case R.id.window_seven_menu_id:
1585 case R.id.window_eight_menu_id:
1586 {
1587 int menuid = item.getItemId();
1588 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1589 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1590 Tab desiredTab = mTabControl.getTab(id);
1591 if (desiredTab != null &&
1592 desiredTab != mTabControl.getCurrentTab()) {
1593 switchToTab(id);
1594 }
1595 break;
1596 }
1597 }
1598 }
1599 break;
1600
1601 default:
1602 return false;
1603 }
1604 mCanChord = false;
1605 return true;
1606 }
1607
1608 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001609 // Let the History and Bookmark fragments handle menus they created.
1610 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1611 return false;
1612 }
1613
Michael Kolb8233fac2010-10-26 16:08:53 -07001614 // chording is not an issue with context menus, but we use the same
1615 // options selector, so set mCanChord to true so we can access them.
1616 mCanChord = true;
1617 int id = item.getItemId();
1618 boolean result = true;
1619 switch (id) {
1620 // For the context menu from the title bar
1621 case R.id.title_bar_copy_page_url:
1622 Tab currentTab = mTabControl.getCurrentTab();
1623 if (null == currentTab) {
1624 result = false;
1625 break;
1626 }
1627 WebView mainView = currentTab.getWebView();
1628 if (null == mainView) {
1629 result = false;
1630 break;
1631 }
1632 copy(mainView.getUrl());
1633 break;
1634 // -- Browser context menu
1635 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001636 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001637 case R.id.copy_link_context_menu_id:
1638 final WebView webView = getCurrentTopWebView();
1639 if (null == webView) {
1640 result = false;
1641 break;
1642 }
1643 final HashMap<String, WebView> hrefMap =
1644 new HashMap<String, WebView>();
1645 hrefMap.put("webview", webView);
1646 final Message msg = mHandler.obtainMessage(
1647 FOCUS_NODE_HREF, id, 0, hrefMap);
1648 webView.requestFocusNodeHref(msg);
1649 break;
1650
1651 default:
1652 // For other context menus
1653 result = onOptionsItemSelected(item);
1654 }
1655 mCanChord = false;
1656 return result;
1657 }
1658
1659 /**
1660 * support programmatically opening the context menu
1661 */
1662 public void openContextMenu(View view) {
1663 mActivity.openContextMenu(view);
1664 }
1665
1666 /**
1667 * programmatically open the options menu
1668 */
1669 public void openOptionsMenu() {
1670 mActivity.openOptionsMenu();
1671 }
1672
1673 public boolean onMenuOpened(int featureId, Menu menu) {
1674 if (mOptionsMenuOpen) {
1675 if (mConfigChanged) {
1676 // We do not need to make any changes to the state of the
1677 // title bar, since the only thing that happened was a
1678 // change in orientation
1679 mConfigChanged = false;
1680 } else {
1681 if (!mExtendedMenuOpen) {
1682 mExtendedMenuOpen = true;
1683 mUi.onExtendedMenuOpened();
1684 } else {
1685 // Switching the menu back to icon view, so show the
1686 // title bar once again.
1687 mExtendedMenuOpen = false;
1688 mUi.onExtendedMenuClosed(mInLoad);
1689 mUi.onOptionsMenuOpened();
1690 }
1691 }
1692 } else {
1693 // The options menu is closed, so open it, and show the title
1694 mOptionsMenuOpen = true;
1695 mConfigChanged = false;
1696 mExtendedMenuOpen = false;
1697 mUi.onOptionsMenuOpened();
1698 }
1699 return true;
1700 }
1701
1702 public void onOptionsMenuClosed(Menu menu) {
1703 mOptionsMenuOpen = false;
1704 mUi.onOptionsMenuClosed(mInLoad);
1705 }
1706
1707 public void onContextMenuClosed(Menu menu) {
1708 mUi.onContextMenuClosed(menu, mInLoad);
1709 }
1710
1711 // Helper method for getting the top window.
1712 @Override
1713 public WebView getCurrentTopWebView() {
1714 return mTabControl.getCurrentTopWebView();
1715 }
1716
1717 @Override
1718 public WebView getCurrentWebView() {
1719 return mTabControl.getCurrentWebView();
1720 }
1721
1722 /*
1723 * This method is called as a result of the user selecting the options
1724 * menu to see the download window. It shows the download window on top of
1725 * the current window.
1726 */
1727 void viewDownloads() {
1728 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1729 mActivity.startActivity(intent);
1730 }
1731
1732 // action mode
1733
1734 void onActionModeStarted(ActionMode mode) {
1735 mUi.onActionModeStarted(mode);
1736 mActionMode = mode;
1737 }
1738
1739 /*
1740 * True if a custom ActionMode (i.e. find or select) is in use.
1741 */
1742 @Override
1743 public boolean isInCustomActionMode() {
1744 return mActionMode != null;
1745 }
1746
1747 /*
1748 * End the current ActionMode.
1749 */
1750 @Override
1751 public void endActionMode() {
1752 if (mActionMode != null) {
1753 mActionMode.finish();
1754 }
1755 }
1756
1757 /*
1758 * Called by find and select when they are finished. Replace title bars
1759 * as necessary.
1760 */
1761 public void onActionModeFinished(ActionMode mode) {
1762 if (!isInCustomActionMode()) return;
1763 mUi.onActionModeFinished(mInLoad);
1764 mActionMode = null;
1765 }
1766
1767 boolean isInLoad() {
1768 return mInLoad;
1769 }
1770
1771 // bookmark handling
1772
1773 /**
1774 * add the current page as a bookmark to the given folder id
1775 * @param folderId use -1 for the default folder
1776 */
1777 @Override
1778 public void bookmarkCurrentPage(long folderId) {
1779 Intent i = new Intent(mActivity,
1780 AddBookmarkPage.class);
1781 WebView w = getCurrentTopWebView();
1782 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1783 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1784 String touchIconUrl = w.getTouchIconUrl();
1785 if (touchIconUrl != null) {
1786 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1787 WebSettings settings = w.getSettings();
1788 if (settings != null) {
1789 i.putExtra(AddBookmarkPage.USER_AGENT,
1790 settings.getUserAgentString());
1791 }
1792 }
1793 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1794 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1795 getDesiredThumbnailHeight(mActivity)));
1796 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1797 i.putExtra(BrowserContract.Bookmarks.PARENT,
1798 folderId);
1799 // Put the dialog at the upper right of the screen, covering the
1800 // star on the title bar.
1801 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1802 mActivity.startActivity(i);
1803 }
1804
1805 // file chooser
1806 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1807 mUploadHandler = new UploadHandler(this);
1808 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1809 }
1810
1811 // thumbnails
1812
1813 /**
1814 * Return the desired width for thumbnail screenshots, which are stored in
1815 * the database, and used on the bookmarks screen.
1816 * @param context Context for finding out the density of the screen.
1817 * @return desired width for thumbnail screenshot.
1818 */
1819 static int getDesiredThumbnailWidth(Context context) {
1820 return context.getResources().getDimensionPixelOffset(
1821 R.dimen.bookmarkThumbnailWidth);
1822 }
1823
1824 /**
1825 * Return the desired height for thumbnail screenshots, which are stored in
1826 * the database, and used on the bookmarks screen.
1827 * @param context Context for finding out the density of the screen.
1828 * @return desired height for thumbnail screenshot.
1829 */
1830 static int getDesiredThumbnailHeight(Context context) {
1831 return context.getResources().getDimensionPixelOffset(
1832 R.dimen.bookmarkThumbnailHeight);
1833 }
1834
1835 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001836 // We render to a bitmap 2x the desired size so that we can then
1837 // re-scale it with filtering since canvas.scale doesn't filter
1838 // This helps reduce aliasing at the cost of being slightly blurry
1839 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001840 Picture thumbnail = view.capturePicture();
1841 if (thumbnail == null) {
1842 return null;
1843 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001844 width *= filter_scale;
1845 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001846 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1847 Canvas canvas = new Canvas(bm);
1848 // May need to tweak these values to determine what is the
1849 // best scale factor
1850 int thumbnailWidth = thumbnail.getWidth();
1851 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001852 float scaleFactor = 1.0f;
Michael Kolb8233fac2010-10-26 16:08:53 -07001853 if (thumbnailWidth > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001854 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001855 } else {
1856 return null;
1857 }
John Reckfe49ab42010-11-16 17:09:37 -08001858
Michael Kolb8233fac2010-10-26 16:08:53 -07001859 if (view.getWidth() > view.getHeight() &&
1860 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
1861 // If the device is in landscape and the page is shorter
John Reckfe49ab42010-11-16 17:09:37 -08001862 // than the height of the view, center the thumnail and crop the sides
1863 scaleFactor = (float) height / (float)thumbnailHeight;
1864 float wx = (thumbnailWidth * scaleFactor) - width;
1865 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001866 }
1867
John Reckfe49ab42010-11-16 17:09:37 -08001868 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001869
1870 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001871 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
1872 height / filter_scale, true);
1873 bm.recycle();
1874 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001875 }
1876
1877 private void updateScreenshot(WebView view) {
1878 // If this is a bookmarked site, add a screenshot to the database.
1879 // FIXME: When should we update? Every time?
1880 // FIXME: Would like to make sure there is actually something to
1881 // draw, but the API for that (WebViewCore.pictureReady()) is not
1882 // currently accessible here.
1883
1884 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1885 getDesiredThumbnailHeight(mActivity));
1886 if (bm == null) {
1887 return;
1888 }
1889
1890 final ContentResolver cr = mActivity.getContentResolver();
1891 final String url = view.getUrl();
1892 final String originalUrl = view.getOriginalUrl();
1893
John Recka00cbbd2010-12-16 12:38:19 -08001894 // Only update thumbnails for web urls (http(s)://), not for
1895 // about:, javascript:, data:, etc...
John Reck9d038482011-01-04 17:02:09 -08001896 if (url != null && Patterns.WEB_URL.matcher(url).matches()) {
John Recka00cbbd2010-12-16 12:38:19 -08001897 new AsyncTask<Void, Void, Void>() {
1898 @Override
1899 protected Void doInBackground(Void... unused) {
1900 Cursor cursor = null;
1901 try {
1902 // TODO: Clean this up
1903 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
1904 if (cursor != null && cursor.moveToFirst()) {
1905 final ByteArrayOutputStream os =
1906 new ByteArrayOutputStream();
1907 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07001908
John Recka00cbbd2010-12-16 12:38:19 -08001909 ContentValues values = new ContentValues();
1910 values.put(Images.THUMBNAIL, os.toByteArray());
1911 values.put(Images.URL, cursor.getString(0));
Michael Kolb8233fac2010-10-26 16:08:53 -07001912
John Recka00cbbd2010-12-16 12:38:19 -08001913 do {
1914 cr.update(Images.CONTENT_URI, values, null, null);
1915 } while (cursor.moveToNext());
1916 }
1917 } catch (IllegalStateException e) {
1918 // Ignore
1919 } finally {
1920 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07001921 }
John Recka00cbbd2010-12-16 12:38:19 -08001922 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07001923 }
John Recka00cbbd2010-12-16 12:38:19 -08001924 }.execute();
1925 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001926 }
1927
1928 private class Copy implements OnMenuItemClickListener {
1929 private CharSequence mText;
1930
1931 public boolean onMenuItemClick(MenuItem item) {
1932 copy(mText);
1933 return true;
1934 }
1935
1936 public Copy(CharSequence toCopy) {
1937 mText = toCopy;
1938 }
1939 }
1940
Leon Scroggins63c02662010-11-18 15:16:27 -05001941 private static class Download implements OnMenuItemClickListener {
1942 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001943 private String mText;
1944
1945 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05001946 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
1947 null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001948 return true;
1949 }
1950
Leon Scroggins63c02662010-11-18 15:16:27 -05001951 public Download(Activity activity, String toDownload) {
1952 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001953 mText = toDownload;
1954 }
1955 }
1956
Cary Clark8974d282010-11-22 10:46:05 -05001957 private static class SelectText implements OnMenuItemClickListener {
1958 private WebView mWebView;
1959
1960 public boolean onMenuItemClick(MenuItem item) {
1961 if (mWebView != null) {
1962 return mWebView.selectText();
1963 }
1964 return false;
1965 }
1966
1967 public SelectText(WebView webView) {
1968 mWebView = webView;
1969 }
1970
1971 }
1972
Michael Kolb8233fac2010-10-26 16:08:53 -07001973 /********************** TODO: UI stuff *****************************/
1974
1975 // these methods have been copied, they still need to be cleaned up
1976
1977 /****************** tabs ***************************************************/
1978
1979 // basic tab interactions:
1980
1981 // it is assumed that tabcontrol already knows about the tab
1982 protected void addTab(Tab tab) {
1983 mUi.addTab(tab);
1984 }
1985
1986 protected void removeTab(Tab tab) {
1987 mUi.removeTab(tab);
1988 mTabControl.removeTab(tab);
1989 }
1990
1991 protected void setActiveTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001992 mTabControl.setCurrentTab(tab);
Michael Kolb77df4562010-11-19 14:49:34 -08001993 // the tab is guaranteed to have a webview after setCurrentTab
1994 mUi.setActiveTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001995 }
1996
1997 protected void closeEmptyChildTab() {
1998 Tab current = mTabControl.getCurrentTab();
1999 if (current != null
2000 && current.getWebView().copyBackForwardList().getSize() == 0) {
2001 Tab parent = current.getParentTab();
2002 if (parent != null) {
2003 switchToTab(mTabControl.getTabIndex(parent));
2004 closeTab(current);
2005 }
2006 }
2007 }
2008
2009 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
2010 Log.i(LOGTAG, "Reusing tab for " + appId);
2011 // Dismiss the subwindow if applicable.
2012 dismissSubWindow(appTab);
2013 // Since we might kill the WebView, remove it from the
2014 // content view first.
2015 mUi.detachTab(appTab);
2016 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002017 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002018 // TODO: analyze why the remove and add are necessary
2019 mUi.attachTab(appTab);
2020 if (mTabControl.getCurrentTab() != appTab) {
2021 switchToTab(mTabControl.getTabIndex(appTab));
John Reck30c714c2010-12-16 17:30:34 -08002022 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002023 } else {
2024 // If the tab was the current tab, we have to attach
2025 // it to the view system again.
2026 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002027 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002028 }
2029 }
2030
2031 // Remove the sub window if it exists. Also called by TabControl when the
2032 // user clicks the 'X' to dismiss a sub window.
2033 public void dismissSubWindow(Tab tab) {
2034 removeSubWindow(tab);
2035 // dismiss the subwindow. This will destroy the WebView.
2036 tab.dismissSubWindow();
2037 getCurrentTopWebView().requestFocus();
2038 }
2039
2040 @Override
2041 public void removeSubWindow(Tab t) {
2042 if (t.getSubWebView() != null) {
2043 mUi.removeSubWindow(t.getSubViewContainer());
2044 }
2045 }
2046
2047 @Override
2048 public void attachSubWindow(Tab tab) {
2049 if (tab.getSubWebView() != null) {
2050 mUi.attachSubWindow(tab.getSubViewContainer());
2051 getCurrentTopWebView().requestFocus();
2052 }
2053 }
2054
Michael Kolb843510f2010-12-09 10:51:49 -08002055 @Override
2056 public Tab openTabToHomePage() {
2057 // check for max tabs
2058 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002059 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2060 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002061 } else {
2062 mUi.showMaxTabsWarning();
2063 return null;
2064 }
2065 }
2066
Michael Kolb18eb3772010-12-10 14:29:51 -08002067 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2068 if (mSettings.openInBackground() && !forceForeground) {
2069 Tab tab = mTabControl.createNewTab(false, null, null,
2070 (parent != null) && parent.isPrivateBrowsingEnabled());
2071 if (tab != null) {
2072 addTab(tab);
2073 WebView view = tab.getWebView();
2074 loadUrl(view, url);
2075 }
2076 return tab;
2077 } else {
2078 return openTabAndShow(parent, new UrlData(url), false, null);
2079 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002080 }
2081
Michael Kolb18eb3772010-12-10 14:29:51 -08002082
Michael Kolb8233fac2010-10-26 16:08:53 -07002083 // This method does a ton of stuff. It will attempt to create a new tab
2084 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2085 // url isn't null, it will load the given url.
Michael Kolb18eb3772010-12-10 14:29:51 -08002086 public Tab openTabAndShow(Tab parent, UrlData urlData, boolean closeOnExit,
Michael Kolb8233fac2010-10-26 16:08:53 -07002087 String appId) {
2088 final Tab currentTab = mTabControl.getCurrentTab();
2089 if (mTabControl.canCreateNewTab()) {
2090 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Michael Kolb18eb3772010-12-10 14:29:51 -08002091 urlData.mUrl,
2092 (parent != null) && parent.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -07002093 WebView webview = tab.getWebView();
2094 // We must set the new tab as the current tab to reflect the old
2095 // animation behavior.
2096 addTab(tab);
2097 setActiveTab(tab);
2098 if (!urlData.isEmpty()) {
2099 loadUrlDataIn(tab, urlData);
2100 }
2101 return tab;
2102 } else {
2103 // Get rid of the subwindow if it exists
2104 dismissSubWindow(currentTab);
2105 if (!urlData.isEmpty()) {
2106 // Load the given url.
2107 loadUrlDataIn(currentTab, urlData);
2108 }
2109 return currentTab;
2110 }
2111 }
2112
Michael Kolb8233fac2010-10-26 16:08:53 -07002113 @Override
2114 public Tab openIncognitoTab() {
2115 if (mTabControl.canCreateNewTab()) {
2116 Tab currentTab = mTabControl.getCurrentTab();
2117 Tab tab = mTabControl.createNewTab(false, null, null, true);
2118 addTab(tab);
2119 setActiveTab(tab);
2120 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002121 } else {
2122 mUi.showMaxTabsWarning();
2123 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002124 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002125 }
2126
2127 /**
2128 * @param index Index of the tab to change to, as defined by
2129 * mTabControl.getTabIndex(Tab t).
2130 * @return boolean True if we successfully switched to a different tab. If
2131 * the indexth tab is null, or if that tab is the same as
2132 * the current one, return false.
2133 */
2134 @Override
2135 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002136 // hide combo view if open
2137 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002138 Tab tab = mTabControl.getTab(index);
2139 Tab currentTab = mTabControl.getCurrentTab();
2140 if (tab == null || tab == currentTab) {
2141 return false;
2142 }
2143 setActiveTab(tab);
2144 return true;
2145 }
2146
2147 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002148 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002149 // hide combo view if open
2150 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002151 final Tab current = mTabControl.getCurrentTab();
2152 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002153 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002154 return;
2155 }
2156 final Tab parent = current.getParentTab();
2157 int indexToShow = -1;
2158 if (parent != null) {
2159 indexToShow = mTabControl.getTabIndex(parent);
2160 } else {
2161 final int currentIndex = mTabControl.getCurrentIndex();
2162 // Try to move to the tab to the right
2163 indexToShow = currentIndex + 1;
2164 if (indexToShow > mTabControl.getTabCount() - 1) {
2165 // Try to move to the tab to the left
2166 indexToShow = currentIndex - 1;
2167 }
2168 }
2169 if (switchToTab(indexToShow)) {
2170 // Close window
2171 closeTab(current);
2172 }
2173 }
2174
2175 /**
2176 * Close the tab, remove its associated title bar, and adjust mTabControl's
2177 * current tab to a valid value.
2178 */
2179 @Override
2180 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002181 // hide combo view if open
2182 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002183 int currentIndex = mTabControl.getCurrentIndex();
2184 int removeIndex = mTabControl.getTabIndex(tab);
2185 removeTab(tab);
2186 if (currentIndex >= removeIndex && currentIndex != 0) {
2187 currentIndex--;
2188 }
2189 Tab newtab = mTabControl.getTab(currentIndex);
2190 setActiveTab(newtab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002191 }
2192
2193 /**************** TODO: Url loading clean up *******************************/
2194
2195 // Called when loading from context menu or LOAD_URL message
2196 protected void loadUrlFromContext(WebView view, String url) {
2197 // In case the user enters nothing.
2198 if (url != null && url.length() != 0 && view != null) {
2199 url = UrlUtils.smartUrlFilter(url);
2200 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2201 loadUrl(view, url);
2202 }
2203 }
2204 }
2205
2206 /**
2207 * Load the URL into the given WebView and update the title bar
2208 * to reflect the new load. Call this instead of WebView.loadUrl
2209 * directly.
2210 * @param view The WebView used to load url.
2211 * @param url The URL to load.
2212 */
2213 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002214 view.loadUrl(url);
2215 }
2216
2217 /**
2218 * Load UrlData into a Tab and update the title bar to reflect the new
2219 * load. Call this instead of UrlData.loadIn directly.
2220 * @param t The Tab used to load.
2221 * @param data The UrlData being loaded.
2222 */
2223 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002224 data.loadIn(t);
2225 }
2226
John Reck30c714c2010-12-16 17:30:34 -08002227 @Override
2228 public void onUserCanceledSsl(Tab tab) {
2229 WebView web = tab.getWebView();
2230 // TODO: Figure out the "right" behavior
2231 if (web.canGoBack()) {
2232 web.goBack();
2233 } else {
2234 web.loadUrl(mSettings.getHomePage());
2235 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002236 }
2237
2238 void goBackOnePageOrQuit() {
2239 Tab current = mTabControl.getCurrentTab();
2240 if (current == null) {
2241 /*
2242 * Instead of finishing the activity, simply push this to the back
2243 * of the stack and let ActivityManager to choose the foreground
2244 * activity. As BrowserActivity is singleTask, it will be always the
2245 * root of the task. So we can use either true or false for
2246 * moveTaskToBack().
2247 */
2248 mActivity.moveTaskToBack(true);
2249 return;
2250 }
2251 WebView w = current.getWebView();
2252 if (w.canGoBack()) {
2253 w.goBack();
2254 } else {
2255 // Check to see if we are closing a window that was created by
2256 // another window. If so, we switch back to that window.
2257 Tab parent = current.getParentTab();
2258 if (parent != null) {
2259 switchToTab(mTabControl.getTabIndex(parent));
2260 // Now we close the other tab
2261 closeTab(current);
2262 } else {
2263 if (current.closeOnExit()) {
2264 // force the tab's inLoad() to be false as we are going to
2265 // either finish the activity or remove the tab. This will
2266 // ensure pauseWebViewTimers() taking action.
Michael Kolb70976932010-11-30 11:34:01 -08002267 current.clearInPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07002268 if (mTabControl.getTabCount() == 1) {
2269 mActivity.finish();
2270 return;
2271 }
2272 if (mActivityPaused) {
2273 Log.e(LOGTAG, "BrowserActivity is already paused "
2274 + "while handing goBackOnePageOrQuit.");
2275 }
Michael Kolb70976932010-11-30 11:34:01 -08002276 pauseWebViewTimers(current);
Michael Kolb8233fac2010-10-26 16:08:53 -07002277 removeTab(current);
2278 }
2279 /*
2280 * Instead of finishing the activity, simply push this to the back
2281 * of the stack and let ActivityManager to choose the foreground
2282 * activity. As BrowserActivity is singleTask, it will be always the
2283 * root of the task. So we can use either true or false for
2284 * moveTaskToBack().
2285 */
2286 mActivity.moveTaskToBack(true);
2287 }
2288 }
2289 }
2290
2291 /**
2292 * Feed the previously stored results strings to the BrowserProvider so that
2293 * the SearchDialog will show them instead of the standard searches.
2294 * @param result String to show on the editable line of the SearchDialog.
2295 */
2296 @Override
2297 public void showVoiceSearchResults(String result) {
2298 ContentProviderClient client = mActivity.getContentResolver()
2299 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2300 ContentProvider prov = client.getLocalContentProvider();
2301 BrowserProvider bp = (BrowserProvider) prov;
2302 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2303 client.release();
2304
2305 Bundle bundle = createGoogleSearchSourceBundle(
2306 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2307 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2308 startSearch(result, false, bundle, false);
2309 }
2310
2311 private void startSearch(String initialQuery, boolean selectInitialQuery,
2312 Bundle appSearchData, boolean globalSearch) {
2313 if (appSearchData == null) {
2314 appSearchData = createGoogleSearchSourceBundle(
2315 GOOGLE_SEARCH_SOURCE_TYPE);
2316 }
2317
2318 SearchEngine searchEngine = mSettings.getSearchEngine();
2319 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2320 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2321 }
2322 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2323 globalSearch);
2324 }
2325
2326 private Bundle createGoogleSearchSourceBundle(String source) {
2327 Bundle bundle = new Bundle();
2328 bundle.putString(Search.SOURCE, source);
2329 return bundle;
2330 }
2331
2332 /**
2333 * handle key events in browser
2334 *
2335 * @param keyCode
2336 * @param event
2337 * @return true if handled, false to pass to super
2338 */
2339 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002340 boolean noModifiers = event.hasNoModifiers();
2341
Michael Kolb8233fac2010-10-26 16:08:53 -07002342 // Even if MENU is already held down, we need to call to super to open
2343 // the IME on long press.
Cary Clark160bbb92011-01-10 11:17:07 -05002344 if (!noModifiers && KeyEvent.KEYCODE_MENU == keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002345 mMenuIsDown = true;
2346 return false;
2347 }
2348 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2349 // still down, we don't want to trigger the search. Pretend to consume
2350 // the key and do nothing.
2351 if (mMenuIsDown) return true;
2352
Cary Clark8ff8c662010-12-29 15:03:05 -05002353 WebView webView = getCurrentTopWebView();
2354 if (webView == null) return false;
2355
Cary Clark160bbb92011-01-10 11:17:07 -05002356 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2357 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002358
Michael Kolb8233fac2010-10-26 16:08:53 -07002359 switch(keyCode) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002360 case KeyEvent.KEYCODE_ESCAPE:
Cary Clark160bbb92011-01-10 11:17:07 -05002361 if (!noModifiers) break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002362 stopLoading();
2363 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07002364 case KeyEvent.KEYCODE_SPACE:
2365 // WebView/WebTextView handle the keys in the KeyDown. As
2366 // the Activity's shortcut keys are only handled when WebView
2367 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002368 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002369 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002370 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002371 pageDown();
2372 }
2373 return true;
2374 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002375 if (!noModifiers) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002376 if (event.getRepeatCount() == 0) {
2377 event.startTracking();
2378 return true;
2379 } else if (mUi.showsWeb()
2380 && event.isLongPress()) {
2381 bookmarksOrHistoryPicker(true);
2382 return true;
2383 }
2384 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002385 case KeyEvent.KEYCODE_DPAD_LEFT:
2386 if (ctrl) {
2387 webView.goBack();
2388 return true;
2389 }
2390 break;
2391 case KeyEvent.KEYCODE_DPAD_RIGHT:
2392 if (ctrl) {
2393 webView.goForward();
2394 return true;
2395 }
2396 break;
2397 case KeyEvent.KEYCODE_A:
2398 if (ctrl) {
2399 webView.selectAll();
2400 return true;
2401 }
2402 break;
2403 case KeyEvent.KEYCODE_B:
2404 if (ctrl) {
2405 bookmarksOrHistoryPicker(false);
2406 return true;
2407 }
2408 break;
2409 case KeyEvent.KEYCODE_C:
2410 if (ctrl) {
2411 webView.copySelection();
2412 return true;
2413 }
2414 break;
2415 case KeyEvent.KEYCODE_D:
2416 if (ctrl) {
2417 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
2418 return true;
2419 }
2420 break;
2421// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
2422 case KeyEvent.KEYCODE_F:
2423 if (ctrl) {
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05002424 webView.showFindDialog(null, true);
Cary Clark8ff8c662010-12-29 15:03:05 -05002425 return true;
2426 }
2427 break;
2428// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
2429 case KeyEvent.KEYCODE_H:
2430 if (ctrl) {
2431 bookmarksOrHistoryPicker(true);
2432 return true;
2433 }
2434 break;
2435// case KeyEvent.KEYCODE_I: // unused
2436 case KeyEvent.KEYCODE_J:
2437 if (ctrl) {
2438 viewDownloads();
2439 return true;
2440 }
2441 break;
2442// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
2443 case KeyEvent.KEYCODE_L:
2444 if (ctrl) {
2445 editUrl();
2446 return true;
2447 }
2448 break;
2449// case KeyEvent.KEYCODE_M: // unused
2450// case KeyEvent.KEYCODE_N: // in Chrome: new window
2451// case KeyEvent.KEYCODE_O: // in Chrome: open file
2452// case KeyEvent.KEYCODE_P: // in Chrome: print page
2453// case KeyEvent.KEYCODE_Q: // unused
2454 case KeyEvent.KEYCODE_R:
2455 if (ctrl) {
2456 if (mInLoad) {
2457 stopLoading();
2458 } else {
2459 webView.reload();
2460 }
2461 return true;
2462 }
2463 break;
2464// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2465 case KeyEvent.KEYCODE_T:
2466 if (ctrl) {
2467 if (event.isShiftPressed()) {
2468 openIncognitoTab();
2469 } else {
2470 openTabToHomePage();
2471 }
2472 return true;
2473 }
2474 break;
2475// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2476// case KeyEvent.KEYCODE_V: // text view intercepts to paste
2477 case KeyEvent.KEYCODE_W:
2478 if (ctrl) {
2479 closeCurrentTab();
2480 return true;
2481 }
2482 break;
2483// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2484// case KeyEvent.KEYCODE_Y: // unused
2485// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002486 }
2487 return false;
2488 }
2489
2490 boolean onKeyUp(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002491 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002492 switch(keyCode) {
2493 case KeyEvent.KEYCODE_MENU:
2494 mMenuIsDown = false;
2495 break;
2496 case KeyEvent.KEYCODE_BACK:
2497 if (event.isTracking() && !event.isCanceled()) {
2498 onBackKey();
2499 return true;
2500 }
2501 break;
2502 }
2503 return false;
2504 }
2505
2506 public boolean isMenuDown() {
2507 return mMenuIsDown;
2508 }
2509
Ben Murdoch8029a772010-11-16 11:58:21 +00002510 public void setupAutoFill(Message message) {
2511 // Open the settings activity at the AutoFill profile fragment so that
2512 // the user can create a new profile. When they return, we will dispatch
2513 // the message so that we can autofill the form using their new profile.
2514 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2515 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2516 AutoFillSettingsFragment.class.getName());
2517 mAutoFillSetupMessage = message;
2518 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2519 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002520}