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