blob: d49a778bd9c780f9843f54ec6399e16dd8ea8c35 [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 }
321 }
322
323 void setWebViewFactory(WebViewFactory factory) {
324 mFactory = factory;
325 }
326
Michael Kolb1514bb72010-11-22 09:11:48 -0800327 @Override
328 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700329 return mFactory;
330 }
331
332 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800333 public void onSetWebView(Tab tab, WebView view) {
334 mUi.onSetWebView(tab, view);
335 }
336
337 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800338 public void createSubWindow(Tab tab) {
339 endActionMode();
340 WebView mainView = tab.getWebView();
341 WebView subView = mFactory.createWebView((mainView == null)
342 ? false
343 : mainView.isPrivateBrowsingEnabled());
344 mUi.createSubWindow(tab, subView);
345 }
346
347 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700348 public Activity getActivity() {
349 return mActivity;
350 }
351
352 void setUi(UI ui) {
353 mUi = ui;
354 }
355
356 BrowserSettings getSettings() {
357 return mSettings;
358 }
359
360 IntentHandler getIntentHandler() {
361 return mIntentHandler;
362 }
363
364 @Override
365 public UI getUi() {
366 return mUi;
367 }
368
369 int getMaxTabs() {
370 return mActivity.getResources().getInteger(R.integer.max_tabs);
371 }
372
373 @Override
374 public TabControl getTabControl() {
375 return mTabControl;
376 }
377
Michael Kolb1bf23132010-11-19 12:55:12 -0800378 @Override
379 public List<Tab> getTabs() {
380 return mTabControl.getTabs();
381 }
382
Michael Kolb8233fac2010-10-26 16:08:53 -0700383 // Open the icon database and retain all the icons for visited sites.
Ben Murdoch9446b932010-11-25 16:20:14 +0000384 // This is done on a background thread so as not to stall startup.
Michael Kolb8233fac2010-10-26 16:08:53 -0700385 private void retainIconsOnStartup() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000386 // WebIconDatabase needs to be retrieved on the UI thread so that if
387 // it has not been created successfully yet the Handler is started on the
388 // UI thread.
389 new RetainIconsOnStartupTask(WebIconDatabase.getInstance()).execute();
390 }
391
392 private class RetainIconsOnStartupTask extends AsyncTask<Void, Void, Void> {
393 private WebIconDatabase mDb;
394
395 public RetainIconsOnStartupTask(WebIconDatabase db) {
396 mDb = db;
397 }
398
399 protected Void doInBackground(Void... unused) {
400 mDb.open(mActivity.getDir("icons", 0).getPath());
401 Cursor c = null;
402 try {
403 c = Browser.getAllBookmarks(mActivity.getContentResolver());
404 if (c.moveToFirst()) {
405 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
406 do {
407 String url = c.getString(urlIndex);
408 mDb.retainIconForPageUrl(url);
409 } while (c.moveToNext());
410 }
411 } catch (IllegalStateException e) {
412 Log.e(LOGTAG, "retainIconsOnStartup", e);
413 } finally {
414 if (c != null) c.close();
Michael Kolb8233fac2010-10-26 16:08:53 -0700415 }
Ben Murdoch9446b932010-11-25 16:20:14 +0000416
417 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700418 }
419 }
420
421 private void startHandler() {
422 mHandler = new Handler() {
423
424 @Override
425 public void handleMessage(Message msg) {
426 switch (msg.what) {
427 case OPEN_BOOKMARKS:
428 bookmarksOrHistoryPicker(false);
429 break;
430 case FOCUS_NODE_HREF:
431 {
432 String url = (String) msg.getData().get("url");
433 String title = (String) msg.getData().get("title");
434 if (TextUtils.isEmpty(url)) {
435 break;
436 }
437 HashMap focusNodeMap = (HashMap) msg.obj;
438 WebView view = (WebView) focusNodeMap.get("webview");
439 // Only apply the action if the top window did not change.
440 if (getCurrentTopWebView() != view) {
441 break;
442 }
443 switch (msg.arg1) {
444 case R.id.open_context_menu_id:
445 case R.id.view_image_context_menu_id:
446 loadUrlFromContext(getCurrentTopWebView(), url);
447 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500448 case R.id.open_newtab_context_menu_id:
449 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -0800450 final Tab newTab = openTab(parent, url, false);
Leon Scroggins026f2542010-11-22 13:26:12 -0500451 if (newTab != null && newTab != parent) {
452 parent.addChildTab(newTab);
453 }
454 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700455 case R.id.bookmark_context_menu_id:
456 Intent intent = new Intent(mActivity,
457 AddBookmarkPage.class);
458 intent.putExtra(BrowserContract.Bookmarks.URL, url);
459 intent.putExtra(BrowserContract.Bookmarks.TITLE,
460 title);
461 mActivity.startActivity(intent);
462 break;
463 case R.id.share_link_context_menu_id:
464 sharePage(mActivity, title, url, null,
465 null);
466 break;
467 case R.id.copy_link_context_menu_id:
468 copy(url);
469 break;
470 case R.id.save_link_context_menu_id:
471 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500472 DownloadHandler.onDownloadStartNoStream(
473 mActivity, url, null, null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -0700474 break;
475 }
476 break;
477 }
478
479 case LOAD_URL:
480 loadUrlFromContext(getCurrentTopWebView(), (String) msg.obj);
481 break;
482
483 case STOP_LOAD:
484 stopLoading();
485 break;
486
487 case RELEASE_WAKELOCK:
488 if (mWakeLock.isHeld()) {
489 mWakeLock.release();
490 // if we reach here, Browser should be still in the
491 // background loading after WAKELOCK_TIMEOUT (5-min).
492 // To avoid burning the battery, stop loading.
493 mTabControl.stopAllLoading();
494 }
495 break;
496
497 case UPDATE_BOOKMARK_THUMBNAIL:
498 WebView view = (WebView) msg.obj;
499 if (view != null) {
500 updateScreenshot(view);
501 }
502 break;
503 }
504 }
505 };
506
507 }
508
Michael Kolbba99c5d2010-11-29 14:57:41 -0800509 @Override
510 public void shareCurrentPage() {
511 shareCurrentPage(mTabControl.getCurrentTab());
512 }
513
514 private void shareCurrentPage(Tab tab) {
515 if (tab != null) {
516 tab.populatePickerData();
517 sharePage(mActivity, tab.getTitle(),
518 tab.getUrl(), tab.getFavicon(),
519 createScreenshot(tab.getWebView(),
520 getDesiredThumbnailWidth(mActivity),
521 getDesiredThumbnailHeight(mActivity)));
522 }
523 }
524
Michael Kolb8233fac2010-10-26 16:08:53 -0700525 /**
526 * Share a page, providing the title, url, favicon, and a screenshot. Uses
527 * an {@link Intent} to launch the Activity chooser.
528 * @param c Context used to launch a new Activity.
529 * @param title Title of the page. Stored in the Intent with
530 * {@link Intent#EXTRA_SUBJECT}
531 * @param url URL of the page. Stored in the Intent with
532 * {@link Intent#EXTRA_TEXT}
533 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
534 * with {@link Browser#EXTRA_SHARE_FAVICON}
535 * @param screenshot Bitmap of a screenshot of the page. Stored in the
536 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
537 */
538 static final void sharePage(Context c, String title, String url,
539 Bitmap favicon, Bitmap screenshot) {
540 Intent send = new Intent(Intent.ACTION_SEND);
541 send.setType("text/plain");
542 send.putExtra(Intent.EXTRA_TEXT, url);
543 send.putExtra(Intent.EXTRA_SUBJECT, title);
544 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
545 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
546 try {
547 c.startActivity(Intent.createChooser(send, c.getString(
548 R.string.choosertitle_sharevia)));
549 } catch(android.content.ActivityNotFoundException ex) {
550 // if no app handles it, do nothing
551 }
552 }
553
554 private void copy(CharSequence text) {
555 ClipboardManager cm = (ClipboardManager) mActivity
556 .getSystemService(Context.CLIPBOARD_SERVICE);
557 cm.setText(text);
558 }
559
560 // lifecycle
561
562 protected void onConfgurationChanged(Configuration config) {
563 mConfigChanged = true;
564 if (mPageDialogsHandler != null) {
565 mPageDialogsHandler.onConfigurationChanged(config);
566 }
567 mUi.onConfigurationChanged(config);
568 }
569
570 @Override
571 public void handleNewIntent(Intent intent) {
572 mIntentHandler.onNewIntent(intent);
573 }
574
575 protected void onPause() {
576 if (mActivityPaused) {
577 Log.e(LOGTAG, "BrowserActivity is already paused.");
578 return;
579 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700580 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800581 Tab tab = mTabControl.getCurrentTab();
582 if (tab != null) {
583 tab.pause();
584 if (!pauseWebViewTimers(tab)) {
585 mWakeLock.acquire();
586 mHandler.sendMessageDelayed(mHandler
587 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
588 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700589 }
590 mUi.onPause();
591 mNetworkHandler.onPause();
592
593 WebView.disablePlatformNotifications();
594 }
595
596 void onSaveInstanceState(Bundle outState) {
597 // the default implementation requires each view to have an id. As the
598 // browser handles the state itself and it doesn't use id for the views,
599 // don't call the default implementation. Otherwise it will trigger the
600 // warning like this, "couldn't save which view has focus because the
601 // focused view XXX has no id".
602
603 // Save all the tabs
604 mTabControl.saveState(outState);
605 // Save time so that we know how old incognito tabs (if any) are.
606 outState.putSerializable("lastActiveDate", Calendar.getInstance());
607 }
608
609 void onResume() {
610 if (!mActivityPaused) {
611 Log.e(LOGTAG, "BrowserActivity is already resumed.");
612 return;
613 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700614 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800615 Tab current = mTabControl.getCurrentTab();
616 if (current != null) {
617 current.resume();
618 resumeWebViewTimers(current);
619 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700620 if (mWakeLock.isHeld()) {
621 mHandler.removeMessages(RELEASE_WAKELOCK);
622 mWakeLock.release();
623 }
624 mUi.onResume();
625 mNetworkHandler.onResume();
626 WebView.enablePlatformNotifications();
627 }
628
Michael Kolb70976932010-11-30 11:34:01 -0800629 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800630 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800631 * @param tab guaranteed non-null
632 */
633 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700634 boolean inLoad = tab.inPageLoad();
635 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
636 CookieSyncManager.getInstance().startSync();
637 WebView w = tab.getWebView();
638 if (w != null) {
639 w.resumeTimers();
640 }
641 }
642 }
643
Michael Kolb70976932010-11-30 11:34:01 -0800644 /**
645 * Pause all WebView timers using the WebView of the given tab
646 * @param tab
647 * @return true if the timers are paused or tab is null
648 */
649 private boolean pauseWebViewTimers(Tab tab) {
650 if (tab == null) {
651 return true;
652 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700653 CookieSyncManager.getInstance().stopSync();
654 WebView w = getCurrentWebView();
655 if (w != null) {
656 w.pauseTimers();
657 }
658 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700659 }
Michael Kolb70976932010-11-30 11:34:01 -0800660 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700661 }
662
663 void onDestroy() {
664 if (mUploadHandler != null) {
665 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
666 mUploadHandler = null;
667 }
668 if (mTabControl == null) return;
669 mUi.onDestroy();
670 // Remove the current tab and sub window
671 Tab t = mTabControl.getCurrentTab();
672 if (t != null) {
673 dismissSubWindow(t);
674 removeTab(t);
675 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500676 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700677 // Destroy all the tabs
678 mTabControl.destroy();
679 WebIconDatabase.getInstance().close();
680 // Stop watching the default geolocation permissions
681 mSystemAllowGeolocationOrigins.stop();
682 mSystemAllowGeolocationOrigins = null;
683 }
684
685 protected boolean isActivityPaused() {
686 return mActivityPaused;
687 }
688
689 protected void onLowMemory() {
690 mTabControl.freeMemory();
691 }
692
693 @Override
694 public boolean shouldShowErrorConsole() {
695 return mShouldShowErrorConsole;
696 }
697
698 protected void setShouldShowErrorConsole(boolean show) {
699 if (show == mShouldShowErrorConsole) {
700 // Nothing to do.
701 return;
702 }
703 mShouldShowErrorConsole = show;
704 Tab t = mTabControl.getCurrentTab();
705 if (t == null) {
706 // There is no current tab so we cannot toggle the error console
707 return;
708 }
709 mUi.setShouldShowErrorConsole(t, show);
710 }
711
712 @Override
713 public void stopLoading() {
714 mLoadStopped = true;
715 Tab tab = mTabControl.getCurrentTab();
716 resetTitleAndRevertLockIcon(tab);
717 WebView w = getCurrentTopWebView();
718 w.stopLoading();
719 // FIXME: before refactor, it is using mWebViewClient. So I keep the
720 // same logic here. But for subwindow case, should we call into the main
721 // WebView's onPageFinished as we never call its onPageStarted and if
722 // the page finishes itself, we don't call onPageFinished.
723 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
724 w.getUrl());
725 mUi.onPageStopped(tab);
726 }
727
728 boolean didUserStopLoading() {
729 return mLoadStopped;
730 }
731
732 // WebViewController
733
734 @Override
735 public void onPageStarted(Tab tab, WebView view, String url, Bitmap favicon) {
736
737 // We've started to load a new page. If there was a pending message
738 // to save a screenshot then we will now take the new page and save
739 // an incorrect screenshot. Therefore, remove any pending thumbnail
740 // messages from the queue.
741 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
742 view);
743
744 // reset sync timer to avoid sync starts during loading a page
745 CookieSyncManager.getInstance().resetSync();
746
747 if (!mNetworkHandler.isNetworkUp()) {
748 view.setNetworkAvailable(false);
749 }
750
751 // when BrowserActivity just starts, onPageStarted may be called before
752 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
753 // to start the timer. As we won't switch tabs while an activity is in
754 // pause state, we can ensure calling resume and pause in pair.
755 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800756 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700757 }
758 mLoadStopped = false;
759 if (!mNetworkHandler.isNetworkUp()) {
760 mNetworkHandler.createAndShowNetworkDialog();
761 }
762 endActionMode();
763
764 mUi.onPageStarted(tab, url, favicon);
765
Michael Kolb8233fac2010-10-26 16:08:53 -0700766 // update the bookmark database for favicon
767 maybeUpdateFavicon(tab, null, url, favicon);
768
769 Performance.tracePageStart(url);
770
771 // Performance probe
772 if (false) {
773 Performance.onPageStarted();
774 }
775
776 }
777
778 @Override
779 public void onPageFinished(Tab tab, String url) {
780 mUi.onPageFinished(tab, url);
781 if (!tab.isPrivateBrowsingEnabled()) {
782 if (tab.inForeground() && !didUserStopLoading()
783 || !tab.inForeground()) {
784 // Only update the bookmark screenshot if the user did not
785 // cancel the load early.
786 mHandler.sendMessageDelayed(mHandler.obtainMessage(
787 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab.getWebView()),
788 500);
789 }
790 }
791 // pause the WebView timer and release the wake lock if it is finished
792 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800793 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700794 if (mWakeLock.isHeld()) {
795 mHandler.removeMessages(RELEASE_WAKELOCK);
796 mWakeLock.release();
797 }
798 }
799 // Performance probe
800 if (false) {
801 Performance.onPageFinished(url);
802 }
803
804 Performance.tracePageFinished();
805 }
806
807 @Override
808 public void onProgressChanged(Tab tab, int newProgress) {
809
810 if (newProgress == 100) {
811 CookieSyncManager.getInstance().sync();
812 // onProgressChanged() may continue to be called after the main
813 // frame has finished loading, as any remaining sub frames continue
814 // to load. We'll only get called once though with newProgress as
815 // 100 when everything is loaded. (onPageFinished is called once
816 // when the main frame completes loading regardless of the state of
817 // any sub frames so calls to onProgressChanges may continue after
818 // onPageFinished has executed)
819 if (mInLoad) {
820 mInLoad = false;
821 updateInLoadMenuItems(mCachedMenu);
822 }
823 } else {
824 if (!mInLoad) {
825 // onPageFinished may have already been called but a subframe is
826 // still loading and updating the progress. Reset mInLoad and
827 // update the menu items.
828 mInLoad = true;
829 updateInLoadMenuItems(mCachedMenu);
830 }
831 }
832 mUi.onProgressChanged(tab, newProgress);
833 }
834
835 @Override
836 public void onReceivedTitle(Tab tab, final String title) {
837 final String pageUrl = tab.getWebView().getUrl();
838 setUrlTitle(tab, pageUrl, title);
839 if (pageUrl == null || pageUrl.length()
840 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
841 return;
842 }
843 // Update the title in the history database if not in private browsing mode
844 if (!tab.isPrivateBrowsingEnabled()) {
John Reck0ebd3ac2010-12-09 11:14:04 -0800845 mDataController.updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700846 }
847 }
848
849 @Override
850 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
851 mUi.setFavicon(tab, icon);
852 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
853 }
854
855 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800856 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
857 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700858 }
859
860 @Override
861 public boolean shouldOverrideKeyEvent(KeyEvent event) {
862 if (mMenuIsDown) {
863 // only check shortcut key when MENU is held
864 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
865 event);
866 } else {
867 return false;
868 }
869 }
870
871 @Override
872 public void onUnhandledKeyEvent(KeyEvent event) {
873 if (!isActivityPaused()) {
874 if (event.getAction() == KeyEvent.ACTION_DOWN) {
875 mActivity.onKeyDown(event.getKeyCode(), event);
876 } else {
877 mActivity.onKeyUp(event.getKeyCode(), event);
878 }
879 }
880 }
881
882 @Override
883 public void doUpdateVisitedHistory(Tab tab, String url,
884 boolean isReload) {
885 // Don't save anything in private browsing mode
886 if (tab.isPrivateBrowsingEnabled()) return;
887
888 if (url.regionMatches(true, 0, "about:", 0, 6)) {
889 return;
890 }
John Reck0ebd3ac2010-12-09 11:14:04 -0800891 mDataController.updateVisitedHistory(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700892 WebIconDatabase.getInstance().retainIconForPageUrl(url);
893 }
894
895 @Override
896 public void getVisitedHistory(final ValueCallback<String[]> callback) {
897 AsyncTask<Void, Void, String[]> task =
898 new AsyncTask<Void, Void, String[]>() {
899 @Override
900 public String[] doInBackground(Void... unused) {
901 return Browser.getVisitedHistory(mActivity.getContentResolver());
902 }
903 @Override
904 public void onPostExecute(String[] result) {
905 callback.onReceiveValue(result);
906 }
907 };
908 task.execute();
909 }
910
911 @Override
912 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
913 final HttpAuthHandler handler, final String host,
914 final String realm) {
915 String username = null;
916 String password = null;
917
918 boolean reuseHttpAuthUsernamePassword
919 = handler.useHttpAuthUsernamePassword();
920
921 if (reuseHttpAuthUsernamePassword && view != null) {
922 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
923 if (credentials != null && credentials.length == 2) {
924 username = credentials[0];
925 password = credentials[1];
926 }
927 }
928
929 if (username != null && password != null) {
930 handler.proceed(username, password);
931 } else {
932 if (tab.inForeground()) {
933 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
934 } else {
935 handler.cancel();
936 }
937 }
938 }
939
940 @Override
941 public void onDownloadStart(Tab tab, String url, String userAgent,
942 String contentDisposition, String mimetype, long contentLength) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500943 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
944 contentDisposition, mimetype);
Michael Kolb8233fac2010-10-26 16:08:53 -0700945 if (tab.getWebView().copyBackForwardList().getSize() == 0) {
946 // This Tab was opened for the sole purpose of downloading a
947 // file. Remove it.
948 if (tab == mTabControl.getCurrentTab()) {
949 // In this case, the Tab is still on top.
950 goBackOnePageOrQuit();
951 } else {
952 // In this case, it is not.
953 closeTab(tab);
954 }
955 }
956 }
957
958 @Override
959 public Bitmap getDefaultVideoPoster() {
960 return mUi.getDefaultVideoPoster();
961 }
962
963 @Override
964 public View getVideoLoadingProgressView() {
965 return mUi.getVideoLoadingProgressView();
966 }
967
968 @Override
969 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
970 SslError error) {
971 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
972 }
973
974 // helper method
975
976 /*
977 * Update the favorites icon if the private browsing isn't enabled and the
978 * icon is valid.
979 */
980 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
981 final String url, Bitmap favicon) {
982 if (favicon == null) {
983 return;
984 }
985 if (!tab.isPrivateBrowsingEnabled()) {
986 Bookmarks.updateFavicon(mActivity
987 .getContentResolver(), originalUrl, url, favicon);
988 }
989 }
990
Leon Scroggins4cd97792010-12-03 15:31:56 -0500991 @Override
992 public void bookmarkedStatusHasChanged(Tab tab) {
993 mUi.bookmarkedStatusHasChanged(tab);
994 }
995
Michael Kolb8233fac2010-10-26 16:08:53 -0700996 // end WebViewController
997
998 protected void pageUp() {
999 getCurrentTopWebView().pageUp(false);
1000 }
1001
1002 protected void pageDown() {
1003 getCurrentTopWebView().pageDown(false);
1004 }
1005
1006 // callback from phone title bar
1007 public void editUrl() {
1008 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
1009 String url = (getCurrentTopWebView() == null) ? null : getCurrentTopWebView().getUrl();
1010 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1011 null, false);
1012 }
1013
Michael Kolbcfa3af52010-12-14 10:36:11 -08001014 public void startVoiceSearch() {
1015 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1016 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1017 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1018 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1019 mActivity.getComponentName().flattenToString());
1020 intent.putExtra(SEND_APP_ID_EXTRA, false);
1021 mActivity.startActivity(intent);
1022 }
1023
Michael Kolb8233fac2010-10-26 16:08:53 -07001024 public void activateVoiceSearchMode(String title) {
1025 mUi.showVoiceTitleBar(title);
1026 }
1027
1028 public void revertVoiceSearchMode(Tab tab) {
1029 mUi.revertVoiceTitleBar(tab);
1030 }
1031
1032 public void showCustomView(Tab tab, View view,
1033 WebChromeClient.CustomViewCallback callback) {
1034 if (tab.inForeground()) {
1035 if (mUi.isCustomViewShowing()) {
1036 callback.onCustomViewHidden();
1037 return;
1038 }
1039 mUi.showCustomView(view, callback);
1040 // Save the menu state and set it to empty while the custom
1041 // view is showing.
1042 mOldMenuState = mMenuState;
1043 mMenuState = EMPTY_MENU;
1044 }
1045 }
1046
1047 @Override
1048 public void hideCustomView() {
1049 if (mUi.isCustomViewShowing()) {
1050 mUi.onHideCustomView();
1051 // Reset the old menu state.
1052 mMenuState = mOldMenuState;
1053 mOldMenuState = EMPTY_MENU;
1054 }
1055 }
1056
1057 protected void onActivityResult(int requestCode, int resultCode,
1058 Intent intent) {
1059 if (getCurrentTopWebView() == null) return;
1060 switch (requestCode) {
1061 case PREFERENCES_PAGE:
1062 if (resultCode == Activity.RESULT_OK && intent != null) {
1063 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
1064 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
1065 mTabControl.removeParentChildRelationShips();
1066 }
1067 }
1068 break;
1069 case FILE_SELECTED:
1070 // Choose a file from the file picker.
1071 if (null == mUploadHandler) break;
1072 mUploadHandler.onResult(resultCode, intent);
1073 mUploadHandler = null;
1074 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001075 case AUTOFILL_SETUP:
1076 // Determine whether a profile was actually set up or not
1077 // and if so, send the message back to the WebTextView to
1078 // fill the form with the new profile.
1079 if (getSettings().getAutoFillProfile() != null) {
1080 mAutoFillSetupMessage.sendToTarget();
1081 mAutoFillSetupMessage = null;
1082 }
1083 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001084 default:
1085 break;
1086 }
1087 getCurrentTopWebView().requestFocus();
1088 }
1089
1090 /**
1091 * Open the Go page.
1092 * @param startWithHistory If true, open starting on the history tab.
1093 * Otherwise, start with the bookmarks tab.
1094 */
1095 @Override
1096 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1097 if (mTabControl.getCurrentWebView() == null) {
1098 return;
1099 }
1100 Bundle extras = new Bundle();
1101 // Disable opening in a new window if we have maxed out the windows
1102 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1103 !mTabControl.canCreateNewTab());
1104 mUi.showComboView(startWithHistory, extras);
1105 }
1106
1107 // combo view callbacks
1108
1109 /**
1110 * callback from ComboPage when clear history is requested
1111 */
1112 public void onRemoveParentChildRelationships() {
1113 mTabControl.removeParentChildRelationShips();
1114 }
1115
1116 /**
1117 * callback from ComboPage when bookmark/history selection
1118 */
1119 @Override
1120 public void onUrlSelected(String url, boolean newTab) {
1121 removeComboView();
1122 if (!TextUtils.isEmpty(url)) {
1123 if (newTab) {
Michael Kolb18eb3772010-12-10 14:29:51 -08001124 openTab(mTabControl.getCurrentTab(), url, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001125 } else {
1126 final Tab currentTab = mTabControl.getCurrentTab();
1127 dismissSubWindow(currentTab);
1128 loadUrl(getCurrentTopWebView(), url);
1129 }
1130 }
1131 }
1132
1133 /**
1134 * callback from ComboPage when dismissed
1135 */
1136 @Override
1137 public void onComboCanceled() {
1138 removeComboView();
1139 }
1140
1141 /**
1142 * dismiss the ComboPage
1143 */
1144 @Override
1145 public void removeComboView() {
1146 mUi.hideComboView();
1147 }
1148
1149 // active tabs page handling
1150
1151 protected void showActiveTabsPage() {
1152 mMenuState = EMPTY_MENU;
1153 mUi.showActiveTabsPage();
1154 }
1155
1156 /**
1157 * Remove the active tabs page.
1158 * @param needToAttach If true, the active tabs page did not attach a tab
1159 * to the content view, so we need to do that here.
1160 */
1161 @Override
1162 public void removeActiveTabsPage(boolean needToAttach) {
1163 mMenuState = R.id.MAIN_MENU;
1164 mUi.removeActiveTabsPage();
1165 if (needToAttach) {
1166 setActiveTab(mTabControl.getCurrentTab());
1167 }
1168 getCurrentTopWebView().requestFocus();
1169 }
1170
1171 // key handling
1172 protected void onBackKey() {
1173 if (!mUi.onBackKey()) {
1174 WebView subwindow = mTabControl.getCurrentSubWindow();
1175 if (subwindow != null) {
1176 if (subwindow.canGoBack()) {
1177 subwindow.goBack();
1178 } else {
1179 dismissSubWindow(mTabControl.getCurrentTab());
1180 }
1181 } else {
1182 goBackOnePageOrQuit();
1183 }
1184 }
1185 }
1186
1187 // menu handling and state
1188 // TODO: maybe put into separate handler
1189
1190 protected boolean onCreateOptionsMenu(Menu menu) {
1191 MenuInflater inflater = mActivity.getMenuInflater();
1192 inflater.inflate(R.menu.browser, menu);
1193 updateInLoadMenuItems(menu);
1194 // hold on to the menu reference here; it is used by the page callbacks
1195 // to update the menu based on loading state
1196 mCachedMenu = menu;
1197 return true;
1198 }
1199
1200 protected void onCreateContextMenu(ContextMenu menu, View v,
1201 ContextMenuInfo menuInfo) {
1202 if (v instanceof TitleBarBase) {
1203 return;
1204 }
1205 if (!(v instanceof WebView)) {
1206 return;
1207 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001208 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001209 WebView.HitTestResult result = webview.getHitTestResult();
1210 if (result == null) {
1211 return;
1212 }
1213
1214 int type = result.getType();
1215 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1216 Log.w(LOGTAG,
1217 "We should not show context menu when nothing is touched");
1218 return;
1219 }
1220 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1221 // let TextView handles context menu
1222 return;
1223 }
1224
1225 // Note, http://b/issue?id=1106666 is requesting that
1226 // an inflated menu can be used again. This is not available
1227 // yet, so inflate each time (yuk!)
1228 MenuInflater inflater = mActivity.getMenuInflater();
1229 inflater.inflate(R.menu.browsercontext, menu);
1230
1231 // Show the correct menu group
1232 final String extra = result.getExtra();
1233 menu.setGroupVisible(R.id.PHONE_MENU,
1234 type == WebView.HitTestResult.PHONE_TYPE);
1235 menu.setGroupVisible(R.id.EMAIL_MENU,
1236 type == WebView.HitTestResult.EMAIL_TYPE);
1237 menu.setGroupVisible(R.id.GEO_MENU,
1238 type == WebView.HitTestResult.GEO_TYPE);
1239 menu.setGroupVisible(R.id.IMAGE_MENU,
1240 type == WebView.HitTestResult.IMAGE_TYPE
1241 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1242 menu.setGroupVisible(R.id.ANCHOR_MENU,
1243 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1244 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001245 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1246 || type == WebView.HitTestResult.PHONE_TYPE
1247 || type == WebView.HitTestResult.EMAIL_TYPE
1248 || type == WebView.HitTestResult.GEO_TYPE;
1249 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1250 if (hitText) {
1251 menu.findItem(R.id.select_text_menu_id)
1252 .setOnMenuItemClickListener(new SelectText(webview));
1253 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001254 // Setup custom handling depending on the type
1255 switch (type) {
1256 case WebView.HitTestResult.PHONE_TYPE:
1257 menu.setHeaderTitle(Uri.decode(extra));
1258 menu.findItem(R.id.dial_context_menu_id).setIntent(
1259 new Intent(Intent.ACTION_VIEW, Uri
1260 .parse(WebView.SCHEME_TEL + extra)));
1261 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1262 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1263 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1264 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1265 addIntent);
1266 menu.findItem(R.id.copy_phone_context_menu_id)
1267 .setOnMenuItemClickListener(
1268 new Copy(extra));
1269 break;
1270
1271 case WebView.HitTestResult.EMAIL_TYPE:
1272 menu.setHeaderTitle(extra);
1273 menu.findItem(R.id.email_context_menu_id).setIntent(
1274 new Intent(Intent.ACTION_VIEW, Uri
1275 .parse(WebView.SCHEME_MAILTO + extra)));
1276 menu.findItem(R.id.copy_mail_context_menu_id)
1277 .setOnMenuItemClickListener(
1278 new Copy(extra));
1279 break;
1280
1281 case WebView.HitTestResult.GEO_TYPE:
1282 menu.setHeaderTitle(extra);
1283 menu.findItem(R.id.map_context_menu_id).setIntent(
1284 new Intent(Intent.ACTION_VIEW, Uri
1285 .parse(WebView.SCHEME_GEO
1286 + URLEncoder.encode(extra))));
1287 menu.findItem(R.id.copy_geo_context_menu_id)
1288 .setOnMenuItemClickListener(
1289 new Copy(extra));
1290 break;
1291
1292 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1293 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1294 TextView titleView = (TextView) LayoutInflater.from(mActivity)
1295 .inflate(android.R.layout.browser_link_context_header,
1296 null);
1297 titleView.setText(extra);
1298 menu.setHeaderView(titleView);
1299 // decide whether to show the open link in new tab option
1300 boolean showNewTab = mTabControl.canCreateNewTab();
1301 MenuItem newTabItem
1302 = menu.findItem(R.id.open_newtab_context_menu_id);
1303 newTabItem.setVisible(showNewTab);
1304 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001305 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1306 newTabItem.setOnMenuItemClickListener(
1307 new MenuItem.OnMenuItemClickListener() {
1308 @Override
1309 public boolean onMenuItemClick(MenuItem item) {
1310 final HashMap<String, WebView> hrefMap =
1311 new HashMap<String, WebView>();
1312 hrefMap.put("webview", webview);
1313 final Message msg = mHandler.obtainMessage(
1314 FOCUS_NODE_HREF,
1315 R.id.open_newtab_context_menu_id,
1316 0, hrefMap);
1317 webview.requestFocusNodeHref(msg);
1318 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001319 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001320 });
1321 } else {
1322 newTabItem.setOnMenuItemClickListener(
1323 new MenuItem.OnMenuItemClickListener() {
1324 @Override
1325 public boolean onMenuItemClick(MenuItem item) {
1326 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -08001327 final Tab newTab = openTab(parent,
1328 extra, false);
Leon Scroggins026f2542010-11-22 13:26:12 -05001329 if (newTab != parent) {
1330 parent.addChildTab(newTab);
1331 }
1332 return true;
1333 }
1334 });
1335 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001336 }
1337 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1338 Bookmarks.urlHasAcceptableScheme(extra));
1339 PackageManager pm = mActivity.getPackageManager();
1340 Intent send = new Intent(Intent.ACTION_SEND);
1341 send.setType("text/plain");
1342 ResolveInfo ri = pm.resolveActivity(send,
1343 PackageManager.MATCH_DEFAULT_ONLY);
1344 menu.findItem(R.id.share_link_context_menu_id)
1345 .setVisible(ri != null);
1346 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1347 break;
1348 }
1349 // otherwise fall through to handle image part
1350 case WebView.HitTestResult.IMAGE_TYPE:
1351 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1352 menu.setHeaderTitle(extra);
1353 }
1354 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1355 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1356 menu.findItem(R.id.download_context_menu_id).
Leon Scroggins63c02662010-11-18 15:16:27 -05001357 setOnMenuItemClickListener(new Download(mActivity, extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001358 menu.findItem(R.id.set_wallpaper_context_menu_id).
1359 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1360 extra));
1361 break;
1362
1363 default:
1364 Log.w(LOGTAG, "We should not get here.");
1365 break;
1366 }
1367 //update the ui
1368 mUi.onContextMenuCreated(menu);
1369 }
1370
1371 /**
1372 * As the menu can be open when loading state changes
1373 * we must manually update the state of the stop/reload menu
1374 * item
1375 */
1376 private void updateInLoadMenuItems(Menu menu) {
1377 if (menu == null) {
1378 return;
1379 }
1380 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1381 MenuItem src = mInLoad ?
1382 menu.findItem(R.id.stop_menu_id):
1383 menu.findItem(R.id.reload_menu_id);
1384 if (src != null) {
1385 dest.setIcon(src.getIcon());
1386 dest.setTitle(src.getTitle());
1387 }
1388 }
1389
1390 boolean prepareOptionsMenu(Menu menu) {
1391 // This happens when the user begins to hold down the menu key, so
1392 // allow them to chord to get a shortcut.
1393 mCanChord = true;
1394 // Note: setVisible will decide whether an item is visible; while
1395 // setEnabled() will decide whether an item is enabled, which also means
1396 // whether the matching shortcut key will function.
1397 switch (mMenuState) {
1398 case EMPTY_MENU:
1399 if (mCurrentMenuState != mMenuState) {
1400 menu.setGroupVisible(R.id.MAIN_MENU, false);
1401 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1402 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1403 }
1404 break;
1405 default:
1406 if (mCurrentMenuState != mMenuState) {
1407 menu.setGroupVisible(R.id.MAIN_MENU, true);
1408 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1409 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1410 }
1411 final WebView w = getCurrentTopWebView();
1412 boolean canGoBack = false;
1413 boolean canGoForward = false;
1414 boolean isHome = false;
1415 if (w != null) {
1416 canGoBack = w.canGoBack();
1417 canGoForward = w.canGoForward();
1418 isHome = mSettings.getHomePage().equals(w.getUrl());
1419 }
1420 final MenuItem back = menu.findItem(R.id.back_menu_id);
1421 back.setEnabled(canGoBack);
1422
1423 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1424 home.setEnabled(!isHome);
1425
1426 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1427 forward.setEnabled(canGoForward);
1428
1429 // decide whether to show the share link option
1430 PackageManager pm = mActivity.getPackageManager();
1431 Intent send = new Intent(Intent.ACTION_SEND);
1432 send.setType("text/plain");
1433 ResolveInfo ri = pm.resolveActivity(send,
1434 PackageManager.MATCH_DEFAULT_ONLY);
1435 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1436
1437 boolean isNavDump = mSettings.isNavDump();
1438 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1439 nav.setVisible(isNavDump);
1440 nav.setEnabled(isNavDump);
1441
1442 boolean showDebugSettings = mSettings.showDebugSettings();
1443 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1444 counter.setVisible(showDebugSettings);
1445 counter.setEnabled(showDebugSettings);
1446
1447 // allow the ui to adjust state based settings
1448 mUi.onPrepareOptionsMenu(menu);
1449
1450 break;
1451 }
1452 mCurrentMenuState = mMenuState;
1453 return true;
1454 }
1455
1456 public boolean onOptionsItemSelected(MenuItem item) {
1457 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1458 // menu remains active, so ensure comboview is dismissed
1459 // if main menu option is selected
1460 removeComboView();
1461 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001462 if (!mCanChord) {
1463 // The user has already fired a shortcut with this hold down of the
1464 // menu key.
1465 return false;
1466 }
1467 if (null == getCurrentTopWebView()) {
1468 return false;
1469 }
1470 if (mMenuIsDown) {
1471 // The shortcut action consumes the MENU. Even if it is still down,
1472 // it won't trigger the next shortcut action. In the case of the
1473 // shortcut action triggering a new activity, like Bookmarks, we
1474 // won't get onKeyUp for MENU. So it is important to reset it here.
1475 mMenuIsDown = false;
1476 }
1477 switch (item.getItemId()) {
1478 // -- Main menu
1479 case R.id.new_tab_menu_id:
1480 openTabToHomePage();
1481 break;
1482
1483 case R.id.incognito_menu_id:
1484 openIncognitoTab();
1485 break;
1486
1487 case R.id.goto_menu_id:
1488 editUrl();
1489 break;
1490
1491 case R.id.bookmarks_menu_id:
1492 bookmarksOrHistoryPicker(false);
1493 break;
1494
1495 case R.id.active_tabs_menu_id:
1496 showActiveTabsPage();
1497 break;
1498
1499 case R.id.add_bookmark_menu_id:
1500 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
1501 break;
1502
1503 case R.id.stop_reload_menu_id:
1504 if (mInLoad) {
1505 stopLoading();
1506 } else {
1507 getCurrentTopWebView().reload();
1508 }
1509 break;
1510
1511 case R.id.back_menu_id:
1512 getCurrentTopWebView().goBack();
1513 break;
1514
1515 case R.id.forward_menu_id:
1516 getCurrentTopWebView().goForward();
1517 break;
1518
1519 case R.id.close_menu_id:
1520 // Close the subwindow if it exists.
1521 if (mTabControl.getCurrentSubWindow() != null) {
1522 dismissSubWindow(mTabControl.getCurrentTab());
1523 break;
1524 }
1525 closeCurrentTab();
1526 break;
1527
1528 case R.id.homepage_menu_id:
1529 Tab current = mTabControl.getCurrentTab();
1530 if (current != null) {
1531 dismissSubWindow(current);
1532 loadUrl(current.getWebView(), mSettings.getHomePage());
1533 }
1534 break;
1535
1536 case R.id.preferences_menu_id:
1537 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1538 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1539 getCurrentTopWebView().getUrl());
1540 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1541 break;
1542
1543 case R.id.find_menu_id:
1544 getCurrentTopWebView().showFindDialog(null);
1545 break;
1546
1547 case R.id.page_info_menu_id:
1548 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1549 false);
1550 break;
1551
1552 case R.id.classic_history_menu_id:
1553 bookmarksOrHistoryPicker(true);
1554 break;
1555
1556 case R.id.title_bar_share_page_url:
1557 case R.id.share_page_menu_id:
1558 Tab currentTab = mTabControl.getCurrentTab();
1559 if (null == currentTab) {
1560 mCanChord = false;
1561 return false;
1562 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001563 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001564 break;
1565
1566 case R.id.dump_nav_menu_id:
1567 getCurrentTopWebView().debugDump();
1568 break;
1569
1570 case R.id.dump_counters_menu_id:
1571 getCurrentTopWebView().dumpV8Counters();
1572 break;
1573
1574 case R.id.zoom_in_menu_id:
1575 getCurrentTopWebView().zoomIn();
1576 break;
1577
1578 case R.id.zoom_out_menu_id:
1579 getCurrentTopWebView().zoomOut();
1580 break;
1581
1582 case R.id.view_downloads_menu_id:
1583 viewDownloads();
1584 break;
1585
1586 case R.id.window_one_menu_id:
1587 case R.id.window_two_menu_id:
1588 case R.id.window_three_menu_id:
1589 case R.id.window_four_menu_id:
1590 case R.id.window_five_menu_id:
1591 case R.id.window_six_menu_id:
1592 case R.id.window_seven_menu_id:
1593 case R.id.window_eight_menu_id:
1594 {
1595 int menuid = item.getItemId();
1596 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1597 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1598 Tab desiredTab = mTabControl.getTab(id);
1599 if (desiredTab != null &&
1600 desiredTab != mTabControl.getCurrentTab()) {
1601 switchToTab(id);
1602 }
1603 break;
1604 }
1605 }
1606 }
1607 break;
1608
1609 default:
1610 return false;
1611 }
1612 mCanChord = false;
1613 return true;
1614 }
1615
1616 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001617 // Let the History and Bookmark fragments handle menus they created.
1618 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1619 return false;
1620 }
1621
Michael Kolb8233fac2010-10-26 16:08:53 -07001622 // chording is not an issue with context menus, but we use the same
1623 // options selector, so set mCanChord to true so we can access them.
1624 mCanChord = true;
1625 int id = item.getItemId();
1626 boolean result = true;
1627 switch (id) {
1628 // For the context menu from the title bar
1629 case R.id.title_bar_copy_page_url:
1630 Tab currentTab = mTabControl.getCurrentTab();
1631 if (null == currentTab) {
1632 result = false;
1633 break;
1634 }
1635 WebView mainView = currentTab.getWebView();
1636 if (null == mainView) {
1637 result = false;
1638 break;
1639 }
1640 copy(mainView.getUrl());
1641 break;
1642 // -- Browser context menu
1643 case R.id.open_context_menu_id:
1644 case R.id.bookmark_context_menu_id:
1645 case R.id.save_link_context_menu_id:
1646 case R.id.share_link_context_menu_id:
1647 case R.id.copy_link_context_menu_id:
1648 final WebView webView = getCurrentTopWebView();
1649 if (null == webView) {
1650 result = false;
1651 break;
1652 }
1653 final HashMap<String, WebView> hrefMap =
1654 new HashMap<String, WebView>();
1655 hrefMap.put("webview", webView);
1656 final Message msg = mHandler.obtainMessage(
1657 FOCUS_NODE_HREF, id, 0, hrefMap);
1658 webView.requestFocusNodeHref(msg);
1659 break;
1660
1661 default:
1662 // For other context menus
1663 result = onOptionsItemSelected(item);
1664 }
1665 mCanChord = false;
1666 return result;
1667 }
1668
1669 /**
1670 * support programmatically opening the context menu
1671 */
1672 public void openContextMenu(View view) {
1673 mActivity.openContextMenu(view);
1674 }
1675
1676 /**
1677 * programmatically open the options menu
1678 */
1679 public void openOptionsMenu() {
1680 mActivity.openOptionsMenu();
1681 }
1682
1683 public boolean onMenuOpened(int featureId, Menu menu) {
1684 if (mOptionsMenuOpen) {
1685 if (mConfigChanged) {
1686 // We do not need to make any changes to the state of the
1687 // title bar, since the only thing that happened was a
1688 // change in orientation
1689 mConfigChanged = false;
1690 } else {
1691 if (!mExtendedMenuOpen) {
1692 mExtendedMenuOpen = true;
1693 mUi.onExtendedMenuOpened();
1694 } else {
1695 // Switching the menu back to icon view, so show the
1696 // title bar once again.
1697 mExtendedMenuOpen = false;
1698 mUi.onExtendedMenuClosed(mInLoad);
1699 mUi.onOptionsMenuOpened();
1700 }
1701 }
1702 } else {
1703 // The options menu is closed, so open it, and show the title
1704 mOptionsMenuOpen = true;
1705 mConfigChanged = false;
1706 mExtendedMenuOpen = false;
1707 mUi.onOptionsMenuOpened();
1708 }
1709 return true;
1710 }
1711
1712 public void onOptionsMenuClosed(Menu menu) {
1713 mOptionsMenuOpen = false;
1714 mUi.onOptionsMenuClosed(mInLoad);
1715 }
1716
1717 public void onContextMenuClosed(Menu menu) {
1718 mUi.onContextMenuClosed(menu, mInLoad);
1719 }
1720
1721 // Helper method for getting the top window.
1722 @Override
1723 public WebView getCurrentTopWebView() {
1724 return mTabControl.getCurrentTopWebView();
1725 }
1726
1727 @Override
1728 public WebView getCurrentWebView() {
1729 return mTabControl.getCurrentWebView();
1730 }
1731
1732 /*
1733 * This method is called as a result of the user selecting the options
1734 * menu to see the download window. It shows the download window on top of
1735 * the current window.
1736 */
1737 void viewDownloads() {
1738 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1739 mActivity.startActivity(intent);
1740 }
1741
1742 // action mode
1743
1744 void onActionModeStarted(ActionMode mode) {
1745 mUi.onActionModeStarted(mode);
1746 mActionMode = mode;
1747 }
1748
1749 /*
1750 * True if a custom ActionMode (i.e. find or select) is in use.
1751 */
1752 @Override
1753 public boolean isInCustomActionMode() {
1754 return mActionMode != null;
1755 }
1756
1757 /*
1758 * End the current ActionMode.
1759 */
1760 @Override
1761 public void endActionMode() {
1762 if (mActionMode != null) {
1763 mActionMode.finish();
1764 }
1765 }
1766
1767 /*
1768 * Called by find and select when they are finished. Replace title bars
1769 * as necessary.
1770 */
1771 public void onActionModeFinished(ActionMode mode) {
1772 if (!isInCustomActionMode()) return;
1773 mUi.onActionModeFinished(mInLoad);
1774 mActionMode = null;
1775 }
1776
1777 boolean isInLoad() {
1778 return mInLoad;
1779 }
1780
1781 // bookmark handling
1782
1783 /**
1784 * add the current page as a bookmark to the given folder id
1785 * @param folderId use -1 for the default folder
1786 */
1787 @Override
1788 public void bookmarkCurrentPage(long folderId) {
1789 Intent i = new Intent(mActivity,
1790 AddBookmarkPage.class);
1791 WebView w = getCurrentTopWebView();
1792 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1793 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1794 String touchIconUrl = w.getTouchIconUrl();
1795 if (touchIconUrl != null) {
1796 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1797 WebSettings settings = w.getSettings();
1798 if (settings != null) {
1799 i.putExtra(AddBookmarkPage.USER_AGENT,
1800 settings.getUserAgentString());
1801 }
1802 }
1803 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1804 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1805 getDesiredThumbnailHeight(mActivity)));
1806 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1807 i.putExtra(BrowserContract.Bookmarks.PARENT,
1808 folderId);
1809 // Put the dialog at the upper right of the screen, covering the
1810 // star on the title bar.
1811 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1812 mActivity.startActivity(i);
1813 }
1814
1815 // file chooser
1816 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1817 mUploadHandler = new UploadHandler(this);
1818 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1819 }
1820
1821 // thumbnails
1822
1823 /**
1824 * Return the desired width for thumbnail screenshots, which are stored in
1825 * the database, and used on the bookmarks screen.
1826 * @param context Context for finding out the density of the screen.
1827 * @return desired width for thumbnail screenshot.
1828 */
1829 static int getDesiredThumbnailWidth(Context context) {
1830 return context.getResources().getDimensionPixelOffset(
1831 R.dimen.bookmarkThumbnailWidth);
1832 }
1833
1834 /**
1835 * Return the desired height for thumbnail screenshots, which are stored in
1836 * the database, and used on the bookmarks screen.
1837 * @param context Context for finding out the density of the screen.
1838 * @return desired height for thumbnail screenshot.
1839 */
1840 static int getDesiredThumbnailHeight(Context context) {
1841 return context.getResources().getDimensionPixelOffset(
1842 R.dimen.bookmarkThumbnailHeight);
1843 }
1844
1845 private static Bitmap createScreenshot(WebView view, int width, int height) {
1846 Picture thumbnail = view.capturePicture();
1847 if (thumbnail == null) {
1848 return null;
1849 }
1850 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1851 Canvas canvas = new Canvas(bm);
1852 // May need to tweak these values to determine what is the
1853 // best scale factor
1854 int thumbnailWidth = thumbnail.getWidth();
1855 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001856 float scaleFactor = 1.0f;
Michael Kolb8233fac2010-10-26 16:08:53 -07001857 if (thumbnailWidth > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001858 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001859 } else {
1860 return null;
1861 }
John Reckfe49ab42010-11-16 17:09:37 -08001862
Michael Kolb8233fac2010-10-26 16:08:53 -07001863 if (view.getWidth() > view.getHeight() &&
1864 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
1865 // If the device is in landscape and the page is shorter
John Reckfe49ab42010-11-16 17:09:37 -08001866 // than the height of the view, center the thumnail and crop the sides
1867 scaleFactor = (float) height / (float)thumbnailHeight;
1868 float wx = (thumbnailWidth * scaleFactor) - width;
1869 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001870 }
1871
John Reckfe49ab42010-11-16 17:09:37 -08001872 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001873
1874 thumbnail.draw(canvas);
1875 return bm;
1876 }
1877
1878 private void updateScreenshot(WebView view) {
1879 // If this is a bookmarked site, add a screenshot to the database.
1880 // FIXME: When should we update? Every time?
1881 // FIXME: Would like to make sure there is actually something to
1882 // draw, but the API for that (WebViewCore.pictureReady()) is not
1883 // currently accessible here.
1884
1885 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1886 getDesiredThumbnailHeight(mActivity));
1887 if (bm == null) {
1888 return;
1889 }
1890
1891 final ContentResolver cr = mActivity.getContentResolver();
1892 final String url = view.getUrl();
1893 final String originalUrl = view.getOriginalUrl();
1894
1895 new AsyncTask<Void, Void, Void>() {
1896 @Override
1897 protected Void doInBackground(Void... unused) {
1898 Cursor cursor = null;
1899 try {
1900 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
1901 if (cursor != null && cursor.moveToFirst()) {
1902 final ByteArrayOutputStream os =
1903 new ByteArrayOutputStream();
1904 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
1905
1906 ContentValues values = new ContentValues();
1907 values.put(Images.THUMBNAIL, os.toByteArray());
1908 values.put(Images.URL, cursor.getString(0));
1909
1910 do {
1911 cr.update(Images.CONTENT_URI, values, null, null);
1912 } while (cursor.moveToNext());
1913 }
1914 } catch (IllegalStateException e) {
1915 // Ignore
1916 } finally {
1917 if (cursor != null) cursor.close();
1918 }
1919 return null;
1920 }
1921 }.execute();
1922 }
1923
1924 private class Copy implements OnMenuItemClickListener {
1925 private CharSequence mText;
1926
1927 public boolean onMenuItemClick(MenuItem item) {
1928 copy(mText);
1929 return true;
1930 }
1931
1932 public Copy(CharSequence toCopy) {
1933 mText = toCopy;
1934 }
1935 }
1936
Leon Scroggins63c02662010-11-18 15:16:27 -05001937 private static class Download implements OnMenuItemClickListener {
1938 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001939 private String mText;
1940
1941 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05001942 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
1943 null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001944 return true;
1945 }
1946
Leon Scroggins63c02662010-11-18 15:16:27 -05001947 public Download(Activity activity, String toDownload) {
1948 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001949 mText = toDownload;
1950 }
1951 }
1952
Cary Clark8974d282010-11-22 10:46:05 -05001953 private static class SelectText implements OnMenuItemClickListener {
1954 private WebView mWebView;
1955
1956 public boolean onMenuItemClick(MenuItem item) {
1957 if (mWebView != null) {
1958 return mWebView.selectText();
1959 }
1960 return false;
1961 }
1962
1963 public SelectText(WebView webView) {
1964 mWebView = webView;
1965 }
1966
1967 }
1968
Michael Kolb8233fac2010-10-26 16:08:53 -07001969 /********************** TODO: UI stuff *****************************/
1970
1971 // these methods have been copied, they still need to be cleaned up
1972
1973 /****************** tabs ***************************************************/
1974
1975 // basic tab interactions:
1976
1977 // it is assumed that tabcontrol already knows about the tab
1978 protected void addTab(Tab tab) {
1979 mUi.addTab(tab);
1980 }
1981
1982 protected void removeTab(Tab tab) {
1983 mUi.removeTab(tab);
1984 mTabControl.removeTab(tab);
1985 }
1986
1987 protected void setActiveTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001988 mTabControl.setCurrentTab(tab);
Michael Kolb77df4562010-11-19 14:49:34 -08001989 // the tab is guaranteed to have a webview after setCurrentTab
1990 mUi.setActiveTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001991 }
1992
1993 protected void closeEmptyChildTab() {
1994 Tab current = mTabControl.getCurrentTab();
1995 if (current != null
1996 && current.getWebView().copyBackForwardList().getSize() == 0) {
1997 Tab parent = current.getParentTab();
1998 if (parent != null) {
1999 switchToTab(mTabControl.getTabIndex(parent));
2000 closeTab(current);
2001 }
2002 }
2003 }
2004
2005 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
2006 Log.i(LOGTAG, "Reusing tab for " + appId);
2007 // Dismiss the subwindow if applicable.
2008 dismissSubWindow(appTab);
2009 // Since we might kill the WebView, remove it from the
2010 // content view first.
2011 mUi.detachTab(appTab);
2012 // Recreate the main WebView after destroying the old one.
2013 // If the WebView has the same original url and is on that
2014 // page, it can be reused.
2015 boolean needsLoad =
2016 mTabControl.recreateWebView(appTab, urlData);
2017 // TODO: analyze why the remove and add are necessary
2018 mUi.attachTab(appTab);
2019 if (mTabControl.getCurrentTab() != appTab) {
2020 switchToTab(mTabControl.getTabIndex(appTab));
2021 if (needsLoad) {
2022 loadUrlDataIn(appTab, urlData);
2023 }
2024 } else {
2025 // If the tab was the current tab, we have to attach
2026 // it to the view system again.
2027 setActiveTab(appTab);
2028 if (needsLoad) {
2029 loadUrlDataIn(appTab, urlData);
2030 }
2031 }
2032 }
2033
2034 // Remove the sub window if it exists. Also called by TabControl when the
2035 // user clicks the 'X' to dismiss a sub window.
2036 public void dismissSubWindow(Tab tab) {
2037 removeSubWindow(tab);
2038 // dismiss the subwindow. This will destroy the WebView.
2039 tab.dismissSubWindow();
2040 getCurrentTopWebView().requestFocus();
2041 }
2042
2043 @Override
2044 public void removeSubWindow(Tab t) {
2045 if (t.getSubWebView() != null) {
2046 mUi.removeSubWindow(t.getSubViewContainer());
2047 }
2048 }
2049
2050 @Override
2051 public void attachSubWindow(Tab tab) {
2052 if (tab.getSubWebView() != null) {
2053 mUi.attachSubWindow(tab.getSubViewContainer());
2054 getCurrentTopWebView().requestFocus();
2055 }
2056 }
2057
Michael Kolb843510f2010-12-09 10:51:49 -08002058 @Override
2059 public Tab openTabToHomePage() {
2060 // check for max tabs
2061 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002062 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2063 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002064 } else {
2065 mUi.showMaxTabsWarning();
2066 return null;
2067 }
2068 }
2069
Michael Kolb18eb3772010-12-10 14:29:51 -08002070 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2071 if (mSettings.openInBackground() && !forceForeground) {
2072 Tab tab = mTabControl.createNewTab(false, null, null,
2073 (parent != null) && parent.isPrivateBrowsingEnabled());
2074 if (tab != null) {
2075 addTab(tab);
2076 WebView view = tab.getWebView();
2077 loadUrl(view, url);
2078 }
2079 return tab;
2080 } else {
2081 return openTabAndShow(parent, new UrlData(url), false, null);
2082 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002083 }
2084
Michael Kolb18eb3772010-12-10 14:29:51 -08002085
Michael Kolb8233fac2010-10-26 16:08:53 -07002086 // This method does a ton of stuff. It will attempt to create a new tab
2087 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2088 // url isn't null, it will load the given url.
Michael Kolb18eb3772010-12-10 14:29:51 -08002089 public Tab openTabAndShow(Tab parent, UrlData urlData, boolean closeOnExit,
Michael Kolb8233fac2010-10-26 16:08:53 -07002090 String appId) {
2091 final Tab currentTab = mTabControl.getCurrentTab();
2092 if (mTabControl.canCreateNewTab()) {
2093 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Michael Kolb18eb3772010-12-10 14:29:51 -08002094 urlData.mUrl,
2095 (parent != null) && parent.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -07002096 WebView webview = tab.getWebView();
2097 // We must set the new tab as the current tab to reflect the old
2098 // animation behavior.
2099 addTab(tab);
2100 setActiveTab(tab);
2101 if (!urlData.isEmpty()) {
2102 loadUrlDataIn(tab, urlData);
2103 }
2104 return tab;
2105 } else {
2106 // Get rid of the subwindow if it exists
2107 dismissSubWindow(currentTab);
2108 if (!urlData.isEmpty()) {
2109 // Load the given url.
2110 loadUrlDataIn(currentTab, urlData);
2111 }
2112 return currentTab;
2113 }
2114 }
2115
Michael Kolb8233fac2010-10-26 16:08:53 -07002116 @Override
2117 public Tab openIncognitoTab() {
2118 if (mTabControl.canCreateNewTab()) {
2119 Tab currentTab = mTabControl.getCurrentTab();
2120 Tab tab = mTabControl.createNewTab(false, null, null, true);
2121 addTab(tab);
2122 setActiveTab(tab);
2123 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002124 } else {
2125 mUi.showMaxTabsWarning();
2126 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002127 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002128 }
2129
2130 /**
2131 * @param index Index of the tab to change to, as defined by
2132 * mTabControl.getTabIndex(Tab t).
2133 * @return boolean True if we successfully switched to a different tab. If
2134 * the indexth tab is null, or if that tab is the same as
2135 * the current one, return false.
2136 */
2137 @Override
2138 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002139 // hide combo view if open
2140 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002141 Tab tab = mTabControl.getTab(index);
2142 Tab currentTab = mTabControl.getCurrentTab();
2143 if (tab == null || tab == currentTab) {
2144 return false;
2145 }
2146 setActiveTab(tab);
2147 return true;
2148 }
2149
2150 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002151 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002152 // hide combo view if open
2153 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002154 final Tab current = mTabControl.getCurrentTab();
2155 if (mTabControl.getTabCount() == 1) {
2156 // This is the last tab. Open a new one, with the home
2157 // page and close the current one.
2158 openTabToHomePage();
2159 closeTab(current);
2160 return;
2161 }
2162 final Tab parent = current.getParentTab();
2163 int indexToShow = -1;
2164 if (parent != null) {
2165 indexToShow = mTabControl.getTabIndex(parent);
2166 } else {
2167 final int currentIndex = mTabControl.getCurrentIndex();
2168 // Try to move to the tab to the right
2169 indexToShow = currentIndex + 1;
2170 if (indexToShow > mTabControl.getTabCount() - 1) {
2171 // Try to move to the tab to the left
2172 indexToShow = currentIndex - 1;
2173 }
2174 }
2175 if (switchToTab(indexToShow)) {
2176 // Close window
2177 closeTab(current);
2178 }
2179 }
2180
2181 /**
2182 * Close the tab, remove its associated title bar, and adjust mTabControl's
2183 * current tab to a valid value.
2184 */
2185 @Override
2186 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002187 // hide combo view if open
2188 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002189 int currentIndex = mTabControl.getCurrentIndex();
2190 int removeIndex = mTabControl.getTabIndex(tab);
2191 removeTab(tab);
2192 if (currentIndex >= removeIndex && currentIndex != 0) {
2193 currentIndex--;
2194 }
2195 Tab newtab = mTabControl.getTab(currentIndex);
2196 setActiveTab(newtab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002197 }
2198
2199 /**************** TODO: Url loading clean up *******************************/
2200
2201 // Called when loading from context menu or LOAD_URL message
2202 protected void loadUrlFromContext(WebView view, String url) {
2203 // In case the user enters nothing.
2204 if (url != null && url.length() != 0 && view != null) {
2205 url = UrlUtils.smartUrlFilter(url);
2206 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2207 loadUrl(view, url);
2208 }
2209 }
2210 }
2211
2212 /**
2213 * Load the URL into the given WebView and update the title bar
2214 * to reflect the new load. Call this instead of WebView.loadUrl
2215 * directly.
2216 * @param view The WebView used to load url.
2217 * @param url The URL to load.
2218 */
2219 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002220 view.loadUrl(url);
2221 }
2222
2223 /**
2224 * Load UrlData into a Tab and update the title bar to reflect the new
2225 * load. Call this instead of UrlData.loadIn directly.
2226 * @param t The Tab used to load.
2227 * @param data The UrlData being loaded.
2228 */
2229 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002230 data.loadIn(t);
2231 }
2232
2233 /**
2234 * Resets the browser title-view to whatever it must be
2235 * (for example, if we had a loading error)
2236 * When we have a new page, we call resetTitle, when we
2237 * have to reset the titlebar to whatever it used to be
2238 * (for example, if the user chose to stop loading), we
2239 * call resetTitleAndRevertLockIcon.
2240 */
2241 public void resetTitleAndRevertLockIcon(Tab tab) {
2242 mUi.resetTitleAndRevertLockIcon(tab);
2243 }
2244
2245 void resetTitleAndIcon(Tab tab) {
2246 mUi.resetTitleAndIcon(tab);
2247 }
2248
2249 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002250 * Sets a title composed of the URL and the title string.
2251 * @param url The URL of the site being loaded.
2252 * @param title The title of the site being loaded.
2253 */
2254 void setUrlTitle(Tab tab, String url, String title) {
2255 tab.setCurrentUrl(url);
2256 tab.setCurrentTitle(title);
2257 // If we are in voice search mode, the title has already been set.
2258 if (tab.isInVoiceSearchMode()) return;
2259 mUi.setUrlTitle(tab, url, title);
2260 }
2261
2262 void goBackOnePageOrQuit() {
2263 Tab current = mTabControl.getCurrentTab();
2264 if (current == null) {
2265 /*
2266 * Instead of finishing the activity, simply push this to the back
2267 * of the stack and let ActivityManager to choose the foreground
2268 * activity. As BrowserActivity is singleTask, it will be always the
2269 * root of the task. So we can use either true or false for
2270 * moveTaskToBack().
2271 */
2272 mActivity.moveTaskToBack(true);
2273 return;
2274 }
2275 WebView w = current.getWebView();
2276 if (w.canGoBack()) {
2277 w.goBack();
2278 } else {
2279 // Check to see if we are closing a window that was created by
2280 // another window. If so, we switch back to that window.
2281 Tab parent = current.getParentTab();
2282 if (parent != null) {
2283 switchToTab(mTabControl.getTabIndex(parent));
2284 // Now we close the other tab
2285 closeTab(current);
2286 } else {
2287 if (current.closeOnExit()) {
2288 // force the tab's inLoad() to be false as we are going to
2289 // either finish the activity or remove the tab. This will
2290 // ensure pauseWebViewTimers() taking action.
Michael Kolb70976932010-11-30 11:34:01 -08002291 current.clearInPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07002292 if (mTabControl.getTabCount() == 1) {
2293 mActivity.finish();
2294 return;
2295 }
2296 if (mActivityPaused) {
2297 Log.e(LOGTAG, "BrowserActivity is already paused "
2298 + "while handing goBackOnePageOrQuit.");
2299 }
Michael Kolb70976932010-11-30 11:34:01 -08002300 pauseWebViewTimers(current);
Michael Kolb8233fac2010-10-26 16:08:53 -07002301 removeTab(current);
2302 }
2303 /*
2304 * Instead of finishing the activity, simply push this to the back
2305 * of the stack and let ActivityManager to choose the foreground
2306 * activity. As BrowserActivity is singleTask, it will be always the
2307 * root of the task. So we can use either true or false for
2308 * moveTaskToBack().
2309 */
2310 mActivity.moveTaskToBack(true);
2311 }
2312 }
2313 }
2314
2315 /**
2316 * Feed the previously stored results strings to the BrowserProvider so that
2317 * the SearchDialog will show them instead of the standard searches.
2318 * @param result String to show on the editable line of the SearchDialog.
2319 */
2320 @Override
2321 public void showVoiceSearchResults(String result) {
2322 ContentProviderClient client = mActivity.getContentResolver()
2323 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2324 ContentProvider prov = client.getLocalContentProvider();
2325 BrowserProvider bp = (BrowserProvider) prov;
2326 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2327 client.release();
2328
2329 Bundle bundle = createGoogleSearchSourceBundle(
2330 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2331 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2332 startSearch(result, false, bundle, false);
2333 }
2334
2335 private void startSearch(String initialQuery, boolean selectInitialQuery,
2336 Bundle appSearchData, boolean globalSearch) {
2337 if (appSearchData == null) {
2338 appSearchData = createGoogleSearchSourceBundle(
2339 GOOGLE_SEARCH_SOURCE_TYPE);
2340 }
2341
2342 SearchEngine searchEngine = mSettings.getSearchEngine();
2343 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2344 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2345 }
2346 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2347 globalSearch);
2348 }
2349
2350 private Bundle createGoogleSearchSourceBundle(String source) {
2351 Bundle bundle = new Bundle();
2352 bundle.putString(Search.SOURCE, source);
2353 return bundle;
2354 }
2355
2356 /**
2357 * handle key events in browser
2358 *
2359 * @param keyCode
2360 * @param event
2361 * @return true if handled, false to pass to super
2362 */
2363 boolean onKeyDown(int keyCode, KeyEvent event) {
2364 // Even if MENU is already held down, we need to call to super to open
2365 // the IME on long press.
2366 if (KeyEvent.KEYCODE_MENU == keyCode) {
2367 mMenuIsDown = true;
2368 return false;
2369 }
2370 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2371 // still down, we don't want to trigger the search. Pretend to consume
2372 // the key and do nothing.
2373 if (mMenuIsDown) return true;
2374
2375 switch(keyCode) {
2376 case KeyEvent.KEYCODE_SPACE:
2377 // WebView/WebTextView handle the keys in the KeyDown. As
2378 // the Activity's shortcut keys are only handled when WebView
2379 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2380 if (event.isShiftPressed()) {
2381 pageUp();
2382 } else {
2383 pageDown();
2384 }
2385 return true;
2386 case KeyEvent.KEYCODE_BACK:
2387 if (event.getRepeatCount() == 0) {
2388 event.startTracking();
2389 return true;
2390 } else if (mUi.showsWeb()
2391 && event.isLongPress()) {
2392 bookmarksOrHistoryPicker(true);
2393 return true;
2394 }
2395 break;
2396 }
2397 return false;
2398 }
2399
2400 boolean onKeyUp(int keyCode, KeyEvent event) {
2401 switch(keyCode) {
2402 case KeyEvent.KEYCODE_MENU:
2403 mMenuIsDown = false;
2404 break;
2405 case KeyEvent.KEYCODE_BACK:
2406 if (event.isTracking() && !event.isCanceled()) {
2407 onBackKey();
2408 return true;
2409 }
2410 break;
2411 }
2412 return false;
2413 }
2414
2415 public boolean isMenuDown() {
2416 return mMenuIsDown;
2417 }
2418
Ben Murdoch8029a772010-11-16 11:58:21 +00002419 public void setupAutoFill(Message message) {
2420 // Open the settings activity at the AutoFill profile fragment so that
2421 // the user can create a new profile. When they return, we will dispatch
2422 // the message so that we can autofill the form using their new profile.
2423 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2424 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2425 AutoFillSettingsFragment.class.getName());
2426 mAutoFillSetupMessage = message;
2427 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2428 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002429}