blob: 4dc4c4bc1a57e79ad76abb477e6a53f1c4bbeeaa [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;
39import android.database.sqlite.SQLiteException;
40import android.graphics.Bitmap;
41import android.graphics.Canvas;
42import android.graphics.Picture;
43import android.net.Uri;
44import android.net.http.SslError;
45import android.os.AsyncTask;
46import android.os.Bundle;
47import android.os.Handler;
48import android.os.Message;
49import android.os.PowerManager;
50import android.os.PowerManager.WakeLock;
Ben Murdoch8029a772010-11-16 11:58:21 +000051import android.preference.PreferenceActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -070052import android.provider.Browser;
53import android.provider.BrowserContract;
54import android.provider.BrowserContract.History;
55import android.provider.BrowserContract.Images;
56import android.provider.ContactsContract;
57import android.provider.ContactsContract.Intents.Insert;
58import android.speech.RecognizerResultsIntent;
59import android.text.TextUtils;
60import android.util.Log;
61import 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";
97
98 // public message ids
99 public final static int LOAD_URL = 1001;
100 public final static int STOP_LOAD = 1002;
101
102 // Message Ids
103 private static final int FOCUS_NODE_HREF = 102;
104 private static final int RELEASE_WAKELOCK = 107;
105
106 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
107
108 private static final int OPEN_BOOKMARKS = 201;
109
110 private static final int EMPTY_MENU = -1;
111
Michael Kolb8233fac2010-10-26 16:08:53 -0700112 // activity requestCode
113 final static int PREFERENCES_PAGE = 3;
114 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000115 final static int AUTOFILL_SETUP = 5;
116
Michael Kolb8233fac2010-10-26 16:08:53 -0700117 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
118
119 // As the ids are dynamically created, we can't guarantee that they will
120 // be in sequence, so this static array maps ids to a window number.
121 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
122 { R.id.window_one_menu_id, R.id.window_two_menu_id,
123 R.id.window_three_menu_id, R.id.window_four_menu_id,
124 R.id.window_five_menu_id, R.id.window_six_menu_id,
125 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
126
127 // "source" parameter for Google search through search key
128 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
129 // "source" parameter for Google search through simplily type
130 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
131
132 private Activity mActivity;
133 private UI mUi;
134 private TabControl mTabControl;
135 private BrowserSettings mSettings;
136 private WebViewFactory mFactory;
137
138 private WakeLock mWakeLock;
139
140 private UrlHandler mUrlHandler;
141 private UploadHandler mUploadHandler;
142 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700143 private PageDialogsHandler mPageDialogsHandler;
144 private NetworkStateHandler mNetworkHandler;
145
Ben Murdoch8029a772010-11-16 11:58:21 +0000146 private Message mAutoFillSetupMessage;
147
Michael Kolb8233fac2010-10-26 16:08:53 -0700148 private boolean mShouldShowErrorConsole;
149
150 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
151
152 // FIXME, temp address onPrepareMenu performance problem.
153 // When we move everything out of view, we should rewrite this.
154 private int mCurrentMenuState = 0;
155 private int mMenuState = R.id.MAIN_MENU;
156 private int mOldMenuState = EMPTY_MENU;
157 private Menu mCachedMenu;
158
159 // Used to prevent chording to result in firing two shortcuts immediately
160 // one after another. Fixes bug 1211714.
161 boolean mCanChord;
162 private boolean mMenuIsDown;
163
164 // For select and find, we keep track of the ActionMode so that
165 // finish() can be called as desired.
166 private ActionMode mActionMode;
167
168 /**
169 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
170 * of whether the configuration has changed. The first onMenuOpened call
171 * after a configuration change is simply a reopening of the same menu
172 * (i.e. mIconView did not change).
173 */
174 private boolean mConfigChanged;
175
176 /**
177 * Keeps track of whether the options menu is open. This is important in
178 * determining whether to show or hide the title bar overlay
179 */
180 private boolean mOptionsMenuOpen;
181
182 /**
183 * Whether or not the options menu is in its bigger, popup menu form. When
184 * true, we want the title bar overlay to be gone. When false, we do not.
185 * Only meaningful if mOptionsMenuOpen is true.
186 */
187 private boolean mExtendedMenuOpen;
188
189 private boolean mInLoad;
190
191 private boolean mActivityPaused = true;
192 private boolean mLoadStopped;
193
194 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500195 // Checks to see when the bookmarks database has changed, and updates the
196 // Tabs' notion of whether they represent bookmarked sites.
197 private ContentObserver mBookmarksObserver;
Michael Kolb8233fac2010-10-26 16:08:53 -0700198
199 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
200 @Override
201 public Void doInBackground(File... files) {
202 if (files != null) {
203 for (File f : files) {
204 if (!f.delete()) {
205 Log.e(LOGTAG, f.getPath() + " was not deleted");
206 }
207 }
208 }
209 return null;
210 }
211 }
212
213 public Controller(Activity browser) {
214 mActivity = browser;
215 mSettings = BrowserSettings.getInstance();
216 mTabControl = new TabControl(this);
217 mSettings.setController(this);
218
219 mUrlHandler = new UrlHandler(this);
220 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700221 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
222
223 PowerManager pm = (PowerManager) mActivity
224 .getSystemService(Context.POWER_SERVICE);
225 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
226
227 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500228 mBookmarksObserver = new ContentObserver(mHandler) {
229 @Override
230 public void onChange(boolean selfChange) {
231 int size = mTabControl.getTabCount();
232 for (int i = 0; i < size; i++) {
233 mTabControl.getTab(i).updateBookmarkedStatus();
234 }
235 }
236
237 };
238 browser.getContentResolver().registerContentObserver(
239 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700240
241 mNetworkHandler = new NetworkStateHandler(mActivity, this);
242 // Start watching the default geolocation permissions
243 mSystemAllowGeolocationOrigins =
244 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
245 mSystemAllowGeolocationOrigins.start();
246
247 retainIconsOnStartup();
248 }
249
250 void start(Bundle icicle, Intent intent) {
251 // Unless the last browser usage was within 24 hours, destroy any
252 // remaining incognito tabs.
253
254 Calendar lastActiveDate = icicle != null ?
255 (Calendar) icicle.getSerializable("lastActiveDate") : null;
256 Calendar today = Calendar.getInstance();
257 Calendar yesterday = Calendar.getInstance();
258 yesterday.add(Calendar.DATE, -1);
259
Michael Kolb1bf23132010-11-19 12:55:12 -0800260 boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700261 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800262 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700263
Michael Kolb1bf23132010-11-19 12:55:12 -0800264 if (!mTabControl.restoreState(icicle, restoreIncognitoTabs,
265 mUi.needsRestoreAllTabs())) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700266 // there is no quit on Android. But if we can't restore the state,
267 // we can treat it as a new Browser, remove the old session cookies.
Kristian Monsen3a4e8092010-12-08 11:09:25 +0000268 // This is done async in the CookieManager.
269 CookieManager.getInstance().removeSessionCookie();
Kristian Monsen2cd97012010-12-07 11:11:40 +0000270
Michael Kolb8233fac2010-10-26 16:08:53 -0700271 // remove any incognito files
Steve Block83101a82010-11-26 11:33:35 +0000272 WebView.cleanupPrivateBrowsingFiles();
Michael Kolb8233fac2010-10-26 16:08:53 -0700273 final Bundle extra = intent.getExtras();
274 // Create an initial tab.
275 // If the intent is ACTION_VIEW and data is not null, the Browser is
276 // invoked to view the content by another application. In this case,
277 // the tab will be close when exit.
278 UrlData urlData = mIntentHandler.getUrlDataFromIntent(intent);
279
280 String action = intent.getAction();
281 final Tab t = mTabControl.createNewTab(
282 (Intent.ACTION_VIEW.equals(action) &&
283 intent.getData() != null)
284 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
285 .equals(action),
286 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
287 urlData.mUrl, false);
288 addTab(t);
289 setActiveTab(t);
290 WebView webView = t.getWebView();
291 if (extra != null) {
292 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
293 if (scale > 0 && scale <= 1000) {
294 webView.setInitialScale(scale);
295 }
296 }
297
298 if (urlData.isEmpty()) {
299 loadUrl(webView, mSettings.getHomePage());
300 } else {
301 loadUrlDataIn(t, urlData);
302 }
303 } else {
Michael Kolb1bf23132010-11-19 12:55:12 -0800304 mUi.updateTabs(mTabControl.getTabs());
305 if (!restoreIncognitoTabs) {
Steve Block83101a82010-11-26 11:33:35 +0000306 WebView.cleanupPrivateBrowsingFiles();
Michael Kolb8233fac2010-10-26 16:08:53 -0700307 }
308 // 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 }
322 }
323
324 void setWebViewFactory(WebViewFactory factory) {
325 mFactory = factory;
326 }
327
Michael Kolb1514bb72010-11-22 09:11:48 -0800328 @Override
329 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700330 return mFactory;
331 }
332
333 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800334 public void onSetWebView(Tab tab, WebView view) {
335 mUi.onSetWebView(tab, view);
336 }
337
338 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800339 public void createSubWindow(Tab tab) {
340 endActionMode();
341 WebView mainView = tab.getWebView();
342 WebView subView = mFactory.createWebView((mainView == null)
343 ? false
344 : mainView.isPrivateBrowsingEnabled());
345 mUi.createSubWindow(tab, subView);
346 }
347
348 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700349 public Activity getActivity() {
350 return mActivity;
351 }
352
353 void setUi(UI ui) {
354 mUi = ui;
355 }
356
357 BrowserSettings getSettings() {
358 return mSettings;
359 }
360
361 IntentHandler getIntentHandler() {
362 return mIntentHandler;
363 }
364
365 @Override
366 public UI getUi() {
367 return mUi;
368 }
369
370 int getMaxTabs() {
371 return mActivity.getResources().getInteger(R.integer.max_tabs);
372 }
373
374 @Override
375 public TabControl getTabControl() {
376 return mTabControl;
377 }
378
Michael Kolb1bf23132010-11-19 12:55:12 -0800379 @Override
380 public List<Tab> getTabs() {
381 return mTabControl.getTabs();
382 }
383
Michael Kolb8233fac2010-10-26 16:08:53 -0700384 // Open the icon database and retain all the icons for visited sites.
Ben Murdoch9446b932010-11-25 16:20:14 +0000385 // This is done on a background thread so as not to stall startup.
Michael Kolb8233fac2010-10-26 16:08:53 -0700386 private void retainIconsOnStartup() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000387 // WebIconDatabase needs to be retrieved on the UI thread so that if
388 // it has not been created successfully yet the Handler is started on the
389 // UI thread.
390 new RetainIconsOnStartupTask(WebIconDatabase.getInstance()).execute();
391 }
392
393 private class RetainIconsOnStartupTask extends AsyncTask<Void, Void, Void> {
394 private WebIconDatabase mDb;
395
396 public RetainIconsOnStartupTask(WebIconDatabase db) {
397 mDb = db;
398 }
399
400 protected Void doInBackground(Void... unused) {
401 mDb.open(mActivity.getDir("icons", 0).getPath());
402 Cursor c = null;
403 try {
404 c = Browser.getAllBookmarks(mActivity.getContentResolver());
405 if (c.moveToFirst()) {
406 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
407 do {
408 String url = c.getString(urlIndex);
409 mDb.retainIconForPageUrl(url);
410 } while (c.moveToNext());
411 }
412 } catch (IllegalStateException e) {
413 Log.e(LOGTAG, "retainIconsOnStartup", e);
414 } finally {
415 if (c != null) c.close();
Michael Kolb8233fac2010-10-26 16:08:53 -0700416 }
Ben Murdoch9446b932010-11-25 16:20:14 +0000417
418 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700419 }
420 }
421
422 private void startHandler() {
423 mHandler = new Handler() {
424
425 @Override
426 public void handleMessage(Message msg) {
427 switch (msg.what) {
428 case OPEN_BOOKMARKS:
429 bookmarksOrHistoryPicker(false);
430 break;
431 case FOCUS_NODE_HREF:
432 {
433 String url = (String) msg.getData().get("url");
434 String title = (String) msg.getData().get("title");
435 if (TextUtils.isEmpty(url)) {
436 break;
437 }
438 HashMap focusNodeMap = (HashMap) msg.obj;
439 WebView view = (WebView) focusNodeMap.get("webview");
440 // Only apply the action if the top window did not change.
441 if (getCurrentTopWebView() != view) {
442 break;
443 }
444 switch (msg.arg1) {
445 case R.id.open_context_menu_id:
446 case R.id.view_image_context_menu_id:
447 loadUrlFromContext(getCurrentTopWebView(), url);
448 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500449 case R.id.open_newtab_context_menu_id:
450 final Tab parent = mTabControl.getCurrentTab();
451 final Tab newTab = openTab(url, false);
452 if (newTab != null && newTab != parent) {
453 parent.addChildTab(newTab);
454 }
455 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700456 case R.id.bookmark_context_menu_id:
457 Intent intent = new Intent(mActivity,
458 AddBookmarkPage.class);
459 intent.putExtra(BrowserContract.Bookmarks.URL, url);
460 intent.putExtra(BrowserContract.Bookmarks.TITLE,
461 title);
462 mActivity.startActivity(intent);
463 break;
464 case R.id.share_link_context_menu_id:
465 sharePage(mActivity, title, url, null,
466 null);
467 break;
468 case R.id.copy_link_context_menu_id:
469 copy(url);
470 break;
471 case R.id.save_link_context_menu_id:
472 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500473 DownloadHandler.onDownloadStartNoStream(
474 mActivity, url, null, null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -0700475 break;
476 }
477 break;
478 }
479
480 case LOAD_URL:
481 loadUrlFromContext(getCurrentTopWebView(), (String) msg.obj);
482 break;
483
484 case STOP_LOAD:
485 stopLoading();
486 break;
487
488 case RELEASE_WAKELOCK:
489 if (mWakeLock.isHeld()) {
490 mWakeLock.release();
491 // if we reach here, Browser should be still in the
492 // background loading after WAKELOCK_TIMEOUT (5-min).
493 // To avoid burning the battery, stop loading.
494 mTabControl.stopAllLoading();
495 }
496 break;
497
498 case UPDATE_BOOKMARK_THUMBNAIL:
499 WebView view = (WebView) msg.obj;
500 if (view != null) {
501 updateScreenshot(view);
502 }
503 break;
504 }
505 }
506 };
507
508 }
509
Michael Kolbba99c5d2010-11-29 14:57:41 -0800510 @Override
511 public void shareCurrentPage() {
512 shareCurrentPage(mTabControl.getCurrentTab());
513 }
514
515 private void shareCurrentPage(Tab tab) {
516 if (tab != null) {
517 tab.populatePickerData();
518 sharePage(mActivity, tab.getTitle(),
519 tab.getUrl(), tab.getFavicon(),
520 createScreenshot(tab.getWebView(),
521 getDesiredThumbnailWidth(mActivity),
522 getDesiredThumbnailHeight(mActivity)));
523 }
524 }
525
Michael Kolb8233fac2010-10-26 16:08:53 -0700526 /**
527 * Share a page, providing the title, url, favicon, and a screenshot. Uses
528 * an {@link Intent} to launch the Activity chooser.
529 * @param c Context used to launch a new Activity.
530 * @param title Title of the page. Stored in the Intent with
531 * {@link Intent#EXTRA_SUBJECT}
532 * @param url URL of the page. Stored in the Intent with
533 * {@link Intent#EXTRA_TEXT}
534 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
535 * with {@link Browser#EXTRA_SHARE_FAVICON}
536 * @param screenshot Bitmap of a screenshot of the page. Stored in the
537 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
538 */
539 static final void sharePage(Context c, String title, String url,
540 Bitmap favicon, Bitmap screenshot) {
541 Intent send = new Intent(Intent.ACTION_SEND);
542 send.setType("text/plain");
543 send.putExtra(Intent.EXTRA_TEXT, url);
544 send.putExtra(Intent.EXTRA_SUBJECT, title);
545 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
546 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
547 try {
548 c.startActivity(Intent.createChooser(send, c.getString(
549 R.string.choosertitle_sharevia)));
550 } catch(android.content.ActivityNotFoundException ex) {
551 // if no app handles it, do nothing
552 }
553 }
554
555 private void copy(CharSequence text) {
556 ClipboardManager cm = (ClipboardManager) mActivity
557 .getSystemService(Context.CLIPBOARD_SERVICE);
558 cm.setText(text);
559 }
560
561 // lifecycle
562
563 protected void onConfgurationChanged(Configuration config) {
564 mConfigChanged = true;
565 if (mPageDialogsHandler != null) {
566 mPageDialogsHandler.onConfigurationChanged(config);
567 }
568 mUi.onConfigurationChanged(config);
569 }
570
571 @Override
572 public void handleNewIntent(Intent intent) {
573 mIntentHandler.onNewIntent(intent);
574 }
575
576 protected void onPause() {
577 if (mActivityPaused) {
578 Log.e(LOGTAG, "BrowserActivity is already paused.");
579 return;
580 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700581 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800582 Tab tab = mTabControl.getCurrentTab();
583 if (tab != null) {
584 tab.pause();
585 if (!pauseWebViewTimers(tab)) {
586 mWakeLock.acquire();
587 mHandler.sendMessageDelayed(mHandler
588 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
589 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700590 }
591 mUi.onPause();
592 mNetworkHandler.onPause();
593
594 WebView.disablePlatformNotifications();
595 }
596
597 void onSaveInstanceState(Bundle outState) {
598 // the default implementation requires each view to have an id. As the
599 // browser handles the state itself and it doesn't use id for the views,
600 // don't call the default implementation. Otherwise it will trigger the
601 // warning like this, "couldn't save which view has focus because the
602 // focused view XXX has no id".
603
604 // Save all the tabs
605 mTabControl.saveState(outState);
606 // Save time so that we know how old incognito tabs (if any) are.
607 outState.putSerializable("lastActiveDate", Calendar.getInstance());
608 }
609
610 void onResume() {
611 if (!mActivityPaused) {
612 Log.e(LOGTAG, "BrowserActivity is already resumed.");
613 return;
614 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700615 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800616 Tab current = mTabControl.getCurrentTab();
617 if (current != null) {
618 current.resume();
619 resumeWebViewTimers(current);
620 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700621 if (mWakeLock.isHeld()) {
622 mHandler.removeMessages(RELEASE_WAKELOCK);
623 mWakeLock.release();
624 }
625 mUi.onResume();
626 mNetworkHandler.onResume();
627 WebView.enablePlatformNotifications();
628 }
629
Michael Kolb70976932010-11-30 11:34:01 -0800630 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800631 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800632 * @param tab guaranteed non-null
633 */
634 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700635 boolean inLoad = tab.inPageLoad();
636 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
637 CookieSyncManager.getInstance().startSync();
638 WebView w = tab.getWebView();
639 if (w != null) {
640 w.resumeTimers();
641 }
642 }
643 }
644
Michael Kolb70976932010-11-30 11:34:01 -0800645 /**
646 * Pause all WebView timers using the WebView of the given tab
647 * @param tab
648 * @return true if the timers are paused or tab is null
649 */
650 private boolean pauseWebViewTimers(Tab tab) {
651 if (tab == null) {
652 return true;
653 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700654 CookieSyncManager.getInstance().stopSync();
655 WebView w = getCurrentWebView();
656 if (w != null) {
657 w.pauseTimers();
658 }
659 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700660 }
Michael Kolb70976932010-11-30 11:34:01 -0800661 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700662 }
663
664 void onDestroy() {
665 if (mUploadHandler != null) {
666 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
667 mUploadHandler = null;
668 }
669 if (mTabControl == null) return;
670 mUi.onDestroy();
671 // Remove the current tab and sub window
672 Tab t = mTabControl.getCurrentTab();
673 if (t != null) {
674 dismissSubWindow(t);
675 removeTab(t);
676 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500677 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700678 // Destroy all the tabs
679 mTabControl.destroy();
680 WebIconDatabase.getInstance().close();
681 // Stop watching the default geolocation permissions
682 mSystemAllowGeolocationOrigins.stop();
683 mSystemAllowGeolocationOrigins = null;
684 }
685
686 protected boolean isActivityPaused() {
687 return mActivityPaused;
688 }
689
690 protected void onLowMemory() {
691 mTabControl.freeMemory();
692 }
693
694 @Override
695 public boolean shouldShowErrorConsole() {
696 return mShouldShowErrorConsole;
697 }
698
699 protected void setShouldShowErrorConsole(boolean show) {
700 if (show == mShouldShowErrorConsole) {
701 // Nothing to do.
702 return;
703 }
704 mShouldShowErrorConsole = show;
705 Tab t = mTabControl.getCurrentTab();
706 if (t == null) {
707 // There is no current tab so we cannot toggle the error console
708 return;
709 }
710 mUi.setShouldShowErrorConsole(t, show);
711 }
712
713 @Override
714 public void stopLoading() {
715 mLoadStopped = true;
716 Tab tab = mTabControl.getCurrentTab();
717 resetTitleAndRevertLockIcon(tab);
718 WebView w = getCurrentTopWebView();
719 w.stopLoading();
720 // FIXME: before refactor, it is using mWebViewClient. So I keep the
721 // same logic here. But for subwindow case, should we call into the main
722 // WebView's onPageFinished as we never call its onPageStarted and if
723 // the page finishes itself, we don't call onPageFinished.
724 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
725 w.getUrl());
726 mUi.onPageStopped(tab);
727 }
728
729 boolean didUserStopLoading() {
730 return mLoadStopped;
731 }
732
733 // WebViewController
734
735 @Override
736 public void onPageStarted(Tab tab, WebView view, String url, Bitmap favicon) {
737
738 // We've started to load a new page. If there was a pending message
739 // to save a screenshot then we will now take the new page and save
740 // an incorrect screenshot. Therefore, remove any pending thumbnail
741 // messages from the queue.
742 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
743 view);
744
745 // reset sync timer to avoid sync starts during loading a page
746 CookieSyncManager.getInstance().resetSync();
747
748 if (!mNetworkHandler.isNetworkUp()) {
749 view.setNetworkAvailable(false);
750 }
751
752 // when BrowserActivity just starts, onPageStarted may be called before
753 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
754 // to start the timer. As we won't switch tabs while an activity is in
755 // pause state, we can ensure calling resume and pause in pair.
756 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800757 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700758 }
759 mLoadStopped = false;
760 if (!mNetworkHandler.isNetworkUp()) {
761 mNetworkHandler.createAndShowNetworkDialog();
762 }
763 endActionMode();
764
765 mUi.onPageStarted(tab, url, favicon);
766
Michael Kolb8233fac2010-10-26 16:08:53 -0700767 // update the bookmark database for favicon
768 maybeUpdateFavicon(tab, null, url, favicon);
769
770 Performance.tracePageStart(url);
771
772 // Performance probe
773 if (false) {
774 Performance.onPageStarted();
775 }
776
777 }
778
779 @Override
780 public void onPageFinished(Tab tab, String url) {
781 mUi.onPageFinished(tab, url);
782 if (!tab.isPrivateBrowsingEnabled()) {
783 if (tab.inForeground() && !didUserStopLoading()
784 || !tab.inForeground()) {
785 // Only update the bookmark screenshot if the user did not
786 // cancel the load early.
787 mHandler.sendMessageDelayed(mHandler.obtainMessage(
788 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab.getWebView()),
789 500);
790 }
791 }
792 // pause the WebView timer and release the wake lock if it is finished
793 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800794 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700795 if (mWakeLock.isHeld()) {
796 mHandler.removeMessages(RELEASE_WAKELOCK);
797 mWakeLock.release();
798 }
799 }
800 // Performance probe
801 if (false) {
802 Performance.onPageFinished(url);
803 }
804
805 Performance.tracePageFinished();
806 }
807
808 @Override
809 public void onProgressChanged(Tab tab, int newProgress) {
810
811 if (newProgress == 100) {
812 CookieSyncManager.getInstance().sync();
813 // onProgressChanged() may continue to be called after the main
814 // frame has finished loading, as any remaining sub frames continue
815 // to load. We'll only get called once though with newProgress as
816 // 100 when everything is loaded. (onPageFinished is called once
817 // when the main frame completes loading regardless of the state of
818 // any sub frames so calls to onProgressChanges may continue after
819 // onPageFinished has executed)
820 if (mInLoad) {
821 mInLoad = false;
822 updateInLoadMenuItems(mCachedMenu);
823 }
824 } else {
825 if (!mInLoad) {
826 // onPageFinished may have already been called but a subframe is
827 // still loading and updating the progress. Reset mInLoad and
828 // update the menu items.
829 mInLoad = true;
830 updateInLoadMenuItems(mCachedMenu);
831 }
832 }
833 mUi.onProgressChanged(tab, newProgress);
834 }
835
836 @Override
837 public void onReceivedTitle(Tab tab, final String title) {
838 final String pageUrl = tab.getWebView().getUrl();
839 setUrlTitle(tab, pageUrl, title);
840 if (pageUrl == null || pageUrl.length()
841 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
842 return;
843 }
844 // Update the title in the history database if not in private browsing mode
845 if (!tab.isPrivateBrowsingEnabled()) {
846 new AsyncTask<Void, Void, Void>() {
847 @Override
848 protected Void doInBackground(Void... unused) {
849 // See if we can find the current url in our history
850 // database and add the new title to it.
851 String url = pageUrl;
852 if (url.startsWith("http://www.")) {
853 url = url.substring(11);
854 } else if (url.startsWith("http://")) {
855 url = url.substring(4);
856 }
857 // Escape wildcards for LIKE operator.
858 url = url.replace("\\", "\\\\").replace("%", "\\%")
859 .replace("_", "\\_");
860 Cursor c = null;
861 try {
862 final ContentResolver cr =
863 getActivity().getContentResolver();
864 String selection = History.URL + " LIKE ? ESCAPE '\\'";
865 String [] selectionArgs = new String[] { "%" + url };
866 ContentValues values = new ContentValues();
867 values.put(History.TITLE, title);
868 cr.update(History.CONTENT_URI, values, selection,
869 selectionArgs);
870 } catch (IllegalStateException e) {
871 Log.e(LOGTAG, "Tab onReceived title", e);
872 } catch (SQLiteException ex) {
873 Log.e(LOGTAG,
874 "onReceivedTitle() caught SQLiteException: ",
875 ex);
876 } finally {
877 if (c != null) c.close();
878 }
879 return null;
880 }
881 }.execute();
882 }
883 }
884
885 @Override
886 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
887 mUi.setFavicon(tab, icon);
888 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
889 }
890
891 @Override
892 public boolean shouldOverrideUrlLoading(WebView view, String url) {
893 return mUrlHandler.shouldOverrideUrlLoading(view, url);
894 }
895
896 @Override
897 public boolean shouldOverrideKeyEvent(KeyEvent event) {
898 if (mMenuIsDown) {
899 // only check shortcut key when MENU is held
900 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
901 event);
902 } else {
903 return false;
904 }
905 }
906
907 @Override
908 public void onUnhandledKeyEvent(KeyEvent event) {
909 if (!isActivityPaused()) {
910 if (event.getAction() == KeyEvent.ACTION_DOWN) {
911 mActivity.onKeyDown(event.getKeyCode(), event);
912 } else {
913 mActivity.onKeyUp(event.getKeyCode(), event);
914 }
915 }
916 }
917
918 @Override
919 public void doUpdateVisitedHistory(Tab tab, String url,
920 boolean isReload) {
921 // Don't save anything in private browsing mode
922 if (tab.isPrivateBrowsingEnabled()) return;
923
924 if (url.regionMatches(true, 0, "about:", 0, 6)) {
925 return;
926 }
927 // remove "client" before updating it to the history so that it wont
928 // show up in the auto-complete list.
929 int index = url.indexOf("client=ms-");
930 if (index > 0 && url.contains(".google.")) {
931 int end = url.indexOf('&', index);
932 if (end > 0) {
933 url = url.substring(0, index)
934 .concat(url.substring(end + 1));
935 } else {
936 // the url.charAt(index-1) should be either '?' or '&'
937 url = url.substring(0, index-1);
938 }
939 }
940 final ContentResolver cr = getActivity().getContentResolver();
941 final String newUrl = url;
942 new AsyncTask<Void, Void, Void>() {
943 @Override
944 protected Void doInBackground(Void... unused) {
945 Browser.updateVisitedHistory(cr, newUrl, true);
946 return null;
947 }
948 }.execute();
949 WebIconDatabase.getInstance().retainIconForPageUrl(url);
950 }
951
952 @Override
953 public void getVisitedHistory(final ValueCallback<String[]> callback) {
954 AsyncTask<Void, Void, String[]> task =
955 new AsyncTask<Void, Void, String[]>() {
956 @Override
957 public String[] doInBackground(Void... unused) {
958 return Browser.getVisitedHistory(mActivity.getContentResolver());
959 }
960 @Override
961 public void onPostExecute(String[] result) {
962 callback.onReceiveValue(result);
963 }
964 };
965 task.execute();
966 }
967
968 @Override
969 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
970 final HttpAuthHandler handler, final String host,
971 final String realm) {
972 String username = null;
973 String password = null;
974
975 boolean reuseHttpAuthUsernamePassword
976 = handler.useHttpAuthUsernamePassword();
977
978 if (reuseHttpAuthUsernamePassword && view != null) {
979 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
980 if (credentials != null && credentials.length == 2) {
981 username = credentials[0];
982 password = credentials[1];
983 }
984 }
985
986 if (username != null && password != null) {
987 handler.proceed(username, password);
988 } else {
989 if (tab.inForeground()) {
990 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
991 } else {
992 handler.cancel();
993 }
994 }
995 }
996
997 @Override
998 public void onDownloadStart(Tab tab, String url, String userAgent,
999 String contentDisposition, String mimetype, long contentLength) {
Leon Scroggins63c02662010-11-18 15:16:27 -05001000 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
1001 contentDisposition, mimetype);
Michael Kolb8233fac2010-10-26 16:08:53 -07001002 if (tab.getWebView().copyBackForwardList().getSize() == 0) {
1003 // This Tab was opened for the sole purpose of downloading a
1004 // file. Remove it.
1005 if (tab == mTabControl.getCurrentTab()) {
1006 // In this case, the Tab is still on top.
1007 goBackOnePageOrQuit();
1008 } else {
1009 // In this case, it is not.
1010 closeTab(tab);
1011 }
1012 }
1013 }
1014
1015 @Override
1016 public Bitmap getDefaultVideoPoster() {
1017 return mUi.getDefaultVideoPoster();
1018 }
1019
1020 @Override
1021 public View getVideoLoadingProgressView() {
1022 return mUi.getVideoLoadingProgressView();
1023 }
1024
1025 @Override
1026 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1027 SslError error) {
1028 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1029 }
1030
1031 // helper method
1032
1033 /*
1034 * Update the favorites icon if the private browsing isn't enabled and the
1035 * icon is valid.
1036 */
1037 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1038 final String url, Bitmap favicon) {
1039 if (favicon == null) {
1040 return;
1041 }
1042 if (!tab.isPrivateBrowsingEnabled()) {
1043 Bookmarks.updateFavicon(mActivity
1044 .getContentResolver(), originalUrl, url, favicon);
1045 }
1046 }
1047
Leon Scroggins4cd97792010-12-03 15:31:56 -05001048 @Override
1049 public void bookmarkedStatusHasChanged(Tab tab) {
1050 mUi.bookmarkedStatusHasChanged(tab);
1051 }
1052
Michael Kolb8233fac2010-10-26 16:08:53 -07001053 // end WebViewController
1054
1055 protected void pageUp() {
1056 getCurrentTopWebView().pageUp(false);
1057 }
1058
1059 protected void pageDown() {
1060 getCurrentTopWebView().pageDown(false);
1061 }
1062
1063 // callback from phone title bar
1064 public void editUrl() {
1065 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
1066 String url = (getCurrentTopWebView() == null) ? null : getCurrentTopWebView().getUrl();
1067 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1068 null, false);
1069 }
1070
1071 public void activateVoiceSearchMode(String title) {
1072 mUi.showVoiceTitleBar(title);
1073 }
1074
1075 public void revertVoiceSearchMode(Tab tab) {
1076 mUi.revertVoiceTitleBar(tab);
1077 }
1078
1079 public void showCustomView(Tab tab, View view,
1080 WebChromeClient.CustomViewCallback callback) {
1081 if (tab.inForeground()) {
1082 if (mUi.isCustomViewShowing()) {
1083 callback.onCustomViewHidden();
1084 return;
1085 }
1086 mUi.showCustomView(view, callback);
1087 // Save the menu state and set it to empty while the custom
1088 // view is showing.
1089 mOldMenuState = mMenuState;
1090 mMenuState = EMPTY_MENU;
1091 }
1092 }
1093
1094 @Override
1095 public void hideCustomView() {
1096 if (mUi.isCustomViewShowing()) {
1097 mUi.onHideCustomView();
1098 // Reset the old menu state.
1099 mMenuState = mOldMenuState;
1100 mOldMenuState = EMPTY_MENU;
1101 }
1102 }
1103
1104 protected void onActivityResult(int requestCode, int resultCode,
1105 Intent intent) {
1106 if (getCurrentTopWebView() == null) return;
1107 switch (requestCode) {
1108 case PREFERENCES_PAGE:
1109 if (resultCode == Activity.RESULT_OK && intent != null) {
1110 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
1111 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
1112 mTabControl.removeParentChildRelationShips();
1113 }
1114 }
1115 break;
1116 case FILE_SELECTED:
1117 // Choose a file from the file picker.
1118 if (null == mUploadHandler) break;
1119 mUploadHandler.onResult(resultCode, intent);
1120 mUploadHandler = null;
1121 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001122 case AUTOFILL_SETUP:
1123 // Determine whether a profile was actually set up or not
1124 // and if so, send the message back to the WebTextView to
1125 // fill the form with the new profile.
1126 if (getSettings().getAutoFillProfile() != null) {
1127 mAutoFillSetupMessage.sendToTarget();
1128 mAutoFillSetupMessage = null;
1129 }
1130 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001131 default:
1132 break;
1133 }
1134 getCurrentTopWebView().requestFocus();
1135 }
1136
1137 /**
1138 * Open the Go page.
1139 * @param startWithHistory If true, open starting on the history tab.
1140 * Otherwise, start with the bookmarks tab.
1141 */
1142 @Override
1143 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1144 if (mTabControl.getCurrentWebView() == null) {
1145 return;
1146 }
1147 Bundle extras = new Bundle();
1148 // Disable opening in a new window if we have maxed out the windows
1149 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1150 !mTabControl.canCreateNewTab());
1151 mUi.showComboView(startWithHistory, extras);
1152 }
1153
1154 // combo view callbacks
1155
1156 /**
1157 * callback from ComboPage when clear history is requested
1158 */
1159 public void onRemoveParentChildRelationships() {
1160 mTabControl.removeParentChildRelationShips();
1161 }
1162
1163 /**
1164 * callback from ComboPage when bookmark/history selection
1165 */
1166 @Override
1167 public void onUrlSelected(String url, boolean newTab) {
1168 removeComboView();
1169 if (!TextUtils.isEmpty(url)) {
1170 if (newTab) {
1171 openTab(url, false);
1172 } else {
1173 final Tab currentTab = mTabControl.getCurrentTab();
1174 dismissSubWindow(currentTab);
1175 loadUrl(getCurrentTopWebView(), url);
1176 }
1177 }
1178 }
1179
1180 /**
1181 * callback from ComboPage when dismissed
1182 */
1183 @Override
1184 public void onComboCanceled() {
1185 removeComboView();
1186 }
1187
1188 /**
1189 * dismiss the ComboPage
1190 */
1191 @Override
1192 public void removeComboView() {
1193 mUi.hideComboView();
1194 }
1195
1196 // active tabs page handling
1197
1198 protected void showActiveTabsPage() {
1199 mMenuState = EMPTY_MENU;
1200 mUi.showActiveTabsPage();
1201 }
1202
1203 /**
1204 * Remove the active tabs page.
1205 * @param needToAttach If true, the active tabs page did not attach a tab
1206 * to the content view, so we need to do that here.
1207 */
1208 @Override
1209 public void removeActiveTabsPage(boolean needToAttach) {
1210 mMenuState = R.id.MAIN_MENU;
1211 mUi.removeActiveTabsPage();
1212 if (needToAttach) {
1213 setActiveTab(mTabControl.getCurrentTab());
1214 }
1215 getCurrentTopWebView().requestFocus();
1216 }
1217
1218 // key handling
1219 protected void onBackKey() {
1220 if (!mUi.onBackKey()) {
1221 WebView subwindow = mTabControl.getCurrentSubWindow();
1222 if (subwindow != null) {
1223 if (subwindow.canGoBack()) {
1224 subwindow.goBack();
1225 } else {
1226 dismissSubWindow(mTabControl.getCurrentTab());
1227 }
1228 } else {
1229 goBackOnePageOrQuit();
1230 }
1231 }
1232 }
1233
1234 // menu handling and state
1235 // TODO: maybe put into separate handler
1236
1237 protected boolean onCreateOptionsMenu(Menu menu) {
1238 MenuInflater inflater = mActivity.getMenuInflater();
1239 inflater.inflate(R.menu.browser, menu);
1240 updateInLoadMenuItems(menu);
1241 // hold on to the menu reference here; it is used by the page callbacks
1242 // to update the menu based on loading state
1243 mCachedMenu = menu;
1244 return true;
1245 }
1246
1247 protected void onCreateContextMenu(ContextMenu menu, View v,
1248 ContextMenuInfo menuInfo) {
1249 if (v instanceof TitleBarBase) {
1250 return;
1251 }
1252 if (!(v instanceof WebView)) {
1253 return;
1254 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001255 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001256 WebView.HitTestResult result = webview.getHitTestResult();
1257 if (result == null) {
1258 return;
1259 }
1260
1261 int type = result.getType();
1262 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1263 Log.w(LOGTAG,
1264 "We should not show context menu when nothing is touched");
1265 return;
1266 }
1267 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1268 // let TextView handles context menu
1269 return;
1270 }
1271
1272 // Note, http://b/issue?id=1106666 is requesting that
1273 // an inflated menu can be used again. This is not available
1274 // yet, so inflate each time (yuk!)
1275 MenuInflater inflater = mActivity.getMenuInflater();
1276 inflater.inflate(R.menu.browsercontext, menu);
1277
1278 // Show the correct menu group
1279 final String extra = result.getExtra();
1280 menu.setGroupVisible(R.id.PHONE_MENU,
1281 type == WebView.HitTestResult.PHONE_TYPE);
1282 menu.setGroupVisible(R.id.EMAIL_MENU,
1283 type == WebView.HitTestResult.EMAIL_TYPE);
1284 menu.setGroupVisible(R.id.GEO_MENU,
1285 type == WebView.HitTestResult.GEO_TYPE);
1286 menu.setGroupVisible(R.id.IMAGE_MENU,
1287 type == WebView.HitTestResult.IMAGE_TYPE
1288 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1289 menu.setGroupVisible(R.id.ANCHOR_MENU,
1290 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1291 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001292 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1293 || type == WebView.HitTestResult.PHONE_TYPE
1294 || type == WebView.HitTestResult.EMAIL_TYPE
1295 || type == WebView.HitTestResult.GEO_TYPE;
1296 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1297 if (hitText) {
1298 menu.findItem(R.id.select_text_menu_id)
1299 .setOnMenuItemClickListener(new SelectText(webview));
1300 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001301 // Setup custom handling depending on the type
1302 switch (type) {
1303 case WebView.HitTestResult.PHONE_TYPE:
1304 menu.setHeaderTitle(Uri.decode(extra));
1305 menu.findItem(R.id.dial_context_menu_id).setIntent(
1306 new Intent(Intent.ACTION_VIEW, Uri
1307 .parse(WebView.SCHEME_TEL + extra)));
1308 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1309 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1310 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1311 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1312 addIntent);
1313 menu.findItem(R.id.copy_phone_context_menu_id)
1314 .setOnMenuItemClickListener(
1315 new Copy(extra));
1316 break;
1317
1318 case WebView.HitTestResult.EMAIL_TYPE:
1319 menu.setHeaderTitle(extra);
1320 menu.findItem(R.id.email_context_menu_id).setIntent(
1321 new Intent(Intent.ACTION_VIEW, Uri
1322 .parse(WebView.SCHEME_MAILTO + extra)));
1323 menu.findItem(R.id.copy_mail_context_menu_id)
1324 .setOnMenuItemClickListener(
1325 new Copy(extra));
1326 break;
1327
1328 case WebView.HitTestResult.GEO_TYPE:
1329 menu.setHeaderTitle(extra);
1330 menu.findItem(R.id.map_context_menu_id).setIntent(
1331 new Intent(Intent.ACTION_VIEW, Uri
1332 .parse(WebView.SCHEME_GEO
1333 + URLEncoder.encode(extra))));
1334 menu.findItem(R.id.copy_geo_context_menu_id)
1335 .setOnMenuItemClickListener(
1336 new Copy(extra));
1337 break;
1338
1339 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1340 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1341 TextView titleView = (TextView) LayoutInflater.from(mActivity)
1342 .inflate(android.R.layout.browser_link_context_header,
1343 null);
1344 titleView.setText(extra);
1345 menu.setHeaderView(titleView);
1346 // decide whether to show the open link in new tab option
1347 boolean showNewTab = mTabControl.canCreateNewTab();
1348 MenuItem newTabItem
1349 = menu.findItem(R.id.open_newtab_context_menu_id);
1350 newTabItem.setVisible(showNewTab);
1351 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001352 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1353 newTabItem.setOnMenuItemClickListener(
1354 new MenuItem.OnMenuItemClickListener() {
1355 @Override
1356 public boolean onMenuItemClick(MenuItem item) {
1357 final HashMap<String, WebView> hrefMap =
1358 new HashMap<String, WebView>();
1359 hrefMap.put("webview", webview);
1360 final Message msg = mHandler.obtainMessage(
1361 FOCUS_NODE_HREF,
1362 R.id.open_newtab_context_menu_id,
1363 0, hrefMap);
1364 webview.requestFocusNodeHref(msg);
1365 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001366 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001367 });
1368 } else {
1369 newTabItem.setOnMenuItemClickListener(
1370 new MenuItem.OnMenuItemClickListener() {
1371 @Override
1372 public boolean onMenuItemClick(MenuItem item) {
1373 final Tab parent = mTabControl.getCurrentTab();
1374 final Tab newTab = openTab(extra, false);
1375 if (newTab != parent) {
1376 parent.addChildTab(newTab);
1377 }
1378 return true;
1379 }
1380 });
1381 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001382 }
1383 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1384 Bookmarks.urlHasAcceptableScheme(extra));
1385 PackageManager pm = mActivity.getPackageManager();
1386 Intent send = new Intent(Intent.ACTION_SEND);
1387 send.setType("text/plain");
1388 ResolveInfo ri = pm.resolveActivity(send,
1389 PackageManager.MATCH_DEFAULT_ONLY);
1390 menu.findItem(R.id.share_link_context_menu_id)
1391 .setVisible(ri != null);
1392 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1393 break;
1394 }
1395 // otherwise fall through to handle image part
1396 case WebView.HitTestResult.IMAGE_TYPE:
1397 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1398 menu.setHeaderTitle(extra);
1399 }
1400 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1401 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1402 menu.findItem(R.id.download_context_menu_id).
Leon Scroggins63c02662010-11-18 15:16:27 -05001403 setOnMenuItemClickListener(new Download(mActivity, extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001404 menu.findItem(R.id.set_wallpaper_context_menu_id).
1405 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1406 extra));
1407 break;
1408
1409 default:
1410 Log.w(LOGTAG, "We should not get here.");
1411 break;
1412 }
1413 //update the ui
1414 mUi.onContextMenuCreated(menu);
1415 }
1416
1417 /**
1418 * As the menu can be open when loading state changes
1419 * we must manually update the state of the stop/reload menu
1420 * item
1421 */
1422 private void updateInLoadMenuItems(Menu menu) {
1423 if (menu == null) {
1424 return;
1425 }
1426 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1427 MenuItem src = mInLoad ?
1428 menu.findItem(R.id.stop_menu_id):
1429 menu.findItem(R.id.reload_menu_id);
1430 if (src != null) {
1431 dest.setIcon(src.getIcon());
1432 dest.setTitle(src.getTitle());
1433 }
1434 }
1435
1436 boolean prepareOptionsMenu(Menu menu) {
1437 // This happens when the user begins to hold down the menu key, so
1438 // allow them to chord to get a shortcut.
1439 mCanChord = true;
1440 // Note: setVisible will decide whether an item is visible; while
1441 // setEnabled() will decide whether an item is enabled, which also means
1442 // whether the matching shortcut key will function.
1443 switch (mMenuState) {
1444 case EMPTY_MENU:
1445 if (mCurrentMenuState != mMenuState) {
1446 menu.setGroupVisible(R.id.MAIN_MENU, false);
1447 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1448 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1449 }
1450 break;
1451 default:
1452 if (mCurrentMenuState != mMenuState) {
1453 menu.setGroupVisible(R.id.MAIN_MENU, true);
1454 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1455 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1456 }
1457 final WebView w = getCurrentTopWebView();
1458 boolean canGoBack = false;
1459 boolean canGoForward = false;
1460 boolean isHome = false;
1461 if (w != null) {
1462 canGoBack = w.canGoBack();
1463 canGoForward = w.canGoForward();
1464 isHome = mSettings.getHomePage().equals(w.getUrl());
1465 }
1466 final MenuItem back = menu.findItem(R.id.back_menu_id);
1467 back.setEnabled(canGoBack);
1468
1469 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1470 home.setEnabled(!isHome);
1471
1472 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1473 forward.setEnabled(canGoForward);
1474
1475 // decide whether to show the share link option
1476 PackageManager pm = mActivity.getPackageManager();
1477 Intent send = new Intent(Intent.ACTION_SEND);
1478 send.setType("text/plain");
1479 ResolveInfo ri = pm.resolveActivity(send,
1480 PackageManager.MATCH_DEFAULT_ONLY);
1481 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1482
1483 boolean isNavDump = mSettings.isNavDump();
1484 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1485 nav.setVisible(isNavDump);
1486 nav.setEnabled(isNavDump);
1487
1488 boolean showDebugSettings = mSettings.showDebugSettings();
1489 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1490 counter.setVisible(showDebugSettings);
1491 counter.setEnabled(showDebugSettings);
1492
1493 // allow the ui to adjust state based settings
1494 mUi.onPrepareOptionsMenu(menu);
1495
1496 break;
1497 }
1498 mCurrentMenuState = mMenuState;
1499 return true;
1500 }
1501
1502 public boolean onOptionsItemSelected(MenuItem item) {
1503 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1504 // menu remains active, so ensure comboview is dismissed
1505 // if main menu option is selected
1506 removeComboView();
1507 }
1508 // check the action bar button before mCanChord check, as the prepare call
1509 // doesn't come for action bar buttons
1510 if (item.getItemId() == R.id.newtab) {
1511 openTabToHomePage();
1512 return true;
1513 }
1514 if (!mCanChord) {
1515 // The user has already fired a shortcut with this hold down of the
1516 // menu key.
1517 return false;
1518 }
1519 if (null == getCurrentTopWebView()) {
1520 return false;
1521 }
1522 if (mMenuIsDown) {
1523 // The shortcut action consumes the MENU. Even if it is still down,
1524 // it won't trigger the next shortcut action. In the case of the
1525 // shortcut action triggering a new activity, like Bookmarks, we
1526 // won't get onKeyUp for MENU. So it is important to reset it here.
1527 mMenuIsDown = false;
1528 }
1529 switch (item.getItemId()) {
1530 // -- Main menu
1531 case R.id.new_tab_menu_id:
1532 openTabToHomePage();
1533 break;
1534
1535 case R.id.incognito_menu_id:
1536 openIncognitoTab();
1537 break;
1538
1539 case R.id.goto_menu_id:
1540 editUrl();
1541 break;
1542
1543 case R.id.bookmarks_menu_id:
1544 bookmarksOrHistoryPicker(false);
1545 break;
1546
1547 case R.id.active_tabs_menu_id:
1548 showActiveTabsPage();
1549 break;
1550
1551 case R.id.add_bookmark_menu_id:
1552 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
1553 break;
1554
1555 case R.id.stop_reload_menu_id:
1556 if (mInLoad) {
1557 stopLoading();
1558 } else {
1559 getCurrentTopWebView().reload();
1560 }
1561 break;
1562
1563 case R.id.back_menu_id:
1564 getCurrentTopWebView().goBack();
1565 break;
1566
1567 case R.id.forward_menu_id:
1568 getCurrentTopWebView().goForward();
1569 break;
1570
1571 case R.id.close_menu_id:
1572 // Close the subwindow if it exists.
1573 if (mTabControl.getCurrentSubWindow() != null) {
1574 dismissSubWindow(mTabControl.getCurrentTab());
1575 break;
1576 }
1577 closeCurrentTab();
1578 break;
1579
1580 case R.id.homepage_menu_id:
1581 Tab current = mTabControl.getCurrentTab();
1582 if (current != null) {
1583 dismissSubWindow(current);
1584 loadUrl(current.getWebView(), mSettings.getHomePage());
1585 }
1586 break;
1587
1588 case R.id.preferences_menu_id:
1589 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1590 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1591 getCurrentTopWebView().getUrl());
1592 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1593 break;
1594
1595 case R.id.find_menu_id:
1596 getCurrentTopWebView().showFindDialog(null);
1597 break;
1598
1599 case R.id.page_info_menu_id:
1600 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1601 false);
1602 break;
1603
1604 case R.id.classic_history_menu_id:
1605 bookmarksOrHistoryPicker(true);
1606 break;
1607
1608 case R.id.title_bar_share_page_url:
1609 case R.id.share_page_menu_id:
1610 Tab currentTab = mTabControl.getCurrentTab();
1611 if (null == currentTab) {
1612 mCanChord = false;
1613 return false;
1614 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001615 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001616 break;
1617
1618 case R.id.dump_nav_menu_id:
1619 getCurrentTopWebView().debugDump();
1620 break;
1621
1622 case R.id.dump_counters_menu_id:
1623 getCurrentTopWebView().dumpV8Counters();
1624 break;
1625
1626 case R.id.zoom_in_menu_id:
1627 getCurrentTopWebView().zoomIn();
1628 break;
1629
1630 case R.id.zoom_out_menu_id:
1631 getCurrentTopWebView().zoomOut();
1632 break;
1633
1634 case R.id.view_downloads_menu_id:
1635 viewDownloads();
1636 break;
1637
1638 case R.id.window_one_menu_id:
1639 case R.id.window_two_menu_id:
1640 case R.id.window_three_menu_id:
1641 case R.id.window_four_menu_id:
1642 case R.id.window_five_menu_id:
1643 case R.id.window_six_menu_id:
1644 case R.id.window_seven_menu_id:
1645 case R.id.window_eight_menu_id:
1646 {
1647 int menuid = item.getItemId();
1648 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1649 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1650 Tab desiredTab = mTabControl.getTab(id);
1651 if (desiredTab != null &&
1652 desiredTab != mTabControl.getCurrentTab()) {
1653 switchToTab(id);
1654 }
1655 break;
1656 }
1657 }
1658 }
1659 break;
1660
1661 default:
1662 return false;
1663 }
1664 mCanChord = false;
1665 return true;
1666 }
1667
1668 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001669 // Let the History and Bookmark fragments handle menus they created.
1670 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1671 return false;
1672 }
1673
Michael Kolb8233fac2010-10-26 16:08:53 -07001674 // chording is not an issue with context menus, but we use the same
1675 // options selector, so set mCanChord to true so we can access them.
1676 mCanChord = true;
1677 int id = item.getItemId();
1678 boolean result = true;
1679 switch (id) {
1680 // For the context menu from the title bar
1681 case R.id.title_bar_copy_page_url:
1682 Tab currentTab = mTabControl.getCurrentTab();
1683 if (null == currentTab) {
1684 result = false;
1685 break;
1686 }
1687 WebView mainView = currentTab.getWebView();
1688 if (null == mainView) {
1689 result = false;
1690 break;
1691 }
1692 copy(mainView.getUrl());
1693 break;
1694 // -- Browser context menu
1695 case R.id.open_context_menu_id:
1696 case R.id.bookmark_context_menu_id:
1697 case R.id.save_link_context_menu_id:
1698 case R.id.share_link_context_menu_id:
1699 case R.id.copy_link_context_menu_id:
1700 final WebView webView = getCurrentTopWebView();
1701 if (null == webView) {
1702 result = false;
1703 break;
1704 }
1705 final HashMap<String, WebView> hrefMap =
1706 new HashMap<String, WebView>();
1707 hrefMap.put("webview", webView);
1708 final Message msg = mHandler.obtainMessage(
1709 FOCUS_NODE_HREF, id, 0, hrefMap);
1710 webView.requestFocusNodeHref(msg);
1711 break;
1712
1713 default:
1714 // For other context menus
1715 result = onOptionsItemSelected(item);
1716 }
1717 mCanChord = false;
1718 return result;
1719 }
1720
1721 /**
1722 * support programmatically opening the context menu
1723 */
1724 public void openContextMenu(View view) {
1725 mActivity.openContextMenu(view);
1726 }
1727
1728 /**
1729 * programmatically open the options menu
1730 */
1731 public void openOptionsMenu() {
1732 mActivity.openOptionsMenu();
1733 }
1734
1735 public boolean onMenuOpened(int featureId, Menu menu) {
1736 if (mOptionsMenuOpen) {
1737 if (mConfigChanged) {
1738 // We do not need to make any changes to the state of the
1739 // title bar, since the only thing that happened was a
1740 // change in orientation
1741 mConfigChanged = false;
1742 } else {
1743 if (!mExtendedMenuOpen) {
1744 mExtendedMenuOpen = true;
1745 mUi.onExtendedMenuOpened();
1746 } else {
1747 // Switching the menu back to icon view, so show the
1748 // title bar once again.
1749 mExtendedMenuOpen = false;
1750 mUi.onExtendedMenuClosed(mInLoad);
1751 mUi.onOptionsMenuOpened();
1752 }
1753 }
1754 } else {
1755 // The options menu is closed, so open it, and show the title
1756 mOptionsMenuOpen = true;
1757 mConfigChanged = false;
1758 mExtendedMenuOpen = false;
1759 mUi.onOptionsMenuOpened();
1760 }
1761 return true;
1762 }
1763
1764 public void onOptionsMenuClosed(Menu menu) {
1765 mOptionsMenuOpen = false;
1766 mUi.onOptionsMenuClosed(mInLoad);
1767 }
1768
1769 public void onContextMenuClosed(Menu menu) {
1770 mUi.onContextMenuClosed(menu, mInLoad);
1771 }
1772
1773 // Helper method for getting the top window.
1774 @Override
1775 public WebView getCurrentTopWebView() {
1776 return mTabControl.getCurrentTopWebView();
1777 }
1778
1779 @Override
1780 public WebView getCurrentWebView() {
1781 return mTabControl.getCurrentWebView();
1782 }
1783
1784 /*
1785 * This method is called as a result of the user selecting the options
1786 * menu to see the download window. It shows the download window on top of
1787 * the current window.
1788 */
1789 void viewDownloads() {
1790 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1791 mActivity.startActivity(intent);
1792 }
1793
1794 // action mode
1795
1796 void onActionModeStarted(ActionMode mode) {
1797 mUi.onActionModeStarted(mode);
1798 mActionMode = mode;
1799 }
1800
1801 /*
1802 * True if a custom ActionMode (i.e. find or select) is in use.
1803 */
1804 @Override
1805 public boolean isInCustomActionMode() {
1806 return mActionMode != null;
1807 }
1808
1809 /*
1810 * End the current ActionMode.
1811 */
1812 @Override
1813 public void endActionMode() {
1814 if (mActionMode != null) {
1815 mActionMode.finish();
1816 }
1817 }
1818
1819 /*
1820 * Called by find and select when they are finished. Replace title bars
1821 * as necessary.
1822 */
1823 public void onActionModeFinished(ActionMode mode) {
1824 if (!isInCustomActionMode()) return;
1825 mUi.onActionModeFinished(mInLoad);
1826 mActionMode = null;
1827 }
1828
1829 boolean isInLoad() {
1830 return mInLoad;
1831 }
1832
1833 // bookmark handling
1834
1835 /**
1836 * add the current page as a bookmark to the given folder id
1837 * @param folderId use -1 for the default folder
1838 */
1839 @Override
1840 public void bookmarkCurrentPage(long folderId) {
1841 Intent i = new Intent(mActivity,
1842 AddBookmarkPage.class);
1843 WebView w = getCurrentTopWebView();
1844 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1845 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1846 String touchIconUrl = w.getTouchIconUrl();
1847 if (touchIconUrl != null) {
1848 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1849 WebSettings settings = w.getSettings();
1850 if (settings != null) {
1851 i.putExtra(AddBookmarkPage.USER_AGENT,
1852 settings.getUserAgentString());
1853 }
1854 }
1855 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1856 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1857 getDesiredThumbnailHeight(mActivity)));
1858 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1859 i.putExtra(BrowserContract.Bookmarks.PARENT,
1860 folderId);
1861 // Put the dialog at the upper right of the screen, covering the
1862 // star on the title bar.
1863 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1864 mActivity.startActivity(i);
1865 }
1866
1867 // file chooser
1868 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1869 mUploadHandler = new UploadHandler(this);
1870 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1871 }
1872
1873 // thumbnails
1874
1875 /**
1876 * Return the desired width for thumbnail screenshots, which are stored in
1877 * the database, and used on the bookmarks screen.
1878 * @param context Context for finding out the density of the screen.
1879 * @return desired width for thumbnail screenshot.
1880 */
1881 static int getDesiredThumbnailWidth(Context context) {
1882 return context.getResources().getDimensionPixelOffset(
1883 R.dimen.bookmarkThumbnailWidth);
1884 }
1885
1886 /**
1887 * Return the desired height for thumbnail screenshots, which are stored in
1888 * the database, and used on the bookmarks screen.
1889 * @param context Context for finding out the density of the screen.
1890 * @return desired height for thumbnail screenshot.
1891 */
1892 static int getDesiredThumbnailHeight(Context context) {
1893 return context.getResources().getDimensionPixelOffset(
1894 R.dimen.bookmarkThumbnailHeight);
1895 }
1896
1897 private static Bitmap createScreenshot(WebView view, int width, int height) {
1898 Picture thumbnail = view.capturePicture();
1899 if (thumbnail == null) {
1900 return null;
1901 }
1902 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1903 Canvas canvas = new Canvas(bm);
1904 // May need to tweak these values to determine what is the
1905 // best scale factor
1906 int thumbnailWidth = thumbnail.getWidth();
1907 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001908 float scaleFactor = 1.0f;
Michael Kolb8233fac2010-10-26 16:08:53 -07001909 if (thumbnailWidth > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001910 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001911 } else {
1912 return null;
1913 }
John Reckfe49ab42010-11-16 17:09:37 -08001914
Michael Kolb8233fac2010-10-26 16:08:53 -07001915 if (view.getWidth() > view.getHeight() &&
1916 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
1917 // If the device is in landscape and the page is shorter
John Reckfe49ab42010-11-16 17:09:37 -08001918 // than the height of the view, center the thumnail and crop the sides
1919 scaleFactor = (float) height / (float)thumbnailHeight;
1920 float wx = (thumbnailWidth * scaleFactor) - width;
1921 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001922 }
1923
John Reckfe49ab42010-11-16 17:09:37 -08001924 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001925
1926 thumbnail.draw(canvas);
1927 return bm;
1928 }
1929
1930 private void updateScreenshot(WebView view) {
1931 // If this is a bookmarked site, add a screenshot to the database.
1932 // FIXME: When should we update? Every time?
1933 // FIXME: Would like to make sure there is actually something to
1934 // draw, but the API for that (WebViewCore.pictureReady()) is not
1935 // currently accessible here.
1936
1937 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1938 getDesiredThumbnailHeight(mActivity));
1939 if (bm == null) {
1940 return;
1941 }
1942
1943 final ContentResolver cr = mActivity.getContentResolver();
1944 final String url = view.getUrl();
1945 final String originalUrl = view.getOriginalUrl();
1946
1947 new AsyncTask<Void, Void, Void>() {
1948 @Override
1949 protected Void doInBackground(Void... unused) {
1950 Cursor cursor = null;
1951 try {
1952 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
1953 if (cursor != null && cursor.moveToFirst()) {
1954 final ByteArrayOutputStream os =
1955 new ByteArrayOutputStream();
1956 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
1957
1958 ContentValues values = new ContentValues();
1959 values.put(Images.THUMBNAIL, os.toByteArray());
1960 values.put(Images.URL, cursor.getString(0));
1961
1962 do {
1963 cr.update(Images.CONTENT_URI, values, null, null);
1964 } while (cursor.moveToNext());
1965 }
1966 } catch (IllegalStateException e) {
1967 // Ignore
1968 } finally {
1969 if (cursor != null) cursor.close();
1970 }
1971 return null;
1972 }
1973 }.execute();
1974 }
1975
1976 private class Copy implements OnMenuItemClickListener {
1977 private CharSequence mText;
1978
1979 public boolean onMenuItemClick(MenuItem item) {
1980 copy(mText);
1981 return true;
1982 }
1983
1984 public Copy(CharSequence toCopy) {
1985 mText = toCopy;
1986 }
1987 }
1988
Leon Scroggins63c02662010-11-18 15:16:27 -05001989 private static class Download implements OnMenuItemClickListener {
1990 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001991 private String mText;
1992
1993 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05001994 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
1995 null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001996 return true;
1997 }
1998
Leon Scroggins63c02662010-11-18 15:16:27 -05001999 public Download(Activity activity, String toDownload) {
2000 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002001 mText = toDownload;
2002 }
2003 }
2004
Cary Clark8974d282010-11-22 10:46:05 -05002005 private static class SelectText implements OnMenuItemClickListener {
2006 private WebView mWebView;
2007
2008 public boolean onMenuItemClick(MenuItem item) {
2009 if (mWebView != null) {
2010 return mWebView.selectText();
2011 }
2012 return false;
2013 }
2014
2015 public SelectText(WebView webView) {
2016 mWebView = webView;
2017 }
2018
2019 }
2020
Michael Kolb8233fac2010-10-26 16:08:53 -07002021 /********************** TODO: UI stuff *****************************/
2022
2023 // these methods have been copied, they still need to be cleaned up
2024
2025 /****************** tabs ***************************************************/
2026
2027 // basic tab interactions:
2028
2029 // it is assumed that tabcontrol already knows about the tab
2030 protected void addTab(Tab tab) {
2031 mUi.addTab(tab);
2032 }
2033
2034 protected void removeTab(Tab tab) {
2035 mUi.removeTab(tab);
2036 mTabControl.removeTab(tab);
2037 }
2038
2039 protected void setActiveTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002040 mTabControl.setCurrentTab(tab);
Michael Kolb77df4562010-11-19 14:49:34 -08002041 // the tab is guaranteed to have a webview after setCurrentTab
2042 mUi.setActiveTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002043 }
2044
2045 protected void closeEmptyChildTab() {
2046 Tab current = mTabControl.getCurrentTab();
2047 if (current != null
2048 && current.getWebView().copyBackForwardList().getSize() == 0) {
2049 Tab parent = current.getParentTab();
2050 if (parent != null) {
2051 switchToTab(mTabControl.getTabIndex(parent));
2052 closeTab(current);
2053 }
2054 }
2055 }
2056
2057 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
2058 Log.i(LOGTAG, "Reusing tab for " + appId);
2059 // Dismiss the subwindow if applicable.
2060 dismissSubWindow(appTab);
2061 // Since we might kill the WebView, remove it from the
2062 // content view first.
2063 mUi.detachTab(appTab);
2064 // Recreate the main WebView after destroying the old one.
2065 // If the WebView has the same original url and is on that
2066 // page, it can be reused.
2067 boolean needsLoad =
2068 mTabControl.recreateWebView(appTab, urlData);
2069 // TODO: analyze why the remove and add are necessary
2070 mUi.attachTab(appTab);
2071 if (mTabControl.getCurrentTab() != appTab) {
2072 switchToTab(mTabControl.getTabIndex(appTab));
2073 if (needsLoad) {
2074 loadUrlDataIn(appTab, urlData);
2075 }
2076 } else {
2077 // If the tab was the current tab, we have to attach
2078 // it to the view system again.
2079 setActiveTab(appTab);
2080 if (needsLoad) {
2081 loadUrlDataIn(appTab, urlData);
2082 }
2083 }
2084 }
2085
2086 // Remove the sub window if it exists. Also called by TabControl when the
2087 // user clicks the 'X' to dismiss a sub window.
2088 public void dismissSubWindow(Tab tab) {
2089 removeSubWindow(tab);
2090 // dismiss the subwindow. This will destroy the WebView.
2091 tab.dismissSubWindow();
2092 getCurrentTopWebView().requestFocus();
2093 }
2094
2095 @Override
2096 public void removeSubWindow(Tab t) {
2097 if (t.getSubWebView() != null) {
2098 mUi.removeSubWindow(t.getSubViewContainer());
2099 }
2100 }
2101
2102 @Override
2103 public void attachSubWindow(Tab tab) {
2104 if (tab.getSubWebView() != null) {
2105 mUi.attachSubWindow(tab.getSubViewContainer());
2106 getCurrentTopWebView().requestFocus();
2107 }
2108 }
2109
2110 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
2111 // that accepts url as string.
2112
2113 protected Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
2114 return openTabAndShow(new UrlData(url), closeOnExit, appId);
2115 }
2116
2117 // This method does a ton of stuff. It will attempt to create a new tab
2118 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2119 // url isn't null, it will load the given url.
2120
2121 public Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
2122 String appId) {
2123 final Tab currentTab = mTabControl.getCurrentTab();
2124 if (mTabControl.canCreateNewTab()) {
2125 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
2126 urlData.mUrl, false);
2127 WebView webview = tab.getWebView();
2128 // We must set the new tab as the current tab to reflect the old
2129 // animation behavior.
2130 addTab(tab);
2131 setActiveTab(tab);
2132 if (!urlData.isEmpty()) {
2133 loadUrlDataIn(tab, urlData);
2134 }
2135 return tab;
2136 } else {
2137 // Get rid of the subwindow if it exists
2138 dismissSubWindow(currentTab);
2139 if (!urlData.isEmpty()) {
2140 // Load the given url.
2141 loadUrlDataIn(currentTab, urlData);
2142 }
2143 return currentTab;
2144 }
2145 }
2146
2147 protected Tab openTab(String url, boolean forceForeground) {
2148 if (mSettings.openInBackground() && !forceForeground) {
2149 Tab tab = mTabControl.createNewTab();
2150 if (tab != null) {
2151 addTab(tab);
2152 WebView view = tab.getWebView();
2153 loadUrl(view, url);
2154 }
2155 return tab;
2156 } else {
2157 return openTabAndShow(url, false, null);
2158 }
2159 }
2160
2161 @Override
2162 public Tab openIncognitoTab() {
2163 if (mTabControl.canCreateNewTab()) {
2164 Tab currentTab = mTabControl.getCurrentTab();
2165 Tab tab = mTabControl.createNewTab(false, null, null, true);
2166 addTab(tab);
2167 setActiveTab(tab);
2168 return tab;
2169 }
2170 return null;
2171 }
2172
2173 /**
2174 * @param index Index of the tab to change to, as defined by
2175 * mTabControl.getTabIndex(Tab t).
2176 * @return boolean True if we successfully switched to a different tab. If
2177 * the indexth tab is null, or if that tab is the same as
2178 * the current one, return false.
2179 */
2180 @Override
2181 public boolean switchToTab(int index) {
2182 Tab tab = mTabControl.getTab(index);
2183 Tab currentTab = mTabControl.getCurrentTab();
2184 if (tab == null || tab == currentTab) {
2185 return false;
2186 }
2187 setActiveTab(tab);
2188 return true;
2189 }
2190
2191 @Override
2192 public Tab openTabToHomePage() {
2193 return openTabAndShow(mSettings.getHomePage(), false, null);
2194 }
2195
2196 @Override
2197 public void closeCurrentTab() {
2198 final Tab current = mTabControl.getCurrentTab();
2199 if (mTabControl.getTabCount() == 1) {
2200 // This is the last tab. Open a new one, with the home
2201 // page and close the current one.
2202 openTabToHomePage();
2203 closeTab(current);
2204 return;
2205 }
2206 final Tab parent = current.getParentTab();
2207 int indexToShow = -1;
2208 if (parent != null) {
2209 indexToShow = mTabControl.getTabIndex(parent);
2210 } else {
2211 final int currentIndex = mTabControl.getCurrentIndex();
2212 // Try to move to the tab to the right
2213 indexToShow = currentIndex + 1;
2214 if (indexToShow > mTabControl.getTabCount() - 1) {
2215 // Try to move to the tab to the left
2216 indexToShow = currentIndex - 1;
2217 }
2218 }
2219 if (switchToTab(indexToShow)) {
2220 // Close window
2221 closeTab(current);
2222 }
2223 }
2224
2225 /**
2226 * Close the tab, remove its associated title bar, and adjust mTabControl's
2227 * current tab to a valid value.
2228 */
2229 @Override
2230 public void closeTab(Tab tab) {
2231 int currentIndex = mTabControl.getCurrentIndex();
2232 int removeIndex = mTabControl.getTabIndex(tab);
2233 removeTab(tab);
2234 if (currentIndex >= removeIndex && currentIndex != 0) {
2235 currentIndex--;
2236 }
2237 Tab newtab = mTabControl.getTab(currentIndex);
2238 setActiveTab(newtab);
2239 if (!mTabControl.hasAnyOpenIncognitoTabs()) {
Steve Block83101a82010-11-26 11:33:35 +00002240 WebView.cleanupPrivateBrowsingFiles();
Michael Kolb8233fac2010-10-26 16:08:53 -07002241 }
2242 }
2243
2244 /**************** TODO: Url loading clean up *******************************/
2245
2246 // Called when loading from context menu or LOAD_URL message
2247 protected void loadUrlFromContext(WebView view, String url) {
2248 // In case the user enters nothing.
2249 if (url != null && url.length() != 0 && view != null) {
2250 url = UrlUtils.smartUrlFilter(url);
2251 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2252 loadUrl(view, url);
2253 }
2254 }
2255 }
2256
2257 /**
2258 * Load the URL into the given WebView and update the title bar
2259 * to reflect the new load. Call this instead of WebView.loadUrl
2260 * directly.
2261 * @param view The WebView used to load url.
2262 * @param url The URL to load.
2263 */
2264 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002265 view.loadUrl(url);
2266 }
2267
2268 /**
2269 * Load UrlData into a Tab and update the title bar to reflect the new
2270 * load. Call this instead of UrlData.loadIn directly.
2271 * @param t The Tab used to load.
2272 * @param data The UrlData being loaded.
2273 */
2274 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002275 data.loadIn(t);
2276 }
2277
2278 /**
2279 * Resets the browser title-view to whatever it must be
2280 * (for example, if we had a loading error)
2281 * When we have a new page, we call resetTitle, when we
2282 * have to reset the titlebar to whatever it used to be
2283 * (for example, if the user chose to stop loading), we
2284 * call resetTitleAndRevertLockIcon.
2285 */
2286 public void resetTitleAndRevertLockIcon(Tab tab) {
2287 mUi.resetTitleAndRevertLockIcon(tab);
2288 }
2289
2290 void resetTitleAndIcon(Tab tab) {
2291 mUi.resetTitleAndIcon(tab);
2292 }
2293
2294 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002295 * Sets a title composed of the URL and the title string.
2296 * @param url The URL of the site being loaded.
2297 * @param title The title of the site being loaded.
2298 */
2299 void setUrlTitle(Tab tab, String url, String title) {
2300 tab.setCurrentUrl(url);
2301 tab.setCurrentTitle(title);
2302 // If we are in voice search mode, the title has already been set.
2303 if (tab.isInVoiceSearchMode()) return;
2304 mUi.setUrlTitle(tab, url, title);
2305 }
2306
2307 void goBackOnePageOrQuit() {
2308 Tab current = mTabControl.getCurrentTab();
2309 if (current == null) {
2310 /*
2311 * Instead of finishing the activity, simply push this to the back
2312 * of the stack and let ActivityManager to choose the foreground
2313 * activity. As BrowserActivity is singleTask, it will be always the
2314 * root of the task. So we can use either true or false for
2315 * moveTaskToBack().
2316 */
2317 mActivity.moveTaskToBack(true);
2318 return;
2319 }
2320 WebView w = current.getWebView();
2321 if (w.canGoBack()) {
2322 w.goBack();
2323 } else {
2324 // Check to see if we are closing a window that was created by
2325 // another window. If so, we switch back to that window.
2326 Tab parent = current.getParentTab();
2327 if (parent != null) {
2328 switchToTab(mTabControl.getTabIndex(parent));
2329 // Now we close the other tab
2330 closeTab(current);
2331 } else {
2332 if (current.closeOnExit()) {
2333 // force the tab's inLoad() to be false as we are going to
2334 // either finish the activity or remove the tab. This will
2335 // ensure pauseWebViewTimers() taking action.
Michael Kolb70976932010-11-30 11:34:01 -08002336 current.clearInPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07002337 if (mTabControl.getTabCount() == 1) {
2338 mActivity.finish();
2339 return;
2340 }
2341 if (mActivityPaused) {
2342 Log.e(LOGTAG, "BrowserActivity is already paused "
2343 + "while handing goBackOnePageOrQuit.");
2344 }
Michael Kolb70976932010-11-30 11:34:01 -08002345 pauseWebViewTimers(current);
Michael Kolb8233fac2010-10-26 16:08:53 -07002346 removeTab(current);
2347 }
2348 /*
2349 * Instead of finishing the activity, simply push this to the back
2350 * of the stack and let ActivityManager to choose the foreground
2351 * activity. As BrowserActivity is singleTask, it will be always the
2352 * root of the task. So we can use either true or false for
2353 * moveTaskToBack().
2354 */
2355 mActivity.moveTaskToBack(true);
2356 }
2357 }
2358 }
2359
2360 /**
2361 * Feed the previously stored results strings to the BrowserProvider so that
2362 * the SearchDialog will show them instead of the standard searches.
2363 * @param result String to show on the editable line of the SearchDialog.
2364 */
2365 @Override
2366 public void showVoiceSearchResults(String result) {
2367 ContentProviderClient client = mActivity.getContentResolver()
2368 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2369 ContentProvider prov = client.getLocalContentProvider();
2370 BrowserProvider bp = (BrowserProvider) prov;
2371 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2372 client.release();
2373
2374 Bundle bundle = createGoogleSearchSourceBundle(
2375 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2376 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2377 startSearch(result, false, bundle, false);
2378 }
2379
2380 private void startSearch(String initialQuery, boolean selectInitialQuery,
2381 Bundle appSearchData, boolean globalSearch) {
2382 if (appSearchData == null) {
2383 appSearchData = createGoogleSearchSourceBundle(
2384 GOOGLE_SEARCH_SOURCE_TYPE);
2385 }
2386
2387 SearchEngine searchEngine = mSettings.getSearchEngine();
2388 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2389 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2390 }
2391 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2392 globalSearch);
2393 }
2394
2395 private Bundle createGoogleSearchSourceBundle(String source) {
2396 Bundle bundle = new Bundle();
2397 bundle.putString(Search.SOURCE, source);
2398 return bundle;
2399 }
2400
2401 /**
2402 * handle key events in browser
2403 *
2404 * @param keyCode
2405 * @param event
2406 * @return true if handled, false to pass to super
2407 */
2408 boolean onKeyDown(int keyCode, KeyEvent event) {
2409 // Even if MENU is already held down, we need to call to super to open
2410 // the IME on long press.
2411 if (KeyEvent.KEYCODE_MENU == keyCode) {
2412 mMenuIsDown = true;
2413 return false;
2414 }
2415 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2416 // still down, we don't want to trigger the search. Pretend to consume
2417 // the key and do nothing.
2418 if (mMenuIsDown) return true;
2419
2420 switch(keyCode) {
2421 case KeyEvent.KEYCODE_SPACE:
2422 // WebView/WebTextView handle the keys in the KeyDown. As
2423 // the Activity's shortcut keys are only handled when WebView
2424 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2425 if (event.isShiftPressed()) {
2426 pageUp();
2427 } else {
2428 pageDown();
2429 }
2430 return true;
2431 case KeyEvent.KEYCODE_BACK:
2432 if (event.getRepeatCount() == 0) {
2433 event.startTracking();
2434 return true;
2435 } else if (mUi.showsWeb()
2436 && event.isLongPress()) {
2437 bookmarksOrHistoryPicker(true);
2438 return true;
2439 }
2440 break;
2441 }
2442 return false;
2443 }
2444
2445 boolean onKeyUp(int keyCode, KeyEvent event) {
2446 switch(keyCode) {
2447 case KeyEvent.KEYCODE_MENU:
2448 mMenuIsDown = false;
2449 break;
2450 case KeyEvent.KEYCODE_BACK:
2451 if (event.isTracking() && !event.isCanceled()) {
2452 onBackKey();
2453 return true;
2454 }
2455 break;
2456 }
2457 return false;
2458 }
2459
2460 public boolean isMenuDown() {
2461 return mMenuIsDown;
2462 }
2463
Ben Murdoch8029a772010-11-16 11:58:21 +00002464 public void setupAutoFill(Message message) {
2465 // Open the settings activity at the AutoFill profile fragment so that
2466 // the user can create a new profile. When they return, we will dispatch
2467 // the message so that we can autofill the form using their new profile.
2468 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2469 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2470 AutoFillSettingsFragment.class.getName());
2471 mAutoFillSetupMessage = message;
2472 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2473 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002474}