blob: 487c69c41079a1a675c4d1fab075410095a35902 [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) {
525 tab.populatePickerData();
526 sharePage(mActivity, tab.getTitle(),
527 tab.getUrl(), tab.getFavicon(),
528 createScreenshot(tab.getWebView(),
529 getDesiredThumbnailWidth(mActivity),
530 getDesiredThumbnailHeight(mActivity)));
531 }
532 }
533
Michael Kolb8233fac2010-10-26 16:08:53 -0700534 /**
535 * Share a page, providing the title, url, favicon, and a screenshot. Uses
536 * an {@link Intent} to launch the Activity chooser.
537 * @param c Context used to launch a new Activity.
538 * @param title Title of the page. Stored in the Intent with
539 * {@link Intent#EXTRA_SUBJECT}
540 * @param url URL of the page. Stored in the Intent with
541 * {@link Intent#EXTRA_TEXT}
542 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
543 * with {@link Browser#EXTRA_SHARE_FAVICON}
544 * @param screenshot Bitmap of a screenshot of the page. Stored in the
545 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
546 */
547 static final void sharePage(Context c, String title, String url,
548 Bitmap favicon, Bitmap screenshot) {
549 Intent send = new Intent(Intent.ACTION_SEND);
550 send.setType("text/plain");
551 send.putExtra(Intent.EXTRA_TEXT, url);
552 send.putExtra(Intent.EXTRA_SUBJECT, title);
553 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
554 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
555 try {
556 c.startActivity(Intent.createChooser(send, c.getString(
557 R.string.choosertitle_sharevia)));
558 } catch(android.content.ActivityNotFoundException ex) {
559 // if no app handles it, do nothing
560 }
561 }
562
563 private void copy(CharSequence text) {
564 ClipboardManager cm = (ClipboardManager) mActivity
565 .getSystemService(Context.CLIPBOARD_SERVICE);
566 cm.setText(text);
567 }
568
569 // lifecycle
570
571 protected void onConfgurationChanged(Configuration config) {
572 mConfigChanged = true;
573 if (mPageDialogsHandler != null) {
574 mPageDialogsHandler.onConfigurationChanged(config);
575 }
576 mUi.onConfigurationChanged(config);
577 }
578
579 @Override
580 public void handleNewIntent(Intent intent) {
581 mIntentHandler.onNewIntent(intent);
582 }
583
584 protected void onPause() {
585 if (mActivityPaused) {
586 Log.e(LOGTAG, "BrowserActivity is already paused.");
587 return;
588 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700589 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800590 Tab tab = mTabControl.getCurrentTab();
591 if (tab != null) {
592 tab.pause();
593 if (!pauseWebViewTimers(tab)) {
594 mWakeLock.acquire();
595 mHandler.sendMessageDelayed(mHandler
596 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
597 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700598 }
599 mUi.onPause();
600 mNetworkHandler.onPause();
601
602 WebView.disablePlatformNotifications();
603 }
604
605 void onSaveInstanceState(Bundle outState) {
606 // the default implementation requires each view to have an id. As the
607 // browser handles the state itself and it doesn't use id for the views,
608 // don't call the default implementation. Otherwise it will trigger the
609 // warning like this, "couldn't save which view has focus because the
610 // focused view XXX has no id".
611
612 // Save all the tabs
613 mTabControl.saveState(outState);
614 // Save time so that we know how old incognito tabs (if any) are.
615 outState.putSerializable("lastActiveDate", Calendar.getInstance());
616 }
617
618 void onResume() {
619 if (!mActivityPaused) {
620 Log.e(LOGTAG, "BrowserActivity is already resumed.");
621 return;
622 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700623 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800624 Tab current = mTabControl.getCurrentTab();
625 if (current != null) {
626 current.resume();
627 resumeWebViewTimers(current);
628 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700629 if (mWakeLock.isHeld()) {
630 mHandler.removeMessages(RELEASE_WAKELOCK);
631 mWakeLock.release();
632 }
633 mUi.onResume();
634 mNetworkHandler.onResume();
635 WebView.enablePlatformNotifications();
636 }
637
Michael Kolb70976932010-11-30 11:34:01 -0800638 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800639 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800640 * @param tab guaranteed non-null
641 */
642 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700643 boolean inLoad = tab.inPageLoad();
644 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
645 CookieSyncManager.getInstance().startSync();
646 WebView w = tab.getWebView();
647 if (w != null) {
648 w.resumeTimers();
649 }
650 }
651 }
652
Michael Kolb70976932010-11-30 11:34:01 -0800653 /**
654 * Pause all WebView timers using the WebView of the given tab
655 * @param tab
656 * @return true if the timers are paused or tab is null
657 */
658 private boolean pauseWebViewTimers(Tab tab) {
659 if (tab == null) {
660 return true;
661 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700662 CookieSyncManager.getInstance().stopSync();
663 WebView w = getCurrentWebView();
664 if (w != null) {
665 w.pauseTimers();
666 }
667 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700668 }
Michael Kolb70976932010-11-30 11:34:01 -0800669 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700670 }
671
672 void onDestroy() {
673 if (mUploadHandler != null) {
674 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
675 mUploadHandler = null;
676 }
677 if (mTabControl == null) return;
678 mUi.onDestroy();
679 // Remove the current tab and sub window
680 Tab t = mTabControl.getCurrentTab();
681 if (t != null) {
682 dismissSubWindow(t);
683 removeTab(t);
684 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500685 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700686 // Destroy all the tabs
687 mTabControl.destroy();
688 WebIconDatabase.getInstance().close();
689 // Stop watching the default geolocation permissions
690 mSystemAllowGeolocationOrigins.stop();
691 mSystemAllowGeolocationOrigins = null;
692 }
693
694 protected boolean isActivityPaused() {
695 return mActivityPaused;
696 }
697
698 protected void onLowMemory() {
699 mTabControl.freeMemory();
700 }
701
702 @Override
703 public boolean shouldShowErrorConsole() {
704 return mShouldShowErrorConsole;
705 }
706
707 protected void setShouldShowErrorConsole(boolean show) {
708 if (show == mShouldShowErrorConsole) {
709 // Nothing to do.
710 return;
711 }
712 mShouldShowErrorConsole = show;
713 Tab t = mTabControl.getCurrentTab();
714 if (t == null) {
715 // There is no current tab so we cannot toggle the error console
716 return;
717 }
718 mUi.setShouldShowErrorConsole(t, show);
719 }
720
721 @Override
722 public void stopLoading() {
723 mLoadStopped = true;
724 Tab tab = mTabControl.getCurrentTab();
725 resetTitleAndRevertLockIcon(tab);
726 WebView w = getCurrentTopWebView();
727 w.stopLoading();
728 // FIXME: before refactor, it is using mWebViewClient. So I keep the
729 // same logic here. But for subwindow case, should we call into the main
730 // WebView's onPageFinished as we never call its onPageStarted and if
731 // the page finishes itself, we don't call onPageFinished.
732 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
733 w.getUrl());
734 mUi.onPageStopped(tab);
735 }
736
737 boolean didUserStopLoading() {
738 return mLoadStopped;
739 }
740
741 // WebViewController
742
743 @Override
744 public void onPageStarted(Tab tab, WebView view, String url, Bitmap favicon) {
745
746 // We've started to load a new page. If there was a pending message
747 // to save a screenshot then we will now take the new page and save
748 // an incorrect screenshot. Therefore, remove any pending thumbnail
749 // messages from the queue.
750 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
751 view);
752
753 // reset sync timer to avoid sync starts during loading a page
754 CookieSyncManager.getInstance().resetSync();
755
756 if (!mNetworkHandler.isNetworkUp()) {
757 view.setNetworkAvailable(false);
758 }
759
760 // when BrowserActivity just starts, onPageStarted may be called before
761 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
762 // to start the timer. As we won't switch tabs while an activity is in
763 // pause state, we can ensure calling resume and pause in pair.
764 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800765 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700766 }
767 mLoadStopped = false;
768 if (!mNetworkHandler.isNetworkUp()) {
769 mNetworkHandler.createAndShowNetworkDialog();
770 }
771 endActionMode();
772
773 mUi.onPageStarted(tab, url, favicon);
774
Michael Kolb8233fac2010-10-26 16:08:53 -0700775 // update the bookmark database for favicon
776 maybeUpdateFavicon(tab, null, url, favicon);
777
778 Performance.tracePageStart(url);
779
780 // Performance probe
781 if (false) {
782 Performance.onPageStarted();
783 }
784
785 }
786
787 @Override
788 public void onPageFinished(Tab tab, String url) {
789 mUi.onPageFinished(tab, url);
790 if (!tab.isPrivateBrowsingEnabled()) {
791 if (tab.inForeground() && !didUserStopLoading()
792 || !tab.inForeground()) {
793 // Only update the bookmark screenshot if the user did not
794 // cancel the load early.
795 mHandler.sendMessageDelayed(mHandler.obtainMessage(
796 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab.getWebView()),
797 500);
798 }
799 }
800 // pause the WebView timer and release the wake lock if it is finished
801 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800802 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700803 if (mWakeLock.isHeld()) {
804 mHandler.removeMessages(RELEASE_WAKELOCK);
805 mWakeLock.release();
806 }
807 }
808 // Performance probe
809 if (false) {
810 Performance.onPageFinished(url);
811 }
812
813 Performance.tracePageFinished();
814 }
815
816 @Override
817 public void onProgressChanged(Tab tab, int newProgress) {
818
819 if (newProgress == 100) {
820 CookieSyncManager.getInstance().sync();
821 // onProgressChanged() may continue to be called after the main
822 // frame has finished loading, as any remaining sub frames continue
823 // to load. We'll only get called once though with newProgress as
824 // 100 when everything is loaded. (onPageFinished is called once
825 // when the main frame completes loading regardless of the state of
826 // any sub frames so calls to onProgressChanges may continue after
827 // onPageFinished has executed)
828 if (mInLoad) {
829 mInLoad = false;
830 updateInLoadMenuItems(mCachedMenu);
831 }
832 } else {
833 if (!mInLoad) {
834 // onPageFinished may have already been called but a subframe is
835 // still loading and updating the progress. Reset mInLoad and
836 // update the menu items.
837 mInLoad = true;
838 updateInLoadMenuItems(mCachedMenu);
839 }
840 }
841 mUi.onProgressChanged(tab, newProgress);
842 }
843
844 @Override
845 public void onReceivedTitle(Tab tab, final String title) {
846 final String pageUrl = tab.getWebView().getUrl();
847 setUrlTitle(tab, pageUrl, title);
848 if (pageUrl == null || pageUrl.length()
849 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
850 return;
851 }
852 // Update the title in the history database if not in private browsing mode
853 if (!tab.isPrivateBrowsingEnabled()) {
John Reck0ebd3ac2010-12-09 11:14:04 -0800854 mDataController.updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700855 }
856 }
857
858 @Override
859 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
860 mUi.setFavicon(tab, icon);
861 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
862 }
863
864 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800865 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
866 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700867 }
868
869 @Override
870 public boolean shouldOverrideKeyEvent(KeyEvent event) {
871 if (mMenuIsDown) {
872 // only check shortcut key when MENU is held
873 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
874 event);
875 } else {
876 return false;
877 }
878 }
879
880 @Override
881 public void onUnhandledKeyEvent(KeyEvent event) {
882 if (!isActivityPaused()) {
883 if (event.getAction() == KeyEvent.ACTION_DOWN) {
884 mActivity.onKeyDown(event.getKeyCode(), event);
885 } else {
886 mActivity.onKeyUp(event.getKeyCode(), event);
887 }
888 }
889 }
890
891 @Override
892 public void doUpdateVisitedHistory(Tab tab, String url,
893 boolean isReload) {
894 // Don't save anything in private browsing mode
895 if (tab.isPrivateBrowsingEnabled()) return;
896
897 if (url.regionMatches(true, 0, "about:", 0, 6)) {
898 return;
899 }
John Reck0ebd3ac2010-12-09 11:14:04 -0800900 mDataController.updateVisitedHistory(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700901 WebIconDatabase.getInstance().retainIconForPageUrl(url);
902 }
903
904 @Override
905 public void getVisitedHistory(final ValueCallback<String[]> callback) {
906 AsyncTask<Void, Void, String[]> task =
907 new AsyncTask<Void, Void, String[]>() {
908 @Override
909 public String[] doInBackground(Void... unused) {
910 return Browser.getVisitedHistory(mActivity.getContentResolver());
911 }
912 @Override
913 public void onPostExecute(String[] result) {
914 callback.onReceiveValue(result);
915 }
916 };
917 task.execute();
918 }
919
920 @Override
921 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
922 final HttpAuthHandler handler, final String host,
923 final String realm) {
924 String username = null;
925 String password = null;
926
927 boolean reuseHttpAuthUsernamePassword
928 = handler.useHttpAuthUsernamePassword();
929
930 if (reuseHttpAuthUsernamePassword && view != null) {
931 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
932 if (credentials != null && credentials.length == 2) {
933 username = credentials[0];
934 password = credentials[1];
935 }
936 }
937
938 if (username != null && password != null) {
939 handler.proceed(username, password);
940 } else {
941 if (tab.inForeground()) {
942 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
943 } else {
944 handler.cancel();
945 }
946 }
947 }
948
949 @Override
950 public void onDownloadStart(Tab tab, String url, String userAgent,
951 String contentDisposition, String mimetype, long contentLength) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500952 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
953 contentDisposition, mimetype);
Michael Kolb8233fac2010-10-26 16:08:53 -0700954 if (tab.getWebView().copyBackForwardList().getSize() == 0) {
955 // This Tab was opened for the sole purpose of downloading a
956 // file. Remove it.
957 if (tab == mTabControl.getCurrentTab()) {
958 // In this case, the Tab is still on top.
959 goBackOnePageOrQuit();
960 } else {
961 // In this case, it is not.
962 closeTab(tab);
963 }
964 }
965 }
966
967 @Override
968 public Bitmap getDefaultVideoPoster() {
969 return mUi.getDefaultVideoPoster();
970 }
971
972 @Override
973 public View getVideoLoadingProgressView() {
974 return mUi.getVideoLoadingProgressView();
975 }
976
977 @Override
978 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
979 SslError error) {
980 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
981 }
982
983 // helper method
984
985 /*
986 * Update the favorites icon if the private browsing isn't enabled and the
987 * icon is valid.
988 */
989 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
990 final String url, Bitmap favicon) {
991 if (favicon == null) {
992 return;
993 }
994 if (!tab.isPrivateBrowsingEnabled()) {
995 Bookmarks.updateFavicon(mActivity
996 .getContentResolver(), originalUrl, url, favicon);
997 }
998 }
999
Leon Scroggins4cd97792010-12-03 15:31:56 -05001000 @Override
1001 public void bookmarkedStatusHasChanged(Tab tab) {
1002 mUi.bookmarkedStatusHasChanged(tab);
1003 }
1004
Michael Kolb8233fac2010-10-26 16:08:53 -07001005 // end WebViewController
1006
1007 protected void pageUp() {
1008 getCurrentTopWebView().pageUp(false);
1009 }
1010
1011 protected void pageDown() {
1012 getCurrentTopWebView().pageDown(false);
1013 }
1014
1015 // callback from phone title bar
1016 public void editUrl() {
1017 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
1018 String url = (getCurrentTopWebView() == null) ? null : getCurrentTopWebView().getUrl();
1019 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1020 null, false);
1021 }
1022
Michael Kolbcfa3af52010-12-14 10:36:11 -08001023 public void startVoiceSearch() {
1024 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1025 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1026 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1027 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1028 mActivity.getComponentName().flattenToString());
1029 intent.putExtra(SEND_APP_ID_EXTRA, false);
1030 mActivity.startActivity(intent);
1031 }
1032
Michael Kolb8233fac2010-10-26 16:08:53 -07001033 public void activateVoiceSearchMode(String title) {
1034 mUi.showVoiceTitleBar(title);
1035 }
1036
1037 public void revertVoiceSearchMode(Tab tab) {
1038 mUi.revertVoiceTitleBar(tab);
1039 }
1040
1041 public void showCustomView(Tab tab, View view,
1042 WebChromeClient.CustomViewCallback callback) {
1043 if (tab.inForeground()) {
1044 if (mUi.isCustomViewShowing()) {
1045 callback.onCustomViewHidden();
1046 return;
1047 }
1048 mUi.showCustomView(view, callback);
1049 // Save the menu state and set it to empty while the custom
1050 // view is showing.
1051 mOldMenuState = mMenuState;
1052 mMenuState = EMPTY_MENU;
1053 }
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;
1063 }
1064 }
1065
1066 protected void onActivityResult(int requestCode, int resultCode,
1067 Intent intent) {
1068 if (getCurrentTopWebView() == null) return;
1069 switch (requestCode) {
1070 case PREFERENCES_PAGE:
1071 if (resultCode == Activity.RESULT_OK && intent != null) {
1072 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
1073 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
1074 mTabControl.removeParentChildRelationShips();
1075 }
1076 }
1077 break;
1078 case FILE_SELECTED:
1079 // Choose a file from the file picker.
1080 if (null == mUploadHandler) break;
1081 mUploadHandler.onResult(resultCode, intent);
1082 mUploadHandler = null;
1083 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001084 case AUTOFILL_SETUP:
1085 // Determine whether a profile was actually set up or not
1086 // and if so, send the message back to the WebTextView to
1087 // fill the form with the new profile.
1088 if (getSettings().getAutoFillProfile() != null) {
1089 mAutoFillSetupMessage.sendToTarget();
1090 mAutoFillSetupMessage = null;
1091 }
1092 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001093 default:
1094 break;
1095 }
1096 getCurrentTopWebView().requestFocus();
1097 }
1098
1099 /**
1100 * Open the Go page.
1101 * @param startWithHistory If true, open starting on the history tab.
1102 * Otherwise, start with the bookmarks tab.
1103 */
1104 @Override
1105 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1106 if (mTabControl.getCurrentWebView() == null) {
1107 return;
1108 }
1109 Bundle extras = new Bundle();
1110 // Disable opening in a new window if we have maxed out the windows
1111 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1112 !mTabControl.canCreateNewTab());
1113 mUi.showComboView(startWithHistory, extras);
1114 }
1115
1116 // combo view callbacks
1117
1118 /**
1119 * callback from ComboPage when clear history is requested
1120 */
1121 public void onRemoveParentChildRelationships() {
1122 mTabControl.removeParentChildRelationShips();
1123 }
1124
1125 /**
1126 * callback from ComboPage when bookmark/history selection
1127 */
1128 @Override
1129 public void onUrlSelected(String url, boolean newTab) {
1130 removeComboView();
1131 if (!TextUtils.isEmpty(url)) {
1132 if (newTab) {
Michael Kolb18eb3772010-12-10 14:29:51 -08001133 openTab(mTabControl.getCurrentTab(), url, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001134 } else {
1135 final Tab currentTab = mTabControl.getCurrentTab();
1136 dismissSubWindow(currentTab);
1137 loadUrl(getCurrentTopWebView(), url);
1138 }
1139 }
1140 }
1141
1142 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07001143 * dismiss the ComboPage
1144 */
1145 @Override
1146 public void removeComboView() {
1147 mUi.hideComboView();
1148 }
1149
1150 // active tabs page handling
1151
1152 protected void showActiveTabsPage() {
1153 mMenuState = EMPTY_MENU;
1154 mUi.showActiveTabsPage();
1155 }
1156
1157 /**
1158 * Remove the active tabs page.
1159 * @param needToAttach If true, the active tabs page did not attach a tab
1160 * to the content view, so we need to do that here.
1161 */
1162 @Override
1163 public void removeActiveTabsPage(boolean needToAttach) {
1164 mMenuState = R.id.MAIN_MENU;
1165 mUi.removeActiveTabsPage();
1166 if (needToAttach) {
1167 setActiveTab(mTabControl.getCurrentTab());
1168 }
1169 getCurrentTopWebView().requestFocus();
1170 }
1171
1172 // key handling
1173 protected void onBackKey() {
1174 if (!mUi.onBackKey()) {
1175 WebView subwindow = mTabControl.getCurrentSubWindow();
1176 if (subwindow != null) {
1177 if (subwindow.canGoBack()) {
1178 subwindow.goBack();
1179 } else {
1180 dismissSubWindow(mTabControl.getCurrentTab());
1181 }
1182 } else {
1183 goBackOnePageOrQuit();
1184 }
1185 }
1186 }
1187
1188 // menu handling and state
1189 // TODO: maybe put into separate handler
1190
1191 protected boolean onCreateOptionsMenu(Menu menu) {
1192 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:
1295 TextView titleView = (TextView) LayoutInflater.from(mActivity)
1296 .inflate(android.R.layout.browser_link_context_header,
1297 null);
1298 titleView.setText(extra);
1299 menu.setHeaderView(titleView);
1300 // decide whether to show the open link in new tab option
1301 boolean showNewTab = mTabControl.canCreateNewTab();
1302 MenuItem newTabItem
1303 = menu.findItem(R.id.open_newtab_context_menu_id);
1304 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 }
1338 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1339 Bookmarks.urlHasAcceptableScheme(extra));
1340 PackageManager pm = mActivity.getPackageManager();
1341 Intent send = new Intent(Intent.ACTION_SEND);
1342 send.setType("text/plain");
1343 ResolveInfo ri = pm.resolveActivity(send,
1344 PackageManager.MATCH_DEFAULT_ONLY);
1345 menu.findItem(R.id.share_link_context_menu_id)
1346 .setVisible(ri != null);
1347 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1348 break;
1349 }
1350 // otherwise fall through to handle image part
1351 case WebView.HitTestResult.IMAGE_TYPE:
1352 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1353 menu.setHeaderTitle(extra);
1354 }
1355 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1356 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1357 menu.findItem(R.id.download_context_menu_id).
Leon Scroggins63c02662010-11-18 15:16:27 -05001358 setOnMenuItemClickListener(new Download(mActivity, extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001359 menu.findItem(R.id.set_wallpaper_context_menu_id).
1360 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1361 extra));
1362 break;
1363
1364 default:
1365 Log.w(LOGTAG, "We should not get here.");
1366 break;
1367 }
1368 //update the ui
1369 mUi.onContextMenuCreated(menu);
1370 }
1371
1372 /**
1373 * As the menu can be open when loading state changes
1374 * we must manually update the state of the stop/reload menu
1375 * item
1376 */
1377 private void updateInLoadMenuItems(Menu menu) {
1378 if (menu == null) {
1379 return;
1380 }
1381 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1382 MenuItem src = mInLoad ?
1383 menu.findItem(R.id.stop_menu_id):
1384 menu.findItem(R.id.reload_menu_id);
1385 if (src != null) {
1386 dest.setIcon(src.getIcon());
1387 dest.setTitle(src.getTitle());
1388 }
1389 }
1390
1391 boolean prepareOptionsMenu(Menu menu) {
1392 // This happens when the user begins to hold down the menu key, so
1393 // allow them to chord to get a shortcut.
1394 mCanChord = true;
1395 // Note: setVisible will decide whether an item is visible; while
1396 // setEnabled() will decide whether an item is enabled, which also means
1397 // whether the matching shortcut key will function.
1398 switch (mMenuState) {
1399 case EMPTY_MENU:
1400 if (mCurrentMenuState != mMenuState) {
1401 menu.setGroupVisible(R.id.MAIN_MENU, false);
1402 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1403 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1404 }
1405 break;
1406 default:
1407 if (mCurrentMenuState != mMenuState) {
1408 menu.setGroupVisible(R.id.MAIN_MENU, true);
1409 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1410 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1411 }
1412 final WebView w = getCurrentTopWebView();
1413 boolean canGoBack = false;
1414 boolean canGoForward = false;
1415 boolean isHome = false;
1416 if (w != null) {
1417 canGoBack = w.canGoBack();
1418 canGoForward = w.canGoForward();
1419 isHome = mSettings.getHomePage().equals(w.getUrl());
1420 }
1421 final MenuItem back = menu.findItem(R.id.back_menu_id);
1422 back.setEnabled(canGoBack);
1423
1424 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1425 home.setEnabled(!isHome);
1426
1427 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1428 forward.setEnabled(canGoForward);
1429
1430 // decide whether to show the share link option
1431 PackageManager pm = mActivity.getPackageManager();
1432 Intent send = new Intent(Intent.ACTION_SEND);
1433 send.setType("text/plain");
1434 ResolveInfo ri = pm.resolveActivity(send,
1435 PackageManager.MATCH_DEFAULT_ONLY);
1436 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1437
1438 boolean isNavDump = mSettings.isNavDump();
1439 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1440 nav.setVisible(isNavDump);
1441 nav.setEnabled(isNavDump);
1442
1443 boolean showDebugSettings = mSettings.showDebugSettings();
1444 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1445 counter.setVisible(showDebugSettings);
1446 counter.setEnabled(showDebugSettings);
1447
1448 // allow the ui to adjust state based settings
1449 mUi.onPrepareOptionsMenu(menu);
1450
1451 break;
1452 }
1453 mCurrentMenuState = mMenuState;
1454 return true;
1455 }
1456
1457 public boolean onOptionsItemSelected(MenuItem item) {
1458 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1459 // menu remains active, so ensure comboview is dismissed
1460 // if main menu option is selected
1461 removeComboView();
1462 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001463 if (!mCanChord) {
1464 // The user has already fired a shortcut with this hold down of the
1465 // menu key.
1466 return false;
1467 }
1468 if (null == getCurrentTopWebView()) {
1469 return false;
1470 }
1471 if (mMenuIsDown) {
1472 // The shortcut action consumes the MENU. Even if it is still down,
1473 // it won't trigger the next shortcut action. In the case of the
1474 // shortcut action triggering a new activity, like Bookmarks, we
1475 // won't get onKeyUp for MENU. So it is important to reset it here.
1476 mMenuIsDown = false;
1477 }
1478 switch (item.getItemId()) {
1479 // -- Main menu
1480 case R.id.new_tab_menu_id:
1481 openTabToHomePage();
1482 break;
1483
1484 case R.id.incognito_menu_id:
1485 openIncognitoTab();
1486 break;
1487
1488 case R.id.goto_menu_id:
1489 editUrl();
1490 break;
1491
1492 case R.id.bookmarks_menu_id:
1493 bookmarksOrHistoryPicker(false);
1494 break;
1495
1496 case R.id.active_tabs_menu_id:
1497 showActiveTabsPage();
1498 break;
1499
1500 case R.id.add_bookmark_menu_id:
1501 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
1502 break;
1503
1504 case R.id.stop_reload_menu_id:
1505 if (mInLoad) {
1506 stopLoading();
1507 } else {
1508 getCurrentTopWebView().reload();
1509 }
1510 break;
1511
1512 case R.id.back_menu_id:
1513 getCurrentTopWebView().goBack();
1514 break;
1515
1516 case R.id.forward_menu_id:
1517 getCurrentTopWebView().goForward();
1518 break;
1519
1520 case R.id.close_menu_id:
1521 // Close the subwindow if it exists.
1522 if (mTabControl.getCurrentSubWindow() != null) {
1523 dismissSubWindow(mTabControl.getCurrentTab());
1524 break;
1525 }
1526 closeCurrentTab();
1527 break;
1528
1529 case R.id.homepage_menu_id:
1530 Tab current = mTabControl.getCurrentTab();
1531 if (current != null) {
1532 dismissSubWindow(current);
1533 loadUrl(current.getWebView(), mSettings.getHomePage());
1534 }
1535 break;
1536
1537 case R.id.preferences_menu_id:
1538 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1539 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1540 getCurrentTopWebView().getUrl());
1541 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1542 break;
1543
1544 case R.id.find_menu_id:
1545 getCurrentTopWebView().showFindDialog(null);
1546 break;
1547
1548 case R.id.page_info_menu_id:
1549 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1550 false);
1551 break;
1552
1553 case R.id.classic_history_menu_id:
1554 bookmarksOrHistoryPicker(true);
1555 break;
1556
1557 case R.id.title_bar_share_page_url:
1558 case R.id.share_page_menu_id:
1559 Tab currentTab = mTabControl.getCurrentTab();
1560 if (null == currentTab) {
1561 mCanChord = false;
1562 return false;
1563 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001564 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001565 break;
1566
1567 case R.id.dump_nav_menu_id:
1568 getCurrentTopWebView().debugDump();
1569 break;
1570
1571 case R.id.dump_counters_menu_id:
1572 getCurrentTopWebView().dumpV8Counters();
1573 break;
1574
1575 case R.id.zoom_in_menu_id:
1576 getCurrentTopWebView().zoomIn();
1577 break;
1578
1579 case R.id.zoom_out_menu_id:
1580 getCurrentTopWebView().zoomOut();
1581 break;
1582
1583 case R.id.view_downloads_menu_id:
1584 viewDownloads();
1585 break;
1586
1587 case R.id.window_one_menu_id:
1588 case R.id.window_two_menu_id:
1589 case R.id.window_three_menu_id:
1590 case R.id.window_four_menu_id:
1591 case R.id.window_five_menu_id:
1592 case R.id.window_six_menu_id:
1593 case R.id.window_seven_menu_id:
1594 case R.id.window_eight_menu_id:
1595 {
1596 int menuid = item.getItemId();
1597 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1598 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1599 Tab desiredTab = mTabControl.getTab(id);
1600 if (desiredTab != null &&
1601 desiredTab != mTabControl.getCurrentTab()) {
1602 switchToTab(id);
1603 }
1604 break;
1605 }
1606 }
1607 }
1608 break;
1609
1610 default:
1611 return false;
1612 }
1613 mCanChord = false;
1614 return true;
1615 }
1616
1617 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001618 // Let the History and Bookmark fragments handle menus they created.
1619 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1620 return false;
1621 }
1622
Michael Kolb8233fac2010-10-26 16:08:53 -07001623 // chording is not an issue with context menus, but we use the same
1624 // options selector, so set mCanChord to true so we can access them.
1625 mCanChord = true;
1626 int id = item.getItemId();
1627 boolean result = true;
1628 switch (id) {
1629 // For the context menu from the title bar
1630 case R.id.title_bar_copy_page_url:
1631 Tab currentTab = mTabControl.getCurrentTab();
1632 if (null == currentTab) {
1633 result = false;
1634 break;
1635 }
1636 WebView mainView = currentTab.getWebView();
1637 if (null == mainView) {
1638 result = false;
1639 break;
1640 }
1641 copy(mainView.getUrl());
1642 break;
1643 // -- Browser context menu
1644 case R.id.open_context_menu_id:
1645 case R.id.bookmark_context_menu_id:
1646 case R.id.save_link_context_menu_id:
1647 case R.id.share_link_context_menu_id:
1648 case R.id.copy_link_context_menu_id:
1649 final WebView webView = getCurrentTopWebView();
1650 if (null == webView) {
1651 result = false;
1652 break;
1653 }
1654 final HashMap<String, WebView> hrefMap =
1655 new HashMap<String, WebView>();
1656 hrefMap.put("webview", webView);
1657 final Message msg = mHandler.obtainMessage(
1658 FOCUS_NODE_HREF, id, 0, hrefMap);
1659 webView.requestFocusNodeHref(msg);
1660 break;
1661
1662 default:
1663 // For other context menus
1664 result = onOptionsItemSelected(item);
1665 }
1666 mCanChord = false;
1667 return result;
1668 }
1669
1670 /**
1671 * support programmatically opening the context menu
1672 */
1673 public void openContextMenu(View view) {
1674 mActivity.openContextMenu(view);
1675 }
1676
1677 /**
1678 * programmatically open the options menu
1679 */
1680 public void openOptionsMenu() {
1681 mActivity.openOptionsMenu();
1682 }
1683
1684 public boolean onMenuOpened(int featureId, Menu menu) {
1685 if (mOptionsMenuOpen) {
1686 if (mConfigChanged) {
1687 // We do not need to make any changes to the state of the
1688 // title bar, since the only thing that happened was a
1689 // change in orientation
1690 mConfigChanged = false;
1691 } else {
1692 if (!mExtendedMenuOpen) {
1693 mExtendedMenuOpen = true;
1694 mUi.onExtendedMenuOpened();
1695 } else {
1696 // Switching the menu back to icon view, so show the
1697 // title bar once again.
1698 mExtendedMenuOpen = false;
1699 mUi.onExtendedMenuClosed(mInLoad);
1700 mUi.onOptionsMenuOpened();
1701 }
1702 }
1703 } else {
1704 // The options menu is closed, so open it, and show the title
1705 mOptionsMenuOpen = true;
1706 mConfigChanged = false;
1707 mExtendedMenuOpen = false;
1708 mUi.onOptionsMenuOpened();
1709 }
1710 return true;
1711 }
1712
1713 public void onOptionsMenuClosed(Menu menu) {
1714 mOptionsMenuOpen = false;
1715 mUi.onOptionsMenuClosed(mInLoad);
1716 }
1717
1718 public void onContextMenuClosed(Menu menu) {
1719 mUi.onContextMenuClosed(menu, mInLoad);
1720 }
1721
1722 // Helper method for getting the top window.
1723 @Override
1724 public WebView getCurrentTopWebView() {
1725 return mTabControl.getCurrentTopWebView();
1726 }
1727
1728 @Override
1729 public WebView getCurrentWebView() {
1730 return mTabControl.getCurrentWebView();
1731 }
1732
1733 /*
1734 * This method is called as a result of the user selecting the options
1735 * menu to see the download window. It shows the download window on top of
1736 * the current window.
1737 */
1738 void viewDownloads() {
1739 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1740 mActivity.startActivity(intent);
1741 }
1742
1743 // action mode
1744
1745 void onActionModeStarted(ActionMode mode) {
1746 mUi.onActionModeStarted(mode);
1747 mActionMode = mode;
1748 }
1749
1750 /*
1751 * True if a custom ActionMode (i.e. find or select) is in use.
1752 */
1753 @Override
1754 public boolean isInCustomActionMode() {
1755 return mActionMode != null;
1756 }
1757
1758 /*
1759 * End the current ActionMode.
1760 */
1761 @Override
1762 public void endActionMode() {
1763 if (mActionMode != null) {
1764 mActionMode.finish();
1765 }
1766 }
1767
1768 /*
1769 * Called by find and select when they are finished. Replace title bars
1770 * as necessary.
1771 */
1772 public void onActionModeFinished(ActionMode mode) {
1773 if (!isInCustomActionMode()) return;
1774 mUi.onActionModeFinished(mInLoad);
1775 mActionMode = null;
1776 }
1777
1778 boolean isInLoad() {
1779 return mInLoad;
1780 }
1781
1782 // bookmark handling
1783
1784 /**
1785 * add the current page as a bookmark to the given folder id
1786 * @param folderId use -1 for the default folder
1787 */
1788 @Override
1789 public void bookmarkCurrentPage(long folderId) {
1790 Intent i = new Intent(mActivity,
1791 AddBookmarkPage.class);
1792 WebView w = getCurrentTopWebView();
1793 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1794 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1795 String touchIconUrl = w.getTouchIconUrl();
1796 if (touchIconUrl != null) {
1797 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1798 WebSettings settings = w.getSettings();
1799 if (settings != null) {
1800 i.putExtra(AddBookmarkPage.USER_AGENT,
1801 settings.getUserAgentString());
1802 }
1803 }
1804 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1805 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1806 getDesiredThumbnailHeight(mActivity)));
1807 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1808 i.putExtra(BrowserContract.Bookmarks.PARENT,
1809 folderId);
1810 // Put the dialog at the upper right of the screen, covering the
1811 // star on the title bar.
1812 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1813 mActivity.startActivity(i);
1814 }
1815
1816 // file chooser
1817 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1818 mUploadHandler = new UploadHandler(this);
1819 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1820 }
1821
1822 // thumbnails
1823
1824 /**
1825 * Return the desired width for thumbnail screenshots, which are stored in
1826 * the database, and used on the bookmarks screen.
1827 * @param context Context for finding out the density of the screen.
1828 * @return desired width for thumbnail screenshot.
1829 */
1830 static int getDesiredThumbnailWidth(Context context) {
1831 return context.getResources().getDimensionPixelOffset(
1832 R.dimen.bookmarkThumbnailWidth);
1833 }
1834
1835 /**
1836 * Return the desired height for thumbnail screenshots, which are stored in
1837 * the database, and used on the bookmarks screen.
1838 * @param context Context for finding out the density of the screen.
1839 * @return desired height for thumbnail screenshot.
1840 */
1841 static int getDesiredThumbnailHeight(Context context) {
1842 return context.getResources().getDimensionPixelOffset(
1843 R.dimen.bookmarkThumbnailHeight);
1844 }
1845
1846 private static Bitmap createScreenshot(WebView view, int width, int height) {
1847 Picture thumbnail = view.capturePicture();
1848 if (thumbnail == null) {
1849 return null;
1850 }
1851 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1852 Canvas canvas = new Canvas(bm);
1853 // May need to tweak these values to determine what is the
1854 // best scale factor
1855 int thumbnailWidth = thumbnail.getWidth();
1856 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001857 float scaleFactor = 1.0f;
Michael Kolb8233fac2010-10-26 16:08:53 -07001858 if (thumbnailWidth > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001859 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001860 } else {
1861 return null;
1862 }
John Reckfe49ab42010-11-16 17:09:37 -08001863
Michael Kolb8233fac2010-10-26 16:08:53 -07001864 if (view.getWidth() > view.getHeight() &&
1865 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
1866 // If the device is in landscape and the page is shorter
John Reckfe49ab42010-11-16 17:09:37 -08001867 // than the height of the view, center the thumnail and crop the sides
1868 scaleFactor = (float) height / (float)thumbnailHeight;
1869 float wx = (thumbnailWidth * scaleFactor) - width;
1870 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001871 }
1872
John Reckfe49ab42010-11-16 17:09:37 -08001873 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001874
1875 thumbnail.draw(canvas);
1876 return bm;
1877 }
1878
1879 private void updateScreenshot(WebView view) {
1880 // If this is a bookmarked site, add a screenshot to the database.
1881 // FIXME: When should we update? Every time?
1882 // FIXME: Would like to make sure there is actually something to
1883 // draw, but the API for that (WebViewCore.pictureReady()) is not
1884 // currently accessible here.
1885
1886 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1887 getDesiredThumbnailHeight(mActivity));
1888 if (bm == null) {
1889 return;
1890 }
1891
1892 final ContentResolver cr = mActivity.getContentResolver();
1893 final String url = view.getUrl();
1894 final String originalUrl = view.getOriginalUrl();
1895
John Recka00cbbd2010-12-16 12:38:19 -08001896 // Only update thumbnails for web urls (http(s)://), not for
1897 // about:, javascript:, data:, etc...
1898 if (Patterns.WEB_URL.matcher(url).matches()) {
1899 new AsyncTask<Void, Void, Void>() {
1900 @Override
1901 protected Void doInBackground(Void... unused) {
1902 Cursor cursor = null;
1903 try {
1904 // TODO: Clean this up
1905 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
1906 if (cursor != null && cursor.moveToFirst()) {
1907 final ByteArrayOutputStream os =
1908 new ByteArrayOutputStream();
1909 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07001910
John Recka00cbbd2010-12-16 12:38:19 -08001911 ContentValues values = new ContentValues();
1912 values.put(Images.THUMBNAIL, os.toByteArray());
1913 values.put(Images.URL, cursor.getString(0));
Michael Kolb8233fac2010-10-26 16:08:53 -07001914
John Recka00cbbd2010-12-16 12:38:19 -08001915 do {
1916 cr.update(Images.CONTENT_URI, values, null, null);
1917 } while (cursor.moveToNext());
1918 }
1919 } catch (IllegalStateException e) {
1920 // Ignore
1921 } finally {
1922 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07001923 }
John Recka00cbbd2010-12-16 12:38:19 -08001924 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07001925 }
John Recka00cbbd2010-12-16 12:38:19 -08001926 }.execute();
1927 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001928 }
1929
1930 private class Copy implements OnMenuItemClickListener {
1931 private CharSequence mText;
1932
1933 public boolean onMenuItemClick(MenuItem item) {
1934 copy(mText);
1935 return true;
1936 }
1937
1938 public Copy(CharSequence toCopy) {
1939 mText = toCopy;
1940 }
1941 }
1942
Leon Scroggins63c02662010-11-18 15:16:27 -05001943 private static class Download implements OnMenuItemClickListener {
1944 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001945 private String mText;
1946
1947 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05001948 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
1949 null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001950 return true;
1951 }
1952
Leon Scroggins63c02662010-11-18 15:16:27 -05001953 public Download(Activity activity, String toDownload) {
1954 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001955 mText = toDownload;
1956 }
1957 }
1958
Cary Clark8974d282010-11-22 10:46:05 -05001959 private static class SelectText implements OnMenuItemClickListener {
1960 private WebView mWebView;
1961
1962 public boolean onMenuItemClick(MenuItem item) {
1963 if (mWebView != null) {
1964 return mWebView.selectText();
1965 }
1966 return false;
1967 }
1968
1969 public SelectText(WebView webView) {
1970 mWebView = webView;
1971 }
1972
1973 }
1974
Michael Kolb8233fac2010-10-26 16:08:53 -07001975 /********************** TODO: UI stuff *****************************/
1976
1977 // these methods have been copied, they still need to be cleaned up
1978
1979 /****************** tabs ***************************************************/
1980
1981 // basic tab interactions:
1982
1983 // it is assumed that tabcontrol already knows about the tab
1984 protected void addTab(Tab tab) {
1985 mUi.addTab(tab);
1986 }
1987
1988 protected void removeTab(Tab tab) {
1989 mUi.removeTab(tab);
1990 mTabControl.removeTab(tab);
1991 }
1992
1993 protected void setActiveTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001994 mTabControl.setCurrentTab(tab);
Michael Kolb77df4562010-11-19 14:49:34 -08001995 // the tab is guaranteed to have a webview after setCurrentTab
1996 mUi.setActiveTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001997 }
1998
1999 protected void closeEmptyChildTab() {
2000 Tab current = mTabControl.getCurrentTab();
2001 if (current != null
2002 && current.getWebView().copyBackForwardList().getSize() == 0) {
2003 Tab parent = current.getParentTab();
2004 if (parent != null) {
2005 switchToTab(mTabControl.getTabIndex(parent));
2006 closeTab(current);
2007 }
2008 }
2009 }
2010
2011 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
2012 Log.i(LOGTAG, "Reusing tab for " + appId);
2013 // Dismiss the subwindow if applicable.
2014 dismissSubWindow(appTab);
2015 // Since we might kill the WebView, remove it from the
2016 // content view first.
2017 mUi.detachTab(appTab);
2018 // Recreate the main WebView after destroying the old one.
2019 // If the WebView has the same original url and is on that
2020 // page, it can be reused.
2021 boolean needsLoad =
2022 mTabControl.recreateWebView(appTab, urlData);
2023 // TODO: analyze why the remove and add are necessary
2024 mUi.attachTab(appTab);
2025 if (mTabControl.getCurrentTab() != appTab) {
2026 switchToTab(mTabControl.getTabIndex(appTab));
2027 if (needsLoad) {
2028 loadUrlDataIn(appTab, urlData);
2029 }
2030 } else {
2031 // If the tab was the current tab, we have to attach
2032 // it to the view system again.
2033 setActiveTab(appTab);
2034 if (needsLoad) {
2035 loadUrlDataIn(appTab, urlData);
2036 }
2037 }
2038 }
2039
2040 // Remove the sub window if it exists. Also called by TabControl when the
2041 // user clicks the 'X' to dismiss a sub window.
2042 public void dismissSubWindow(Tab tab) {
2043 removeSubWindow(tab);
2044 // dismiss the subwindow. This will destroy the WebView.
2045 tab.dismissSubWindow();
2046 getCurrentTopWebView().requestFocus();
2047 }
2048
2049 @Override
2050 public void removeSubWindow(Tab t) {
2051 if (t.getSubWebView() != null) {
2052 mUi.removeSubWindow(t.getSubViewContainer());
2053 }
2054 }
2055
2056 @Override
2057 public void attachSubWindow(Tab tab) {
2058 if (tab.getSubWebView() != null) {
2059 mUi.attachSubWindow(tab.getSubViewContainer());
2060 getCurrentTopWebView().requestFocus();
2061 }
2062 }
2063
Michael Kolb843510f2010-12-09 10:51:49 -08002064 @Override
2065 public Tab openTabToHomePage() {
2066 // check for max tabs
2067 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002068 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2069 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002070 } else {
2071 mUi.showMaxTabsWarning();
2072 return null;
2073 }
2074 }
2075
Michael Kolb18eb3772010-12-10 14:29:51 -08002076 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2077 if (mSettings.openInBackground() && !forceForeground) {
2078 Tab tab = mTabControl.createNewTab(false, null, null,
2079 (parent != null) && parent.isPrivateBrowsingEnabled());
2080 if (tab != null) {
2081 addTab(tab);
2082 WebView view = tab.getWebView();
2083 loadUrl(view, url);
2084 }
2085 return tab;
2086 } else {
2087 return openTabAndShow(parent, new UrlData(url), false, null);
2088 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002089 }
2090
Michael Kolb18eb3772010-12-10 14:29:51 -08002091
Michael Kolb8233fac2010-10-26 16:08:53 -07002092 // This method does a ton of stuff. It will attempt to create a new tab
2093 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2094 // url isn't null, it will load the given url.
Michael Kolb18eb3772010-12-10 14:29:51 -08002095 public Tab openTabAndShow(Tab parent, UrlData urlData, boolean closeOnExit,
Michael Kolb8233fac2010-10-26 16:08:53 -07002096 String appId) {
2097 final Tab currentTab = mTabControl.getCurrentTab();
2098 if (mTabControl.canCreateNewTab()) {
2099 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Michael Kolb18eb3772010-12-10 14:29:51 -08002100 urlData.mUrl,
2101 (parent != null) && parent.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -07002102 WebView webview = tab.getWebView();
2103 // We must set the new tab as the current tab to reflect the old
2104 // animation behavior.
2105 addTab(tab);
2106 setActiveTab(tab);
2107 if (!urlData.isEmpty()) {
2108 loadUrlDataIn(tab, urlData);
2109 }
2110 return tab;
2111 } else {
2112 // Get rid of the subwindow if it exists
2113 dismissSubWindow(currentTab);
2114 if (!urlData.isEmpty()) {
2115 // Load the given url.
2116 loadUrlDataIn(currentTab, urlData);
2117 }
2118 return currentTab;
2119 }
2120 }
2121
Michael Kolb8233fac2010-10-26 16:08:53 -07002122 @Override
2123 public Tab openIncognitoTab() {
2124 if (mTabControl.canCreateNewTab()) {
2125 Tab currentTab = mTabControl.getCurrentTab();
2126 Tab tab = mTabControl.createNewTab(false, null, null, true);
2127 addTab(tab);
2128 setActiveTab(tab);
2129 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002130 } else {
2131 mUi.showMaxTabsWarning();
2132 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002133 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002134 }
2135
2136 /**
2137 * @param index Index of the tab to change to, as defined by
2138 * mTabControl.getTabIndex(Tab t).
2139 * @return boolean True if we successfully switched to a different tab. If
2140 * the indexth tab is null, or if that tab is the same as
2141 * the current one, return false.
2142 */
2143 @Override
2144 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002145 // hide combo view if open
2146 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002147 Tab tab = mTabControl.getTab(index);
2148 Tab currentTab = mTabControl.getCurrentTab();
2149 if (tab == null || tab == currentTab) {
2150 return false;
2151 }
2152 setActiveTab(tab);
2153 return true;
2154 }
2155
2156 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002157 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002158 // hide combo view if open
2159 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002160 final Tab current = mTabControl.getCurrentTab();
2161 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002162 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002163 return;
2164 }
2165 final Tab parent = current.getParentTab();
2166 int indexToShow = -1;
2167 if (parent != null) {
2168 indexToShow = mTabControl.getTabIndex(parent);
2169 } else {
2170 final int currentIndex = mTabControl.getCurrentIndex();
2171 // Try to move to the tab to the right
2172 indexToShow = currentIndex + 1;
2173 if (indexToShow > mTabControl.getTabCount() - 1) {
2174 // Try to move to the tab to the left
2175 indexToShow = currentIndex - 1;
2176 }
2177 }
2178 if (switchToTab(indexToShow)) {
2179 // Close window
2180 closeTab(current);
2181 }
2182 }
2183
2184 /**
2185 * Close the tab, remove its associated title bar, and adjust mTabControl's
2186 * current tab to a valid value.
2187 */
2188 @Override
2189 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002190 // hide combo view if open
2191 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002192 int currentIndex = mTabControl.getCurrentIndex();
2193 int removeIndex = mTabControl.getTabIndex(tab);
2194 removeTab(tab);
2195 if (currentIndex >= removeIndex && currentIndex != 0) {
2196 currentIndex--;
2197 }
2198 Tab newtab = mTabControl.getTab(currentIndex);
2199 setActiveTab(newtab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002200 }
2201
2202 /**************** TODO: Url loading clean up *******************************/
2203
2204 // Called when loading from context menu or LOAD_URL message
2205 protected void loadUrlFromContext(WebView view, String url) {
2206 // In case the user enters nothing.
2207 if (url != null && url.length() != 0 && view != null) {
2208 url = UrlUtils.smartUrlFilter(url);
2209 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2210 loadUrl(view, url);
2211 }
2212 }
2213 }
2214
2215 /**
2216 * Load the URL into the given WebView and update the title bar
2217 * to reflect the new load. Call this instead of WebView.loadUrl
2218 * directly.
2219 * @param view The WebView used to load url.
2220 * @param url The URL to load.
2221 */
2222 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002223 view.loadUrl(url);
2224 }
2225
2226 /**
2227 * Load UrlData into a Tab and update the title bar to reflect the new
2228 * load. Call this instead of UrlData.loadIn directly.
2229 * @param t The Tab used to load.
2230 * @param data The UrlData being loaded.
2231 */
2232 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002233 data.loadIn(t);
2234 }
2235
2236 /**
2237 * Resets the browser title-view to whatever it must be
2238 * (for example, if we had a loading error)
2239 * When we have a new page, we call resetTitle, when we
2240 * have to reset the titlebar to whatever it used to be
2241 * (for example, if the user chose to stop loading), we
2242 * call resetTitleAndRevertLockIcon.
2243 */
2244 public void resetTitleAndRevertLockIcon(Tab tab) {
2245 mUi.resetTitleAndRevertLockIcon(tab);
2246 }
2247
2248 void resetTitleAndIcon(Tab tab) {
2249 mUi.resetTitleAndIcon(tab);
2250 }
2251
2252 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002253 * Sets a title composed of the URL and the title string.
2254 * @param url The URL of the site being loaded.
2255 * @param title The title of the site being loaded.
2256 */
2257 void setUrlTitle(Tab tab, String url, String title) {
2258 tab.setCurrentUrl(url);
2259 tab.setCurrentTitle(title);
2260 // If we are in voice search mode, the title has already been set.
2261 if (tab.isInVoiceSearchMode()) return;
2262 mUi.setUrlTitle(tab, url, title);
2263 }
2264
2265 void goBackOnePageOrQuit() {
2266 Tab current = mTabControl.getCurrentTab();
2267 if (current == null) {
2268 /*
2269 * Instead of finishing the activity, simply push this to the back
2270 * of the stack and let ActivityManager to choose the foreground
2271 * activity. As BrowserActivity is singleTask, it will be always the
2272 * root of the task. So we can use either true or false for
2273 * moveTaskToBack().
2274 */
2275 mActivity.moveTaskToBack(true);
2276 return;
2277 }
2278 WebView w = current.getWebView();
2279 if (w.canGoBack()) {
2280 w.goBack();
2281 } else {
2282 // Check to see if we are closing a window that was created by
2283 // another window. If so, we switch back to that window.
2284 Tab parent = current.getParentTab();
2285 if (parent != null) {
2286 switchToTab(mTabControl.getTabIndex(parent));
2287 // Now we close the other tab
2288 closeTab(current);
2289 } else {
2290 if (current.closeOnExit()) {
2291 // force the tab's inLoad() to be false as we are going to
2292 // either finish the activity or remove the tab. This will
2293 // ensure pauseWebViewTimers() taking action.
Michael Kolb70976932010-11-30 11:34:01 -08002294 current.clearInPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07002295 if (mTabControl.getTabCount() == 1) {
2296 mActivity.finish();
2297 return;
2298 }
2299 if (mActivityPaused) {
2300 Log.e(LOGTAG, "BrowserActivity is already paused "
2301 + "while handing goBackOnePageOrQuit.");
2302 }
Michael Kolb70976932010-11-30 11:34:01 -08002303 pauseWebViewTimers(current);
Michael Kolb8233fac2010-10-26 16:08:53 -07002304 removeTab(current);
2305 }
2306 /*
2307 * Instead of finishing the activity, simply push this to the back
2308 * of the stack and let ActivityManager to choose the foreground
2309 * activity. As BrowserActivity is singleTask, it will be always the
2310 * root of the task. So we can use either true or false for
2311 * moveTaskToBack().
2312 */
2313 mActivity.moveTaskToBack(true);
2314 }
2315 }
2316 }
2317
2318 /**
2319 * Feed the previously stored results strings to the BrowserProvider so that
2320 * the SearchDialog will show them instead of the standard searches.
2321 * @param result String to show on the editable line of the SearchDialog.
2322 */
2323 @Override
2324 public void showVoiceSearchResults(String result) {
2325 ContentProviderClient client = mActivity.getContentResolver()
2326 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2327 ContentProvider prov = client.getLocalContentProvider();
2328 BrowserProvider bp = (BrowserProvider) prov;
2329 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2330 client.release();
2331
2332 Bundle bundle = createGoogleSearchSourceBundle(
2333 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2334 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2335 startSearch(result, false, bundle, false);
2336 }
2337
2338 private void startSearch(String initialQuery, boolean selectInitialQuery,
2339 Bundle appSearchData, boolean globalSearch) {
2340 if (appSearchData == null) {
2341 appSearchData = createGoogleSearchSourceBundle(
2342 GOOGLE_SEARCH_SOURCE_TYPE);
2343 }
2344
2345 SearchEngine searchEngine = mSettings.getSearchEngine();
2346 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2347 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2348 }
2349 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2350 globalSearch);
2351 }
2352
2353 private Bundle createGoogleSearchSourceBundle(String source) {
2354 Bundle bundle = new Bundle();
2355 bundle.putString(Search.SOURCE, source);
2356 return bundle;
2357 }
2358
2359 /**
2360 * handle key events in browser
2361 *
2362 * @param keyCode
2363 * @param event
2364 * @return true if handled, false to pass to super
2365 */
2366 boolean onKeyDown(int keyCode, KeyEvent event) {
2367 // Even if MENU is already held down, we need to call to super to open
2368 // the IME on long press.
2369 if (KeyEvent.KEYCODE_MENU == keyCode) {
2370 mMenuIsDown = true;
2371 return false;
2372 }
2373 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2374 // still down, we don't want to trigger the search. Pretend to consume
2375 // the key and do nothing.
2376 if (mMenuIsDown) return true;
2377
2378 switch(keyCode) {
2379 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.
2383 if (event.isShiftPressed()) {
2384 pageUp();
2385 } else {
2386 pageDown();
2387 }
2388 return true;
2389 case KeyEvent.KEYCODE_BACK:
2390 if (event.getRepeatCount() == 0) {
2391 event.startTracking();
2392 return true;
2393 } else if (mUi.showsWeb()
2394 && event.isLongPress()) {
2395 bookmarksOrHistoryPicker(true);
2396 return true;
2397 }
2398 break;
2399 }
2400 return false;
2401 }
2402
2403 boolean onKeyUp(int keyCode, KeyEvent event) {
2404 switch(keyCode) {
2405 case KeyEvent.KEYCODE_MENU:
2406 mMenuIsDown = false;
2407 break;
2408 case KeyEvent.KEYCODE_BACK:
2409 if (event.isTracking() && !event.isCanceled()) {
2410 onBackKey();
2411 return true;
2412 }
2413 break;
2414 }
2415 return false;
2416 }
2417
2418 public boolean isMenuDown() {
2419 return mMenuIsDown;
2420 }
2421
Ben Murdoch8029a772010-11-16 11:58:21 +00002422 public void setupAutoFill(Message message) {
2423 // Open the settings activity at the AutoFill profile fragment so that
2424 // the user can create a new profile. When they return, we will dispatch
2425 // the message so that we can autofill the form using their new profile.
2426 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2427 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2428 AutoFillSettingsFragment.class.getName());
2429 mAutoFillSetupMessage = message;
2430 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2431 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002432}