blob: e7e999d64af66d5a75a3f4f354fdf5344b4dca91 [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;
Narayan Kamath5119edd2011-02-23 15:49:17 +000020import com.android.browser.UI.DropdownChangeListener;
Michael Kolb8233fac2010-10-26 16:08:53 -070021import com.android.browser.search.SearchEngine;
22import com.android.common.Search;
23
24import android.app.Activity;
25import android.app.DownloadManager;
26import android.app.SearchManager;
27import android.content.ClipboardManager;
28import android.content.ContentProvider;
29import android.content.ContentProviderClient;
30import android.content.ContentResolver;
31import android.content.ContentValues;
32import android.content.Context;
33import android.content.Intent;
34import android.content.pm.PackageManager;
35import android.content.pm.ResolveInfo;
36import android.content.res.Configuration;
Leon Scroggins1961ed22010-12-07 15:22:21 -050037import android.database.ContentObserver;
Michael Kolb8233fac2010-10-26 16:08:53 -070038import android.database.Cursor;
39import android.database.sqlite.SQLiteDatabase;
Michael Kolb8233fac2010-10-26 16:08:53 -070040import android.graphics.Bitmap;
41import android.graphics.Canvas;
42import android.graphics.Picture;
43import android.net.Uri;
44import android.net.http.SslError;
45import android.os.AsyncTask;
46import android.os.Bundle;
Leon Scrogginsac993842011-02-02 12:54:07 -050047import android.os.Environment;
Michael Kolb8233fac2010-10-26 16:08:53 -070048import android.os.Handler;
49import android.os.Message;
50import android.os.PowerManager;
51import android.os.PowerManager.WakeLock;
Ben Murdoch8029a772010-11-16 11:58:21 +000052import android.preference.PreferenceActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -070053import android.provider.Browser;
54import android.provider.BrowserContract;
Michael Kolb8233fac2010-10-26 16:08:53 -070055import android.provider.BrowserContract.Images;
56import android.provider.ContactsContract;
57import android.provider.ContactsContract.Intents.Insert;
Michael Kolbcfa3af52010-12-14 10:36:11 -080058import android.speech.RecognizerIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070059import android.speech.RecognizerResultsIntent;
60import android.text.TextUtils;
61import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080062import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070063import android.view.ActionMode;
64import android.view.ContextMenu;
65import android.view.ContextMenu.ContextMenuInfo;
66import android.view.Gravity;
67import android.view.KeyEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070068import android.view.Menu;
69import android.view.MenuInflater;
70import android.view.MenuItem;
71import android.view.MenuItem.OnMenuItemClickListener;
72import android.view.View;
73import android.webkit.CookieManager;
74import android.webkit.CookieSyncManager;
75import android.webkit.HttpAuthHandler;
76import android.webkit.SslErrorHandler;
77import android.webkit.ValueCallback;
78import android.webkit.WebChromeClient;
79import android.webkit.WebIconDatabase;
80import android.webkit.WebSettings;
81import android.webkit.WebView;
Leon Scrogginsac993842011-02-02 12:54:07 -050082import android.widget.Toast;
Michael Kolb8233fac2010-10-26 16:08:53 -070083
84import java.io.ByteArrayOutputStream;
85import java.io.File;
86import java.net.URLEncoder;
87import java.util.Calendar;
88import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -080089import java.util.List;
Michael Kolb8233fac2010-10-26 16:08:53 -070090
91/**
92 * Controller for browser
93 */
94public class Controller
95 implements WebViewController, UiController {
96
97 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -080098 private static final String SEND_APP_ID_EXTRA =
99 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
100
Michael Kolb8233fac2010-10-26 16:08:53 -0700101
102 // public message ids
103 public final static int LOAD_URL = 1001;
104 public final static int STOP_LOAD = 1002;
105
106 // Message Ids
107 private static final int FOCUS_NODE_HREF = 102;
108 private static final int RELEASE_WAKELOCK = 107;
109
110 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
111
112 private static final int OPEN_BOOKMARKS = 201;
113
114 private static final int EMPTY_MENU = -1;
115
Michael Kolb8233fac2010-10-26 16:08:53 -0700116 // activity requestCode
117 final static int PREFERENCES_PAGE = 3;
118 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000119 final static int AUTOFILL_SETUP = 5;
120
Michael Kolb8233fac2010-10-26 16:08:53 -0700121 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
122
123 // As the ids are dynamically created, we can't guarantee that they will
124 // be in sequence, so this static array maps ids to a window number.
125 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
126 { R.id.window_one_menu_id, R.id.window_two_menu_id,
127 R.id.window_three_menu_id, R.id.window_four_menu_id,
128 R.id.window_five_menu_id, R.id.window_six_menu_id,
129 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
130
131 // "source" parameter for Google search through search key
132 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
133 // "source" parameter for Google search through simplily type
134 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
135
136 private Activity mActivity;
137 private UI mUi;
138 private TabControl mTabControl;
139 private BrowserSettings mSettings;
140 private WebViewFactory mFactory;
John Reckb3417f02011-01-14 11:01:05 -0800141 private OptionsMenuHandler mOptionsMenuHandler = null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700142
143 private WakeLock mWakeLock;
144
145 private UrlHandler mUrlHandler;
146 private UploadHandler mUploadHandler;
147 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700148 private PageDialogsHandler mPageDialogsHandler;
149 private NetworkStateHandler mNetworkHandler;
150
Ben Murdoch8029a772010-11-16 11:58:21 +0000151 private Message mAutoFillSetupMessage;
152
Michael Kolb8233fac2010-10-26 16:08:53 -0700153 private boolean mShouldShowErrorConsole;
154
155 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
156
157 // FIXME, temp address onPrepareMenu performance problem.
158 // When we move everything out of view, we should rewrite this.
159 private int mCurrentMenuState = 0;
160 private int mMenuState = R.id.MAIN_MENU;
161 private int mOldMenuState = EMPTY_MENU;
162 private Menu mCachedMenu;
163
164 // Used to prevent chording to result in firing two shortcuts immediately
165 // one after another. Fixes bug 1211714.
166 boolean mCanChord;
167 private boolean mMenuIsDown;
168
169 // For select and find, we keep track of the ActionMode so that
170 // finish() can be called as desired.
171 private ActionMode mActionMode;
172
173 /**
174 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
175 * of whether the configuration has changed. The first onMenuOpened call
176 * after a configuration change is simply a reopening of the same menu
177 * (i.e. mIconView did not change).
178 */
179 private boolean mConfigChanged;
180
181 /**
182 * Keeps track of whether the options menu is open. This is important in
183 * determining whether to show or hide the title bar overlay
184 */
185 private boolean mOptionsMenuOpen;
186
187 /**
188 * Whether or not the options menu is in its bigger, popup menu form. When
189 * true, we want the title bar overlay to be gone. When false, we do not.
190 * Only meaningful if mOptionsMenuOpen is true.
191 */
192 private boolean mExtendedMenuOpen;
193
194 private boolean mInLoad;
195
196 private boolean mActivityPaused = true;
197 private boolean mLoadStopped;
198
199 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500200 // Checks to see when the bookmarks database has changed, and updates the
201 // Tabs' notion of whether they represent bookmarked sites.
202 private ContentObserver mBookmarksObserver;
John Reck0ebd3ac2010-12-09 11:14:04 -0800203 private DataController mDataController;
Michael Kolb8233fac2010-10-26 16:08:53 -0700204
205 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
206 @Override
207 public Void doInBackground(File... files) {
208 if (files != null) {
209 for (File f : files) {
210 if (!f.delete()) {
211 Log.e(LOGTAG, f.getPath() + " was not deleted");
212 }
213 }
214 }
215 return null;
216 }
217 }
218
219 public Controller(Activity browser) {
220 mActivity = browser;
221 mSettings = BrowserSettings.getInstance();
John Reck0ebd3ac2010-12-09 11:14:04 -0800222 mDataController = DataController.getInstance(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700223 mTabControl = new TabControl(this);
224 mSettings.setController(this);
225
226 mUrlHandler = new UrlHandler(this);
227 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700228 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
229
230 PowerManager pm = (PowerManager) mActivity
231 .getSystemService(Context.POWER_SERVICE);
232 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
233
234 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500235 mBookmarksObserver = new ContentObserver(mHandler) {
236 @Override
237 public void onChange(boolean selfChange) {
238 int size = mTabControl.getTabCount();
239 for (int i = 0; i < size; i++) {
240 mTabControl.getTab(i).updateBookmarkedStatus();
241 }
242 }
243
244 };
245 browser.getContentResolver().registerContentObserver(
246 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700247
248 mNetworkHandler = new NetworkStateHandler(mActivity, this);
249 // Start watching the default geolocation permissions
250 mSystemAllowGeolocationOrigins =
251 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
252 mSystemAllowGeolocationOrigins.start();
253
254 retainIconsOnStartup();
255 }
256
Patrick Scott7d50a932011-02-04 09:27:26 -0500257 void start(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700258 // Unless the last browser usage was within 24 hours, destroy any
259 // remaining incognito tabs.
260
261 Calendar lastActiveDate = icicle != null ?
262 (Calendar) icicle.getSerializable("lastActiveDate") : null;
263 Calendar today = Calendar.getInstance();
264 Calendar yesterday = Calendar.getInstance();
265 yesterday.add(Calendar.DATE, -1);
266
Patrick Scott7d50a932011-02-04 09:27:26 -0500267 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700268 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800269 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700270
Patrick Scott7d50a932011-02-04 09:27:26 -0500271 // Find out if we will restore any state and remember the tab.
272 final int currentTab =
273 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000274
Patrick Scott7d50a932011-02-04 09:27:26 -0500275 if (currentTab == -1) {
276 // Not able to restore so we go ahead and clear session cookies. We
277 // must do this before trying to login the user as we don't want to
278 // clear any session cookies set during login.
279 CookieManager.getInstance().removeSessionCookie();
280 }
281
Patrick Scottd43e75a2011-03-14 14:47:23 -0400282 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500283 new Runnable() {
284 @Override public void run() {
285 start(icicle, intent, currentTab, restoreIncognitoTabs);
286 }
287 });
288 }
289
290 private void start(Bundle icicle, Intent intent, int currentTab,
291 boolean restoreIncognitoTabs) {
292 if (currentTab == -1) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700293 final Bundle extra = intent.getExtras();
294 // Create an initial tab.
295 // If the intent is ACTION_VIEW and data is not null, the Browser is
296 // invoked to view the content by another application. In this case,
297 // the tab will be close when exit.
298 UrlData urlData = mIntentHandler.getUrlDataFromIntent(intent);
299
300 String action = intent.getAction();
301 final Tab t = mTabControl.createNewTab(
302 (Intent.ACTION_VIEW.equals(action) &&
303 intent.getData() != null)
304 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
305 .equals(action),
306 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
307 urlData.mUrl, false);
308 addTab(t);
309 setActiveTab(t);
310 WebView webView = t.getWebView();
311 if (extra != null) {
312 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
313 if (scale > 0 && scale <= 1000) {
314 webView.setInitialScale(scale);
315 }
316 }
317
318 if (urlData.isEmpty()) {
319 loadUrl(webView, mSettings.getHomePage());
320 } else {
Michael Kolbcd424e92011-02-24 10:26:26 -0800321 // monkey protection against delayed start
322 if (t != null) {
323 loadUrlDataIn(t, urlData);
324 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700325 }
326 } else {
Patrick Scott7d50a932011-02-04 09:27:26 -0500327 mTabControl.restoreState(icicle, currentTab, restoreIncognitoTabs,
328 mUi.needsRestoreAllTabs());
Michael Kolb1bf23132010-11-19 12:55:12 -0800329 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700330 // TabControl.restoreState() will create a new tab even if
331 // restoring the state fails.
332 setActiveTab(mTabControl.getCurrentTab());
333 }
334 // clear up the thumbnail directory, which is no longer used;
335 // ideally this should only be run once after an upgrade from
336 // a previous version of the browser
337 new ClearThumbnails().execute(mTabControl.getThumbnailDir()
338 .listFiles());
339 // Read JavaScript flags if it exists.
340 String jsFlags = getSettings().getJsFlags();
341 if (jsFlags.trim().length() != 0) {
342 getCurrentWebView().setJsFlags(jsFlags);
343 }
John Reck439c9a52010-12-14 10:04:39 -0800344 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
345 bookmarksOrHistoryPicker(false);
346 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700347 }
348
349 void setWebViewFactory(WebViewFactory factory) {
350 mFactory = factory;
351 }
352
Michael Kolb1514bb72010-11-22 09:11:48 -0800353 @Override
354 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700355 return mFactory;
356 }
357
358 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800359 public void onSetWebView(Tab tab, WebView view) {
360 mUi.onSetWebView(tab, view);
361 }
362
363 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800364 public void createSubWindow(Tab tab) {
365 endActionMode();
366 WebView mainView = tab.getWebView();
367 WebView subView = mFactory.createWebView((mainView == null)
368 ? false
369 : mainView.isPrivateBrowsingEnabled());
370 mUi.createSubWindow(tab, subView);
371 }
372
373 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700374 public Activity getActivity() {
375 return mActivity;
376 }
377
378 void setUi(UI ui) {
379 mUi = ui;
380 }
381
382 BrowserSettings getSettings() {
383 return mSettings;
384 }
385
386 IntentHandler getIntentHandler() {
387 return mIntentHandler;
388 }
389
390 @Override
391 public UI getUi() {
392 return mUi;
393 }
394
395 int getMaxTabs() {
396 return mActivity.getResources().getInteger(R.integer.max_tabs);
397 }
398
399 @Override
400 public TabControl getTabControl() {
401 return mTabControl;
402 }
403
Michael Kolb1bf23132010-11-19 12:55:12 -0800404 @Override
405 public List<Tab> getTabs() {
406 return mTabControl.getTabs();
407 }
408
Michael Kolb8233fac2010-10-26 16:08:53 -0700409 // Open the icon database and retain all the icons for visited sites.
Ben Murdoch9446b932010-11-25 16:20:14 +0000410 // This is done on a background thread so as not to stall startup.
Michael Kolb8233fac2010-10-26 16:08:53 -0700411 private void retainIconsOnStartup() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000412 // WebIconDatabase needs to be retrieved on the UI thread so that if
413 // it has not been created successfully yet the Handler is started on the
414 // UI thread.
415 new RetainIconsOnStartupTask(WebIconDatabase.getInstance()).execute();
416 }
417
418 private class RetainIconsOnStartupTask extends AsyncTask<Void, Void, Void> {
419 private WebIconDatabase mDb;
420
421 public RetainIconsOnStartupTask(WebIconDatabase db) {
422 mDb = db;
423 }
424
John Recka00cbbd2010-12-16 12:38:19 -0800425 @Override
Ben Murdoch9446b932010-11-25 16:20:14 +0000426 protected Void doInBackground(Void... unused) {
427 mDb.open(mActivity.getDir("icons", 0).getPath());
428 Cursor c = null;
429 try {
430 c = Browser.getAllBookmarks(mActivity.getContentResolver());
431 if (c.moveToFirst()) {
432 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
433 do {
434 String url = c.getString(urlIndex);
435 mDb.retainIconForPageUrl(url);
436 } while (c.moveToNext());
437 }
438 } catch (IllegalStateException e) {
439 Log.e(LOGTAG, "retainIconsOnStartup", e);
440 } finally {
441 if (c != null) c.close();
Michael Kolb8233fac2010-10-26 16:08:53 -0700442 }
Ben Murdoch9446b932010-11-25 16:20:14 +0000443
444 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700445 }
446 }
447
448 private void startHandler() {
449 mHandler = new Handler() {
450
451 @Override
452 public void handleMessage(Message msg) {
453 switch (msg.what) {
454 case OPEN_BOOKMARKS:
455 bookmarksOrHistoryPicker(false);
456 break;
457 case FOCUS_NODE_HREF:
458 {
459 String url = (String) msg.getData().get("url");
460 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500461 String src = (String) msg.getData().get("src");
462 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700463 if (TextUtils.isEmpty(url)) {
464 break;
465 }
466 HashMap focusNodeMap = (HashMap) msg.obj;
467 WebView view = (WebView) focusNodeMap.get("webview");
468 // Only apply the action if the top window did not change.
469 if (getCurrentTopWebView() != view) {
470 break;
471 }
472 switch (msg.arg1) {
473 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -0700474 loadUrlFromContext(getCurrentTopWebView(), url);
475 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500476 case R.id.view_image_context_menu_id:
477 loadUrlFromContext(getCurrentTopWebView(), src);
478 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500479 case R.id.open_newtab_context_menu_id:
480 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -0800481 final Tab newTab = openTab(parent, url, false);
Leon Scroggins026f2542010-11-22 13:26:12 -0500482 if (newTab != null && newTab != parent) {
483 parent.addChildTab(newTab);
484 }
485 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700486 case R.id.copy_link_context_menu_id:
487 copy(url);
488 break;
489 case R.id.save_link_context_menu_id:
490 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500491 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000492 mActivity, url, null, null, null,
493 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700494 break;
495 }
496 break;
497 }
498
499 case LOAD_URL:
500 loadUrlFromContext(getCurrentTopWebView(), (String) msg.obj);
501 break;
502
503 case STOP_LOAD:
504 stopLoading();
505 break;
506
507 case RELEASE_WAKELOCK:
508 if (mWakeLock.isHeld()) {
509 mWakeLock.release();
510 // if we reach here, Browser should be still in the
511 // background loading after WAKELOCK_TIMEOUT (5-min).
512 // To avoid burning the battery, stop loading.
513 mTabControl.stopAllLoading();
514 }
515 break;
516
517 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800518 Tab tab = (Tab) msg.obj;
519 if (tab != null) {
520 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700521 }
522 break;
523 }
524 }
525 };
526
527 }
528
Michael Kolbba99c5d2010-11-29 14:57:41 -0800529 @Override
530 public void shareCurrentPage() {
531 shareCurrentPage(mTabControl.getCurrentTab());
532 }
533
534 private void shareCurrentPage(Tab tab) {
535 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800536 sharePage(mActivity, tab.getTitle(),
537 tab.getUrl(), tab.getFavicon(),
538 createScreenshot(tab.getWebView(),
539 getDesiredThumbnailWidth(mActivity),
540 getDesiredThumbnailHeight(mActivity)));
541 }
542 }
543
Michael Kolb8233fac2010-10-26 16:08:53 -0700544 /**
545 * Share a page, providing the title, url, favicon, and a screenshot. Uses
546 * an {@link Intent} to launch the Activity chooser.
547 * @param c Context used to launch a new Activity.
548 * @param title Title of the page. Stored in the Intent with
549 * {@link Intent#EXTRA_SUBJECT}
550 * @param url URL of the page. Stored in the Intent with
551 * {@link Intent#EXTRA_TEXT}
552 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
553 * with {@link Browser#EXTRA_SHARE_FAVICON}
554 * @param screenshot Bitmap of a screenshot of the page. Stored in the
555 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
556 */
557 static final void sharePage(Context c, String title, String url,
558 Bitmap favicon, Bitmap screenshot) {
559 Intent send = new Intent(Intent.ACTION_SEND);
560 send.setType("text/plain");
561 send.putExtra(Intent.EXTRA_TEXT, url);
562 send.putExtra(Intent.EXTRA_SUBJECT, title);
563 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
564 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
565 try {
566 c.startActivity(Intent.createChooser(send, c.getString(
567 R.string.choosertitle_sharevia)));
568 } catch(android.content.ActivityNotFoundException ex) {
569 // if no app handles it, do nothing
570 }
571 }
572
573 private void copy(CharSequence text) {
574 ClipboardManager cm = (ClipboardManager) mActivity
575 .getSystemService(Context.CLIPBOARD_SERVICE);
576 cm.setText(text);
577 }
578
579 // lifecycle
580
581 protected void onConfgurationChanged(Configuration config) {
582 mConfigChanged = true;
583 if (mPageDialogsHandler != null) {
584 mPageDialogsHandler.onConfigurationChanged(config);
585 }
586 mUi.onConfigurationChanged(config);
587 }
588
589 @Override
590 public void handleNewIntent(Intent intent) {
591 mIntentHandler.onNewIntent(intent);
592 }
593
594 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800595 if (mUi.isCustomViewShowing()) {
596 hideCustomView();
597 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700598 if (mActivityPaused) {
599 Log.e(LOGTAG, "BrowserActivity is already paused.");
600 return;
601 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700602 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800603 Tab tab = mTabControl.getCurrentTab();
604 if (tab != null) {
605 tab.pause();
606 if (!pauseWebViewTimers(tab)) {
607 mWakeLock.acquire();
608 mHandler.sendMessageDelayed(mHandler
609 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
610 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700611 }
612 mUi.onPause();
613 mNetworkHandler.onPause();
614
615 WebView.disablePlatformNotifications();
616 }
617
618 void onSaveInstanceState(Bundle outState) {
619 // the default implementation requires each view to have an id. As the
620 // browser handles the state itself and it doesn't use id for the views,
621 // don't call the default implementation. Otherwise it will trigger the
622 // warning like this, "couldn't save which view has focus because the
623 // focused view XXX has no id".
624
625 // Save all the tabs
626 mTabControl.saveState(outState);
627 // Save time so that we know how old incognito tabs (if any) are.
628 outState.putSerializable("lastActiveDate", Calendar.getInstance());
629 }
630
631 void onResume() {
632 if (!mActivityPaused) {
633 Log.e(LOGTAG, "BrowserActivity is already resumed.");
634 return;
635 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700636 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800637 Tab current = mTabControl.getCurrentTab();
638 if (current != null) {
639 current.resume();
640 resumeWebViewTimers(current);
641 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700642 if (mWakeLock.isHeld()) {
643 mHandler.removeMessages(RELEASE_WAKELOCK);
644 mWakeLock.release();
645 }
646 mUi.onResume();
647 mNetworkHandler.onResume();
648 WebView.enablePlatformNotifications();
649 }
650
Michael Kolb70976932010-11-30 11:34:01 -0800651 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800652 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800653 * @param tab guaranteed non-null
654 */
655 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700656 boolean inLoad = tab.inPageLoad();
657 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
658 CookieSyncManager.getInstance().startSync();
659 WebView w = tab.getWebView();
660 if (w != null) {
661 w.resumeTimers();
662 }
663 }
664 }
665
Michael Kolb70976932010-11-30 11:34:01 -0800666 /**
667 * Pause all WebView timers using the WebView of the given tab
668 * @param tab
669 * @return true if the timers are paused or tab is null
670 */
671 private boolean pauseWebViewTimers(Tab tab) {
672 if (tab == null) {
673 return true;
674 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700675 CookieSyncManager.getInstance().stopSync();
676 WebView w = getCurrentWebView();
677 if (w != null) {
678 w.pauseTimers();
679 }
680 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700681 }
Michael Kolb70976932010-11-30 11:34:01 -0800682 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700683 }
684
685 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800686 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700687 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
688 mUploadHandler = null;
689 }
690 if (mTabControl == null) return;
691 mUi.onDestroy();
692 // Remove the current tab and sub window
693 Tab t = mTabControl.getCurrentTab();
694 if (t != null) {
695 dismissSubWindow(t);
696 removeTab(t);
697 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500698 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700699 // Destroy all the tabs
700 mTabControl.destroy();
701 WebIconDatabase.getInstance().close();
702 // Stop watching the default geolocation permissions
703 mSystemAllowGeolocationOrigins.stop();
704 mSystemAllowGeolocationOrigins = null;
705 }
706
707 protected boolean isActivityPaused() {
708 return mActivityPaused;
709 }
710
711 protected void onLowMemory() {
712 mTabControl.freeMemory();
713 }
714
715 @Override
716 public boolean shouldShowErrorConsole() {
717 return mShouldShowErrorConsole;
718 }
719
720 protected void setShouldShowErrorConsole(boolean show) {
721 if (show == mShouldShowErrorConsole) {
722 // Nothing to do.
723 return;
724 }
725 mShouldShowErrorConsole = show;
726 Tab t = mTabControl.getCurrentTab();
727 if (t == null) {
728 // There is no current tab so we cannot toggle the error console
729 return;
730 }
731 mUi.setShouldShowErrorConsole(t, show);
732 }
733
734 @Override
735 public void stopLoading() {
736 mLoadStopped = true;
737 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700738 WebView w = getCurrentTopWebView();
739 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700740 mUi.onPageStopped(tab);
741 }
742
743 boolean didUserStopLoading() {
744 return mLoadStopped;
745 }
746
747 // WebViewController
748
749 @Override
John Reck324d4402011-01-11 16:56:42 -0800750 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700751
752 // We've started to load a new page. If there was a pending message
753 // to save a screenshot then we will now take the new page and save
754 // an incorrect screenshot. Therefore, remove any pending thumbnail
755 // messages from the queue.
756 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800757 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700758
759 // reset sync timer to avoid sync starts during loading a page
760 CookieSyncManager.getInstance().resetSync();
761
762 if (!mNetworkHandler.isNetworkUp()) {
763 view.setNetworkAvailable(false);
764 }
765
766 // when BrowserActivity just starts, onPageStarted may be called before
767 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
768 // to start the timer. As we won't switch tabs while an activity is in
769 // pause state, we can ensure calling resume and pause in pair.
770 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800771 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700772 }
773 mLoadStopped = false;
774 if (!mNetworkHandler.isNetworkUp()) {
775 mNetworkHandler.createAndShowNetworkDialog();
776 }
777 endActionMode();
778
John Reck30c714c2010-12-16 17:30:34 -0800779 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700780
John Reck324d4402011-01-11 16:56:42 -0800781 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700782 // update the bookmark database for favicon
783 maybeUpdateFavicon(tab, null, url, favicon);
784
785 Performance.tracePageStart(url);
786
787 // Performance probe
788 if (false) {
789 Performance.onPageStarted();
790 }
791
792 }
793
794 @Override
John Reck324d4402011-01-11 16:56:42 -0800795 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800796 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800797 if (!tab.isPrivateBrowsingEnabled()
798 && !TextUtils.isEmpty(tab.getUrl())) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700799 if (tab.inForeground() && !didUserStopLoading()
800 || !tab.inForeground()) {
801 // Only update the bookmark screenshot if the user did not
802 // cancel the load early.
803 mHandler.sendMessageDelayed(mHandler.obtainMessage(
John Reck34ef2672011-02-10 11:30:55 -0800804 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
Michael Kolb8233fac2010-10-26 16:08:53 -0700805 500);
806 }
807 }
808 // pause the WebView timer and release the wake lock if it is finished
809 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800810 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700811 if (mWakeLock.isHeld()) {
812 mHandler.removeMessages(RELEASE_WAKELOCK);
813 mWakeLock.release();
814 }
815 }
816 // Performance probe
817 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800818 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700819 }
820
821 Performance.tracePageFinished();
822 }
823
824 @Override
John Reck30c714c2010-12-16 17:30:34 -0800825 public void onProgressChanged(Tab tab) {
826 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700827
828 if (newProgress == 100) {
829 CookieSyncManager.getInstance().sync();
830 // onProgressChanged() may continue to be called after the main
831 // frame has finished loading, as any remaining sub frames continue
832 // to load. We'll only get called once though with newProgress as
833 // 100 when everything is loaded. (onPageFinished is called once
834 // when the main frame completes loading regardless of the state of
835 // any sub frames so calls to onProgressChanges may continue after
836 // onPageFinished has executed)
837 if (mInLoad) {
838 mInLoad = false;
839 updateInLoadMenuItems(mCachedMenu);
840 }
841 } else {
842 if (!mInLoad) {
843 // onPageFinished may have already been called but a subframe is
844 // still loading and updating the progress. Reset mInLoad and
845 // update the menu items.
846 mInLoad = true;
847 updateInLoadMenuItems(mCachedMenu);
848 }
849 }
John Reck30c714c2010-12-16 17:30:34 -0800850 mUi.onProgressChanged(tab);
851 }
852
853 @Override
854 public void onUpdatedLockIcon(Tab tab) {
855 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700856 }
857
858 @Override
859 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800860 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800861 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800862 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700863 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
864 return;
865 }
866 // Update the title in the history database if not in private browsing mode
867 if (!tab.isPrivateBrowsingEnabled()) {
John Reck0ebd3ac2010-12-09 11:14:04 -0800868 mDataController.updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700869 }
870 }
871
872 @Override
873 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800874 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700875 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
876 }
877
878 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800879 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
880 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700881 }
882
883 @Override
884 public boolean shouldOverrideKeyEvent(KeyEvent event) {
885 if (mMenuIsDown) {
886 // only check shortcut key when MENU is held
887 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
888 event);
889 } else {
890 return false;
891 }
892 }
893
894 @Override
895 public void onUnhandledKeyEvent(KeyEvent event) {
896 if (!isActivityPaused()) {
897 if (event.getAction() == KeyEvent.ACTION_DOWN) {
898 mActivity.onKeyDown(event.getKeyCode(), event);
899 } else {
900 mActivity.onKeyUp(event.getKeyCode(), event);
901 }
902 }
903 }
904
905 @Override
John Reck324d4402011-01-11 16:56:42 -0800906 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700907 // Don't save anything in private browsing mode
908 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800909 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700910
John Reck324d4402011-01-11 16:56:42 -0800911 if (TextUtils.isEmpty(url)
912 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700913 return;
914 }
John Reck0ebd3ac2010-12-09 11:14:04 -0800915 mDataController.updateVisitedHistory(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700916 WebIconDatabase.getInstance().retainIconForPageUrl(url);
917 }
918
919 @Override
920 public void getVisitedHistory(final ValueCallback<String[]> callback) {
921 AsyncTask<Void, Void, String[]> task =
922 new AsyncTask<Void, Void, String[]>() {
923 @Override
924 public String[] doInBackground(Void... unused) {
925 return Browser.getVisitedHistory(mActivity.getContentResolver());
926 }
927 @Override
928 public void onPostExecute(String[] result) {
929 callback.onReceiveValue(result);
930 }
931 };
932 task.execute();
933 }
934
935 @Override
936 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
937 final HttpAuthHandler handler, final String host,
938 final String realm) {
939 String username = null;
940 String password = null;
941
942 boolean reuseHttpAuthUsernamePassword
943 = handler.useHttpAuthUsernamePassword();
944
945 if (reuseHttpAuthUsernamePassword && view != null) {
946 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
947 if (credentials != null && credentials.length == 2) {
948 username = credentials[0];
949 password = credentials[1];
950 }
951 }
952
953 if (username != null && password != null) {
954 handler.proceed(username, password);
955 } else {
956 if (tab.inForeground()) {
957 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
958 } else {
959 handler.cancel();
960 }
961 }
962 }
963
964 @Override
965 public void onDownloadStart(Tab tab, String url, String userAgent,
966 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000967 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -0500968 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000969 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
970 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700971 // This Tab was opened for the sole purpose of downloading a
972 // file. Remove it.
973 if (tab == mTabControl.getCurrentTab()) {
974 // In this case, the Tab is still on top.
975 goBackOnePageOrQuit();
976 } else {
977 // In this case, it is not.
978 closeTab(tab);
979 }
980 }
981 }
982
983 @Override
984 public Bitmap getDefaultVideoPoster() {
985 return mUi.getDefaultVideoPoster();
986 }
987
988 @Override
989 public View getVideoLoadingProgressView() {
990 return mUi.getVideoLoadingProgressView();
991 }
992
993 @Override
994 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
995 SslError error) {
996 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
997 }
998
Patrick Scott92066772011-03-10 08:46:27 -0500999 @Override
1000 public void showAutoLogin(Tab tab) {
1001 assert tab.inForeground();
1002 // Update the title bar to show the auto-login request.
1003 mUi.showAutoLogin(tab);
1004 }
1005
1006 @Override
1007 public void hideAutoLogin(Tab tab) {
1008 assert tab.inForeground();
1009 mUi.hideAutoLogin(tab);
1010 }
1011
Michael Kolb8233fac2010-10-26 16:08:53 -07001012 // helper method
1013
1014 /*
1015 * Update the favorites icon if the private browsing isn't enabled and the
1016 * icon is valid.
1017 */
1018 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1019 final String url, Bitmap favicon) {
1020 if (favicon == null) {
1021 return;
1022 }
1023 if (!tab.isPrivateBrowsingEnabled()) {
1024 Bookmarks.updateFavicon(mActivity
1025 .getContentResolver(), originalUrl, url, favicon);
1026 }
1027 }
1028
Leon Scroggins4cd97792010-12-03 15:31:56 -05001029 @Override
1030 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001031 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001032 mUi.bookmarkedStatusHasChanged(tab);
1033 }
1034
Michael Kolb8233fac2010-10-26 16:08:53 -07001035 // end WebViewController
1036
1037 protected void pageUp() {
1038 getCurrentTopWebView().pageUp(false);
1039 }
1040
1041 protected void pageDown() {
1042 getCurrentTopWebView().pageDown(false);
1043 }
1044
1045 // callback from phone title bar
1046 public void editUrl() {
1047 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001048 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001049 }
1050
Michael Kolbcfa3af52010-12-14 10:36:11 -08001051 public void startVoiceSearch() {
1052 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1053 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1054 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1055 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1056 mActivity.getComponentName().flattenToString());
1057 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001058 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001059 mActivity.startActivity(intent);
1060 }
1061
Michael Kolb8233fac2010-10-26 16:08:53 -07001062 public void activateVoiceSearchMode(String title) {
1063 mUi.showVoiceTitleBar(title);
1064 }
1065
1066 public void revertVoiceSearchMode(Tab tab) {
1067 mUi.revertVoiceTitleBar(tab);
1068 }
1069
Michael Kolb736990c2011-03-20 10:01:20 -07001070 public boolean supportsVoiceSearch() {
1071 SearchEngine searchEngine = BrowserSettings.getInstance()
1072 .getSearchEngine();
1073 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1074 }
1075
Michael Kolb8233fac2010-10-26 16:08:53 -07001076 public void showCustomView(Tab tab, View view,
1077 WebChromeClient.CustomViewCallback callback) {
1078 if (tab.inForeground()) {
1079 if (mUi.isCustomViewShowing()) {
1080 callback.onCustomViewHidden();
1081 return;
1082 }
1083 mUi.showCustomView(view, callback);
1084 // Save the menu state and set it to empty while the custom
1085 // view is showing.
1086 mOldMenuState = mMenuState;
1087 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001088 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001089 }
1090 }
1091
1092 @Override
1093 public void hideCustomView() {
1094 if (mUi.isCustomViewShowing()) {
1095 mUi.onHideCustomView();
1096 // Reset the old menu state.
1097 mMenuState = mOldMenuState;
1098 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001099 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001100 }
1101 }
1102
1103 protected void onActivityResult(int requestCode, int resultCode,
1104 Intent intent) {
1105 if (getCurrentTopWebView() == null) return;
1106 switch (requestCode) {
1107 case PREFERENCES_PAGE:
1108 if (resultCode == Activity.RESULT_OK && intent != null) {
1109 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
1110 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
1111 mTabControl.removeParentChildRelationShips();
1112 }
1113 }
1114 break;
1115 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001116 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001117 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001118 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001119 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001120 case AUTOFILL_SETUP:
1121 // Determine whether a profile was actually set up or not
1122 // and if so, send the message back to the WebTextView to
1123 // fill the form with the new profile.
1124 if (getSettings().getAutoFillProfile() != null) {
1125 mAutoFillSetupMessage.sendToTarget();
1126 mAutoFillSetupMessage = null;
1127 }
1128 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001129 default:
1130 break;
1131 }
1132 getCurrentTopWebView().requestFocus();
1133 }
1134
1135 /**
1136 * Open the Go page.
1137 * @param startWithHistory If true, open starting on the history tab.
1138 * Otherwise, start with the bookmarks tab.
1139 */
1140 @Override
1141 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1142 if (mTabControl.getCurrentWebView() == null) {
1143 return;
1144 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001145 // clear action mode
1146 if (isInCustomActionMode()) {
1147 endActionMode();
1148 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001149 Bundle extras = new Bundle();
1150 // Disable opening in a new window if we have maxed out the windows
1151 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1152 !mTabControl.canCreateNewTab());
1153 mUi.showComboView(startWithHistory, extras);
1154 }
1155
1156 // combo view callbacks
1157
1158 /**
1159 * callback from ComboPage when clear history is requested
1160 */
1161 public void onRemoveParentChildRelationships() {
1162 mTabControl.removeParentChildRelationShips();
1163 }
1164
1165 /**
1166 * callback from ComboPage when bookmark/history selection
1167 */
1168 @Override
1169 public void onUrlSelected(String url, boolean newTab) {
1170 removeComboView();
1171 if (!TextUtils.isEmpty(url)) {
1172 if (newTab) {
Michael Kolb18eb3772010-12-10 14:29:51 -08001173 openTab(mTabControl.getCurrentTab(), url, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001174 } else {
1175 final Tab currentTab = mTabControl.getCurrentTab();
1176 dismissSubWindow(currentTab);
1177 loadUrl(getCurrentTopWebView(), url);
1178 }
1179 }
1180 }
1181
1182 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07001183 * dismiss the ComboPage
1184 */
1185 @Override
1186 public void removeComboView() {
1187 mUi.hideComboView();
1188 }
1189
1190 // active tabs page handling
1191
1192 protected void showActiveTabsPage() {
1193 mMenuState = EMPTY_MENU;
1194 mUi.showActiveTabsPage();
1195 }
1196
1197 /**
1198 * Remove the active tabs page.
1199 * @param needToAttach If true, the active tabs page did not attach a tab
1200 * to the content view, so we need to do that here.
1201 */
1202 @Override
1203 public void removeActiveTabsPage(boolean needToAttach) {
1204 mMenuState = R.id.MAIN_MENU;
1205 mUi.removeActiveTabsPage();
1206 if (needToAttach) {
1207 setActiveTab(mTabControl.getCurrentTab());
1208 }
1209 getCurrentTopWebView().requestFocus();
1210 }
1211
1212 // key handling
1213 protected void onBackKey() {
1214 if (!mUi.onBackKey()) {
1215 WebView subwindow = mTabControl.getCurrentSubWindow();
1216 if (subwindow != null) {
1217 if (subwindow.canGoBack()) {
1218 subwindow.goBack();
1219 } else {
1220 dismissSubWindow(mTabControl.getCurrentTab());
1221 }
1222 } else {
1223 goBackOnePageOrQuit();
1224 }
1225 }
1226 }
1227
1228 // menu handling and state
1229 // TODO: maybe put into separate handler
1230
1231 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckb3417f02011-01-14 11:01:05 -08001232 if (mOptionsMenuHandler != null) {
1233 return mOptionsMenuHandler.onCreateOptionsMenu(menu);
1234 }
1235
John Reckd73c5a22010-12-22 10:22:50 -08001236 if (mMenuState == EMPTY_MENU) {
1237 return false;
1238 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001239 MenuInflater inflater = mActivity.getMenuInflater();
1240 inflater.inflate(R.menu.browser, menu);
1241 updateInLoadMenuItems(menu);
1242 // hold on to the menu reference here; it is used by the page callbacks
1243 // to update the menu based on loading state
1244 mCachedMenu = menu;
1245 return true;
1246 }
1247
1248 protected void onCreateContextMenu(ContextMenu menu, View v,
1249 ContextMenuInfo menuInfo) {
1250 if (v instanceof TitleBarBase) {
1251 return;
1252 }
1253 if (!(v instanceof WebView)) {
1254 return;
1255 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001256 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001257 WebView.HitTestResult result = webview.getHitTestResult();
1258 if (result == null) {
1259 return;
1260 }
1261
1262 int type = result.getType();
1263 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1264 Log.w(LOGTAG,
1265 "We should not show context menu when nothing is touched");
1266 return;
1267 }
1268 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1269 // let TextView handles context menu
1270 return;
1271 }
1272
1273 // Note, http://b/issue?id=1106666 is requesting that
1274 // an inflated menu can be used again. This is not available
1275 // yet, so inflate each time (yuk!)
1276 MenuInflater inflater = mActivity.getMenuInflater();
1277 inflater.inflate(R.menu.browsercontext, menu);
1278
1279 // Show the correct menu group
1280 final String extra = result.getExtra();
1281 menu.setGroupVisible(R.id.PHONE_MENU,
1282 type == WebView.HitTestResult.PHONE_TYPE);
1283 menu.setGroupVisible(R.id.EMAIL_MENU,
1284 type == WebView.HitTestResult.EMAIL_TYPE);
1285 menu.setGroupVisible(R.id.GEO_MENU,
1286 type == WebView.HitTestResult.GEO_TYPE);
1287 menu.setGroupVisible(R.id.IMAGE_MENU,
1288 type == WebView.HitTestResult.IMAGE_TYPE
1289 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1290 menu.setGroupVisible(R.id.ANCHOR_MENU,
1291 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1292 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001293 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1294 || type == WebView.HitTestResult.PHONE_TYPE
1295 || type == WebView.HitTestResult.EMAIL_TYPE
1296 || type == WebView.HitTestResult.GEO_TYPE;
1297 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1298 if (hitText) {
1299 menu.findItem(R.id.select_text_menu_id)
1300 .setOnMenuItemClickListener(new SelectText(webview));
1301 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001302 // Setup custom handling depending on the type
1303 switch (type) {
1304 case WebView.HitTestResult.PHONE_TYPE:
1305 menu.setHeaderTitle(Uri.decode(extra));
1306 menu.findItem(R.id.dial_context_menu_id).setIntent(
1307 new Intent(Intent.ACTION_VIEW, Uri
1308 .parse(WebView.SCHEME_TEL + extra)));
1309 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1310 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1311 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1312 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1313 addIntent);
1314 menu.findItem(R.id.copy_phone_context_menu_id)
1315 .setOnMenuItemClickListener(
1316 new Copy(extra));
1317 break;
1318
1319 case WebView.HitTestResult.EMAIL_TYPE:
1320 menu.setHeaderTitle(extra);
1321 menu.findItem(R.id.email_context_menu_id).setIntent(
1322 new Intent(Intent.ACTION_VIEW, Uri
1323 .parse(WebView.SCHEME_MAILTO + extra)));
1324 menu.findItem(R.id.copy_mail_context_menu_id)
1325 .setOnMenuItemClickListener(
1326 new Copy(extra));
1327 break;
1328
1329 case WebView.HitTestResult.GEO_TYPE:
1330 menu.setHeaderTitle(extra);
1331 menu.findItem(R.id.map_context_menu_id).setIntent(
1332 new Intent(Intent.ACTION_VIEW, Uri
1333 .parse(WebView.SCHEME_GEO
1334 + URLEncoder.encode(extra))));
1335 menu.findItem(R.id.copy_geo_context_menu_id)
1336 .setOnMenuItemClickListener(
1337 new Copy(extra));
1338 break;
1339
1340 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1341 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001342 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001343 // decide whether to show the open link in new tab option
1344 boolean showNewTab = mTabControl.canCreateNewTab();
1345 MenuItem newTabItem
1346 = menu.findItem(R.id.open_newtab_context_menu_id);
Michael Kolb2dd65c82011-01-14 11:07:38 -08001347 newTabItem.setTitle(
1348 BrowserSettings.getInstance().openInBackground()
1349 ? R.string.contextmenu_openlink_newwindow_background
1350 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001351 newTabItem.setVisible(showNewTab);
1352 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001353 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1354 newTabItem.setOnMenuItemClickListener(
1355 new MenuItem.OnMenuItemClickListener() {
1356 @Override
1357 public boolean onMenuItemClick(MenuItem item) {
1358 final HashMap<String, WebView> hrefMap =
1359 new HashMap<String, WebView>();
1360 hrefMap.put("webview", webview);
1361 final Message msg = mHandler.obtainMessage(
1362 FOCUS_NODE_HREF,
1363 R.id.open_newtab_context_menu_id,
1364 0, hrefMap);
1365 webview.requestFocusNodeHref(msg);
1366 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001367 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001368 });
1369 } else {
1370 newTabItem.setOnMenuItemClickListener(
1371 new MenuItem.OnMenuItemClickListener() {
1372 @Override
1373 public boolean onMenuItemClick(MenuItem item) {
1374 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -08001375 final Tab newTab = openTab(parent,
1376 extra, false);
Leon Scroggins026f2542010-11-22 13:26:12 -05001377 if (newTab != parent) {
1378 parent.addChildTab(newTab);
1379 }
1380 return true;
1381 }
1382 });
1383 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001384 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001385 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1386 break;
1387 }
1388 // otherwise fall through to handle image part
1389 case WebView.HitTestResult.IMAGE_TYPE:
1390 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1391 menu.setHeaderTitle(extra);
1392 }
1393 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1394 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1395 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001396 setOnMenuItemClickListener(
1397 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001398 menu.findItem(R.id.set_wallpaper_context_menu_id).
1399 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1400 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001401 break;
1402
1403 default:
1404 Log.w(LOGTAG, "We should not get here.");
1405 break;
1406 }
1407 //update the ui
1408 mUi.onContextMenuCreated(menu);
1409 }
1410
1411 /**
1412 * As the menu can be open when loading state changes
1413 * we must manually update the state of the stop/reload menu
1414 * item
1415 */
1416 private void updateInLoadMenuItems(Menu menu) {
1417 if (menu == null) {
1418 return;
1419 }
1420 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1421 MenuItem src = mInLoad ?
1422 menu.findItem(R.id.stop_menu_id):
1423 menu.findItem(R.id.reload_menu_id);
1424 if (src != null) {
1425 dest.setIcon(src.getIcon());
1426 dest.setTitle(src.getTitle());
1427 }
1428 }
1429
John Reckb3417f02011-01-14 11:01:05 -08001430 boolean onPrepareOptionsMenu(Menu menu) {
1431 if (mOptionsMenuHandler != null) {
1432 return mOptionsMenuHandler.onPrepareOptionsMenu(menu);
1433 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001434 // This happens when the user begins to hold down the menu key, so
1435 // allow them to chord to get a shortcut.
1436 mCanChord = true;
1437 // Note: setVisible will decide whether an item is visible; while
1438 // setEnabled() will decide whether an item is enabled, which also means
1439 // whether the matching shortcut key will function.
1440 switch (mMenuState) {
1441 case EMPTY_MENU:
1442 if (mCurrentMenuState != mMenuState) {
1443 menu.setGroupVisible(R.id.MAIN_MENU, false);
1444 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1445 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1446 }
1447 break;
1448 default:
1449 if (mCurrentMenuState != mMenuState) {
1450 menu.setGroupVisible(R.id.MAIN_MENU, true);
1451 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1452 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1453 }
1454 final WebView w = getCurrentTopWebView();
1455 boolean canGoBack = false;
1456 boolean canGoForward = false;
1457 boolean isHome = false;
1458 if (w != null) {
1459 canGoBack = w.canGoBack();
1460 canGoForward = w.canGoForward();
1461 isHome = mSettings.getHomePage().equals(w.getUrl());
1462 }
1463 final MenuItem back = menu.findItem(R.id.back_menu_id);
1464 back.setEnabled(canGoBack);
1465
1466 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1467 home.setEnabled(!isHome);
1468
1469 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1470 forward.setEnabled(canGoForward);
1471
1472 // decide whether to show the share link option
1473 PackageManager pm = mActivity.getPackageManager();
1474 Intent send = new Intent(Intent.ACTION_SEND);
1475 send.setType("text/plain");
1476 ResolveInfo ri = pm.resolveActivity(send,
1477 PackageManager.MATCH_DEFAULT_ONLY);
1478 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1479
1480 boolean isNavDump = mSettings.isNavDump();
1481 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1482 nav.setVisible(isNavDump);
1483 nav.setEnabled(isNavDump);
1484
1485 boolean showDebugSettings = mSettings.showDebugSettings();
1486 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1487 counter.setVisible(showDebugSettings);
1488 counter.setEnabled(showDebugSettings);
1489
John Reckb3417f02011-01-14 11:01:05 -08001490 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1491 newtab.setEnabled(getTabControl().canCreateNewTab());
Michael Kolb8233fac2010-10-26 16:08:53 -07001492
Leon Scroggins81983762011-02-11 15:17:36 -05001493 MenuItem archive = menu.findItem(R.id.save_webarchive_menu_id);
John Reck51d8bad2011-02-28 15:47:47 -08001494 Tab tab = getTabControl().getCurrentTab();
1495 String url = tab != null ? tab.getUrl() : null;
1496 archive.setVisible(!TextUtils.isEmpty(url)
1497 && !url.endsWith(".webarchivexml"));
Michael Kolb8233fac2010-10-26 16:08:53 -07001498 break;
1499 }
1500 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001501 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001502 }
1503
1504 public boolean onOptionsItemSelected(MenuItem item) {
John Reckb3417f02011-01-14 11:01:05 -08001505 if (mOptionsMenuHandler != null &&
1506 mOptionsMenuHandler.onOptionsItemSelected(item)) {
1507 return true;
1508 }
1509
Michael Kolb8233fac2010-10-26 16:08:53 -07001510 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1511 // menu remains active, so ensure comboview is dismissed
1512 // if main menu option is selected
1513 removeComboView();
1514 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001515 if (!mCanChord) {
1516 // The user has already fired a shortcut with this hold down of the
1517 // menu key.
1518 return false;
1519 }
1520 if (null == getCurrentTopWebView()) {
1521 return false;
1522 }
1523 if (mMenuIsDown) {
1524 // The shortcut action consumes the MENU. Even if it is still down,
1525 // it won't trigger the next shortcut action. In the case of the
1526 // shortcut action triggering a new activity, like Bookmarks, we
1527 // won't get onKeyUp for MENU. So it is important to reset it here.
1528 mMenuIsDown = false;
1529 }
1530 switch (item.getItemId()) {
1531 // -- Main menu
1532 case R.id.new_tab_menu_id:
1533 openTabToHomePage();
1534 break;
1535
1536 case R.id.incognito_menu_id:
1537 openIncognitoTab();
1538 break;
1539
1540 case R.id.goto_menu_id:
1541 editUrl();
1542 break;
1543
1544 case R.id.bookmarks_menu_id:
1545 bookmarksOrHistoryPicker(false);
1546 break;
1547
1548 case R.id.active_tabs_menu_id:
1549 showActiveTabsPage();
1550 break;
1551
1552 case R.id.add_bookmark_menu_id:
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001553 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001554 break;
1555
1556 case R.id.stop_reload_menu_id:
1557 if (mInLoad) {
1558 stopLoading();
1559 } else {
1560 getCurrentTopWebView().reload();
1561 }
1562 break;
1563
1564 case R.id.back_menu_id:
1565 getCurrentTopWebView().goBack();
1566 break;
1567
1568 case R.id.forward_menu_id:
1569 getCurrentTopWebView().goForward();
1570 break;
1571
1572 case R.id.close_menu_id:
1573 // Close the subwindow if it exists.
1574 if (mTabControl.getCurrentSubWindow() != null) {
1575 dismissSubWindow(mTabControl.getCurrentTab());
1576 break;
1577 }
1578 closeCurrentTab();
1579 break;
1580
1581 case R.id.homepage_menu_id:
1582 Tab current = mTabControl.getCurrentTab();
1583 if (current != null) {
1584 dismissSubWindow(current);
1585 loadUrl(current.getWebView(), mSettings.getHomePage());
1586 }
1587 break;
1588
1589 case R.id.preferences_menu_id:
1590 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1591 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1592 getCurrentTopWebView().getUrl());
1593 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1594 break;
1595
1596 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001597 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001598 break;
1599
Leon Scrogginsac993842011-02-02 12:54:07 -05001600 case R.id.save_webarchive_menu_id:
1601 String state = Environment.getExternalStorageState();
1602 if (!Environment.MEDIA_MOUNTED.equals(state)) {
1603 Log.e(LOGTAG, "External storage not mounted");
1604 Toast.makeText(mActivity, R.string.webarchive_failed,
1605 Toast.LENGTH_SHORT).show();
1606 break;
1607 }
1608 final String directory = Environment.getExternalStoragePublicDirectory(
1609 Environment.DIRECTORY_DOWNLOADS) + File.separator;
1610 File dir = new File(directory);
1611 if (!dir.exists() && !dir.mkdirs()) {
1612 Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
1613 Toast.makeText(mActivity, R.string.webarchive_failed,
1614 Toast.LENGTH_SHORT).show();
1615 break;
1616 }
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001617 final WebView topWebView = getCurrentTopWebView();
Leon Scrogginsac993842011-02-02 12:54:07 -05001618 final String title = topWebView.getTitle();
John Reck51d8bad2011-02-28 15:47:47 -08001619 final String url = topWebView.getUrl();
Leon Scrogginsac993842011-02-02 12:54:07 -05001620 topWebView.saveWebArchive(directory, true,
1621 new ValueCallback<String>() {
1622 @Override
1623 public void onReceiveValue(final String value) {
1624 if (value != null) {
1625 File file = new File(value);
1626 final long length = file.length();
1627 if (file.exists() && length > 0) {
Leon Scroggins1cb96552011-02-11 14:22:57 -05001628 Toast.makeText(mActivity, R.string.webarchive_saved,
1629 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001630 final DownloadManager manager = (DownloadManager) mActivity
1631 .getSystemService(Context.DOWNLOAD_SERVICE);
1632 new Thread("Add WebArchive to download manager") {
1633 @Override
1634 public void run() {
Vasu Noria9e30a72011-03-07 11:37:34 -08001635 manager.addCompletedDownload(
1636 null == title ? value : title,
Leon Scrogginsac993842011-02-02 12:54:07 -05001637 value, true, "application/x-webarchive-xml",
1638 value, length, true);
1639 }
1640 }.start();
1641 return;
1642 }
1643 }
John Reck51d8bad2011-02-28 15:47:47 -08001644 DownloadHandler.onDownloadStartNoStream(mActivity,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001645 url, null, null, null, topWebView.isPrivateBrowsingEnabled());
Leon Scrogginsac993842011-02-02 12:54:07 -05001646 }
1647 });
1648 break;
1649
Michael Kolb8233fac2010-10-26 16:08:53 -07001650 case R.id.page_info_menu_id:
1651 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1652 false);
1653 break;
1654
1655 case R.id.classic_history_menu_id:
1656 bookmarksOrHistoryPicker(true);
1657 break;
1658
1659 case R.id.title_bar_share_page_url:
1660 case R.id.share_page_menu_id:
1661 Tab currentTab = mTabControl.getCurrentTab();
1662 if (null == currentTab) {
1663 mCanChord = false;
1664 return false;
1665 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001666 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001667 break;
1668
1669 case R.id.dump_nav_menu_id:
1670 getCurrentTopWebView().debugDump();
1671 break;
1672
1673 case R.id.dump_counters_menu_id:
1674 getCurrentTopWebView().dumpV8Counters();
1675 break;
1676
1677 case R.id.zoom_in_menu_id:
1678 getCurrentTopWebView().zoomIn();
1679 break;
1680
1681 case R.id.zoom_out_menu_id:
1682 getCurrentTopWebView().zoomOut();
1683 break;
1684
1685 case R.id.view_downloads_menu_id:
1686 viewDownloads();
1687 break;
1688
1689 case R.id.window_one_menu_id:
1690 case R.id.window_two_menu_id:
1691 case R.id.window_three_menu_id:
1692 case R.id.window_four_menu_id:
1693 case R.id.window_five_menu_id:
1694 case R.id.window_six_menu_id:
1695 case R.id.window_seven_menu_id:
1696 case R.id.window_eight_menu_id:
1697 {
1698 int menuid = item.getItemId();
1699 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1700 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1701 Tab desiredTab = mTabControl.getTab(id);
1702 if (desiredTab != null &&
1703 desiredTab != mTabControl.getCurrentTab()) {
1704 switchToTab(id);
1705 }
1706 break;
1707 }
1708 }
1709 }
1710 break;
1711
1712 default:
1713 return false;
1714 }
1715 mCanChord = false;
1716 return true;
1717 }
1718
1719 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001720 // Let the History and Bookmark fragments handle menus they created.
1721 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1722 return false;
1723 }
1724
Michael Kolb8233fac2010-10-26 16:08:53 -07001725 // chording is not an issue with context menus, but we use the same
1726 // options selector, so set mCanChord to true so we can access them.
1727 mCanChord = true;
1728 int id = item.getItemId();
1729 boolean result = true;
1730 switch (id) {
1731 // For the context menu from the title bar
1732 case R.id.title_bar_copy_page_url:
1733 Tab currentTab = mTabControl.getCurrentTab();
1734 if (null == currentTab) {
1735 result = false;
1736 break;
1737 }
1738 WebView mainView = currentTab.getWebView();
1739 if (null == mainView) {
1740 result = false;
1741 break;
1742 }
1743 copy(mainView.getUrl());
1744 break;
1745 // -- Browser context menu
1746 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001747 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001748 case R.id.copy_link_context_menu_id:
1749 final WebView webView = getCurrentTopWebView();
1750 if (null == webView) {
1751 result = false;
1752 break;
1753 }
1754 final HashMap<String, WebView> hrefMap =
1755 new HashMap<String, WebView>();
1756 hrefMap.put("webview", webView);
1757 final Message msg = mHandler.obtainMessage(
1758 FOCUS_NODE_HREF, id, 0, hrefMap);
1759 webView.requestFocusNodeHref(msg);
1760 break;
1761
1762 default:
1763 // For other context menus
1764 result = onOptionsItemSelected(item);
1765 }
1766 mCanChord = false;
1767 return result;
1768 }
1769
1770 /**
1771 * support programmatically opening the context menu
1772 */
1773 public void openContextMenu(View view) {
1774 mActivity.openContextMenu(view);
1775 }
1776
1777 /**
1778 * programmatically open the options menu
1779 */
1780 public void openOptionsMenu() {
1781 mActivity.openOptionsMenu();
1782 }
1783
1784 public boolean onMenuOpened(int featureId, Menu menu) {
1785 if (mOptionsMenuOpen) {
1786 if (mConfigChanged) {
1787 // We do not need to make any changes to the state of the
1788 // title bar, since the only thing that happened was a
1789 // change in orientation
1790 mConfigChanged = false;
1791 } else {
1792 if (!mExtendedMenuOpen) {
1793 mExtendedMenuOpen = true;
1794 mUi.onExtendedMenuOpened();
1795 } else {
1796 // Switching the menu back to icon view, so show the
1797 // title bar once again.
1798 mExtendedMenuOpen = false;
1799 mUi.onExtendedMenuClosed(mInLoad);
1800 mUi.onOptionsMenuOpened();
1801 }
1802 }
1803 } else {
1804 // The options menu is closed, so open it, and show the title
1805 mOptionsMenuOpen = true;
1806 mConfigChanged = false;
1807 mExtendedMenuOpen = false;
1808 mUi.onOptionsMenuOpened();
1809 }
1810 return true;
1811 }
1812
1813 public void onOptionsMenuClosed(Menu menu) {
1814 mOptionsMenuOpen = false;
1815 mUi.onOptionsMenuClosed(mInLoad);
1816 }
1817
1818 public void onContextMenuClosed(Menu menu) {
1819 mUi.onContextMenuClosed(menu, mInLoad);
1820 }
1821
1822 // Helper method for getting the top window.
1823 @Override
1824 public WebView getCurrentTopWebView() {
1825 return mTabControl.getCurrentTopWebView();
1826 }
1827
1828 @Override
1829 public WebView getCurrentWebView() {
1830 return mTabControl.getCurrentWebView();
1831 }
1832
1833 /*
1834 * This method is called as a result of the user selecting the options
1835 * menu to see the download window. It shows the download window on top of
1836 * the current window.
1837 */
1838 void viewDownloads() {
1839 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1840 mActivity.startActivity(intent);
1841 }
1842
1843 // action mode
1844
1845 void onActionModeStarted(ActionMode mode) {
1846 mUi.onActionModeStarted(mode);
1847 mActionMode = mode;
1848 }
1849
1850 /*
1851 * True if a custom ActionMode (i.e. find or select) is in use.
1852 */
1853 @Override
1854 public boolean isInCustomActionMode() {
1855 return mActionMode != null;
1856 }
1857
1858 /*
1859 * End the current ActionMode.
1860 */
1861 @Override
1862 public void endActionMode() {
1863 if (mActionMode != null) {
1864 mActionMode.finish();
1865 }
1866 }
1867
1868 /*
1869 * Called by find and select when they are finished. Replace title bars
1870 * as necessary.
1871 */
1872 public void onActionModeFinished(ActionMode mode) {
1873 if (!isInCustomActionMode()) return;
1874 mUi.onActionModeFinished(mInLoad);
1875 mActionMode = null;
1876 }
1877
1878 boolean isInLoad() {
1879 return mInLoad;
1880 }
1881
1882 // bookmark handling
1883
1884 /**
1885 * add the current page as a bookmark to the given folder id
1886 * @param folderId use -1 for the default folder
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001887 * @param canBeAnEdit If true, check to see whether the site is already
1888 * bookmarked, and if it is, edit that bookmark. If false, and
1889 * the site is already bookmarked, do not attempt to edit the
1890 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001891 */
1892 @Override
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001893 public void bookmarkCurrentPage(long folderId, boolean canBeAnEdit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001894 Intent i = new Intent(mActivity,
1895 AddBookmarkPage.class);
1896 WebView w = getCurrentTopWebView();
1897 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1898 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1899 String touchIconUrl = w.getTouchIconUrl();
1900 if (touchIconUrl != null) {
1901 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1902 WebSettings settings = w.getSettings();
1903 if (settings != null) {
1904 i.putExtra(AddBookmarkPage.USER_AGENT,
1905 settings.getUserAgentString());
1906 }
1907 }
1908 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1909 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1910 getDesiredThumbnailHeight(mActivity)));
1911 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1912 i.putExtra(BrowserContract.Bookmarks.PARENT,
1913 folderId);
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001914 if (canBeAnEdit) {
1915 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1916 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001917 // Put the dialog at the upper right of the screen, covering the
1918 // star on the title bar.
1919 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1920 mActivity.startActivity(i);
1921 }
1922
1923 // file chooser
1924 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1925 mUploadHandler = new UploadHandler(this);
1926 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1927 }
1928
1929 // thumbnails
1930
1931 /**
1932 * Return the desired width for thumbnail screenshots, which are stored in
1933 * the database, and used on the bookmarks screen.
1934 * @param context Context for finding out the density of the screen.
1935 * @return desired width for thumbnail screenshot.
1936 */
1937 static int getDesiredThumbnailWidth(Context context) {
1938 return context.getResources().getDimensionPixelOffset(
1939 R.dimen.bookmarkThumbnailWidth);
1940 }
1941
1942 /**
1943 * Return the desired height for thumbnail screenshots, which are stored in
1944 * the database, and used on the bookmarks screen.
1945 * @param context Context for finding out the density of the screen.
1946 * @return desired height for thumbnail screenshot.
1947 */
1948 static int getDesiredThumbnailHeight(Context context) {
1949 return context.getResources().getDimensionPixelOffset(
1950 R.dimen.bookmarkThumbnailHeight);
1951 }
1952
Michael Kolb1acef692011-03-08 14:12:06 -08001953 static Bitmap createScreenshot(Tab tab, int width, int height) {
1954 if ((tab != null) && (tab.getWebView() != null)) {
1955 return createScreenshot(tab.getWebView(), width, height);
1956 }
1957 return null;
1958 }
1959
Michael Kolb8233fac2010-10-26 16:08:53 -07001960 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001961 // We render to a bitmap 2x the desired size so that we can then
1962 // re-scale it with filtering since canvas.scale doesn't filter
1963 // This helps reduce aliasing at the cost of being slightly blurry
1964 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001965 Picture thumbnail = view.capturePicture();
1966 if (thumbnail == null) {
1967 return null;
1968 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001969 width *= filter_scale;
1970 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001971 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1972 Canvas canvas = new Canvas(bm);
1973 // May need to tweak these values to determine what is the
1974 // best scale factor
1975 int thumbnailWidth = thumbnail.getWidth();
1976 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001977 float scaleFactor = 1.0f;
Michael Kolbeb95db42011-03-03 10:38:40 -08001978 if (thumbnailWidth > 0 && thumbnailHeight > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001979 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001980 } else {
1981 return null;
1982 }
John Reckfe49ab42010-11-16 17:09:37 -08001983
Michael Kolbeb95db42011-03-03 10:38:40 -08001984 float scaleFactorY = (float) height / (float)thumbnailHeight;
1985 if (scaleFactorY > scaleFactor) {
1986 // The picture is narrower than the requested AR
1987 // Center the thumnail and crop the sides
1988 scaleFactor = scaleFactorY;
John Reckfe49ab42010-11-16 17:09:37 -08001989 float wx = (thumbnailWidth * scaleFactor) - width;
1990 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001991 }
1992
John Reckfe49ab42010-11-16 17:09:37 -08001993 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001994
1995 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001996 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
1997 height / filter_scale, true);
1998 bm.recycle();
1999 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07002000 }
2001
John Reck34ef2672011-02-10 11:30:55 -08002002 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002003 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07002004 // FIXME: Would like to make sure there is actually something to
2005 // draw, but the API for that (WebViewCore.pictureReady()) is not
2006 // currently accessible here.
2007
John Reck34ef2672011-02-10 11:30:55 -08002008 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08002009 if (view == null) {
2010 // Tab was destroyed
2011 return;
2012 }
John Reck34ef2672011-02-10 11:30:55 -08002013 final String url = tab.getUrl();
2014 final String originalUrl = view.getOriginalUrl();
2015
2016 if (TextUtils.isEmpty(url)) {
2017 return;
2018 }
2019
2020 // Only update thumbnails for web urls (http(s)://), not for
2021 // about:, javascript:, data:, etc...
2022 // Unless it is a bookmarked site, then always update
2023 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2024 return;
2025 }
2026
Michael Kolb8233fac2010-10-26 16:08:53 -07002027 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2028 getDesiredThumbnailHeight(mActivity));
2029 if (bm == null) {
2030 return;
2031 }
2032
2033 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002034 new AsyncTask<Void, Void, Void>() {
2035 @Override
2036 protected Void doInBackground(Void... unused) {
2037 Cursor cursor = null;
2038 try {
2039 // TODO: Clean this up
2040 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2041 if (cursor != null && cursor.moveToFirst()) {
2042 final ByteArrayOutputStream os =
2043 new ByteArrayOutputStream();
2044 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002045
John Reck34ef2672011-02-10 11:30:55 -08002046 ContentValues values = new ContentValues();
2047 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002048
John Reck34ef2672011-02-10 11:30:55 -08002049 do {
John Reck617fd832011-02-16 14:35:59 -08002050 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002051 cr.update(Images.CONTENT_URI, values, null, null);
2052 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002053 }
John Reck34ef2672011-02-10 11:30:55 -08002054 } catch (IllegalStateException e) {
2055 // Ignore
2056 } finally {
2057 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002058 }
John Reck34ef2672011-02-10 11:30:55 -08002059 return null;
2060 }
2061 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002062 }
2063
2064 private class Copy implements OnMenuItemClickListener {
2065 private CharSequence mText;
2066
2067 public boolean onMenuItemClick(MenuItem item) {
2068 copy(mText);
2069 return true;
2070 }
2071
2072 public Copy(CharSequence toCopy) {
2073 mText = toCopy;
2074 }
2075 }
2076
Leon Scroggins63c02662010-11-18 15:16:27 -05002077 private static class Download implements OnMenuItemClickListener {
2078 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002079 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002080 private boolean mPrivateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002081
2082 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002083 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002084 null, null, mPrivateBrowsing);
Michael Kolb8233fac2010-10-26 16:08:53 -07002085 return true;
2086 }
2087
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002088 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002089 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002090 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002091 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002092 }
2093 }
2094
Cary Clark8974d282010-11-22 10:46:05 -05002095 private static class SelectText implements OnMenuItemClickListener {
2096 private WebView mWebView;
2097
2098 public boolean onMenuItemClick(MenuItem item) {
2099 if (mWebView != null) {
2100 return mWebView.selectText();
2101 }
2102 return false;
2103 }
2104
2105 public SelectText(WebView webView) {
2106 mWebView = webView;
2107 }
2108
2109 }
2110
Michael Kolb8233fac2010-10-26 16:08:53 -07002111 /********************** TODO: UI stuff *****************************/
2112
2113 // these methods have been copied, they still need to be cleaned up
2114
2115 /****************** tabs ***************************************************/
2116
2117 // basic tab interactions:
2118
2119 // it is assumed that tabcontrol already knows about the tab
2120 protected void addTab(Tab tab) {
2121 mUi.addTab(tab);
2122 }
2123
2124 protected void removeTab(Tab tab) {
2125 mUi.removeTab(tab);
2126 mTabControl.removeTab(tab);
2127 }
2128
2129 protected void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002130 // monkey protection against delayed start
2131 if (tab != null) {
2132 mTabControl.setCurrentTab(tab);
2133 // the tab is guaranteed to have a webview after setCurrentTab
2134 mUi.setActiveTab(tab);
2135 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002136 }
2137
2138 protected void closeEmptyChildTab() {
2139 Tab current = mTabControl.getCurrentTab();
2140 if (current != null
2141 && current.getWebView().copyBackForwardList().getSize() == 0) {
2142 Tab parent = current.getParentTab();
2143 if (parent != null) {
2144 switchToTab(mTabControl.getTabIndex(parent));
2145 closeTab(current);
2146 }
2147 }
2148 }
2149
2150 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002151 // Dismiss the subwindow if applicable.
2152 dismissSubWindow(appTab);
2153 // Since we might kill the WebView, remove it from the
2154 // content view first.
2155 mUi.detachTab(appTab);
2156 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002157 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002158 // TODO: analyze why the remove and add are necessary
2159 mUi.attachTab(appTab);
2160 if (mTabControl.getCurrentTab() != appTab) {
2161 switchToTab(mTabControl.getTabIndex(appTab));
John Reck30c714c2010-12-16 17:30:34 -08002162 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002163 } else {
2164 // If the tab was the current tab, we have to attach
2165 // it to the view system again.
2166 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002167 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002168 }
2169 }
2170
2171 // Remove the sub window if it exists. Also called by TabControl when the
2172 // user clicks the 'X' to dismiss a sub window.
2173 public void dismissSubWindow(Tab tab) {
2174 removeSubWindow(tab);
2175 // dismiss the subwindow. This will destroy the WebView.
2176 tab.dismissSubWindow();
2177 getCurrentTopWebView().requestFocus();
2178 }
2179
2180 @Override
2181 public void removeSubWindow(Tab t) {
2182 if (t.getSubWebView() != null) {
2183 mUi.removeSubWindow(t.getSubViewContainer());
2184 }
2185 }
2186
2187 @Override
2188 public void attachSubWindow(Tab tab) {
2189 if (tab.getSubWebView() != null) {
2190 mUi.attachSubWindow(tab.getSubViewContainer());
2191 getCurrentTopWebView().requestFocus();
2192 }
2193 }
2194
Michael Kolb843510f2010-12-09 10:51:49 -08002195 @Override
2196 public Tab openTabToHomePage() {
2197 // check for max tabs
2198 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002199 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2200 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002201 } else {
2202 mUi.showMaxTabsWarning();
2203 return null;
2204 }
2205 }
2206
Michael Kolb18eb3772010-12-10 14:29:51 -08002207 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2208 if (mSettings.openInBackground() && !forceForeground) {
2209 Tab tab = mTabControl.createNewTab(false, null, null,
2210 (parent != null) && parent.isPrivateBrowsingEnabled());
2211 if (tab != null) {
2212 addTab(tab);
2213 WebView view = tab.getWebView();
2214 loadUrl(view, url);
2215 }
2216 return tab;
2217 } else {
2218 return openTabAndShow(parent, new UrlData(url), false, null);
2219 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002220 }
2221
Michael Kolb18eb3772010-12-10 14:29:51 -08002222
Michael Kolb8233fac2010-10-26 16:08:53 -07002223 // This method does a ton of stuff. It will attempt to create a new tab
2224 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2225 // url isn't null, it will load the given url.
Patrick Scottcd135082011-01-31 18:21:58 -05002226 public Tab openTabAndShow(Tab parent, final UrlData urlData,
2227 boolean closeOnExit, String appId) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002228 final Tab currentTab = mTabControl.getCurrentTab();
2229 if (mTabControl.canCreateNewTab()) {
2230 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Michael Kolb18eb3772010-12-10 14:29:51 -08002231 urlData.mUrl,
2232 (parent != null) && parent.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -07002233 WebView webview = tab.getWebView();
2234 // We must set the new tab as the current tab to reflect the old
2235 // animation behavior.
2236 addTab(tab);
2237 setActiveTab(tab);
Patrick Scottd43e75a2011-03-14 14:47:23 -04002238 if (!urlData.isEmpty()) {
2239 loadUrlDataIn(tab, urlData);
2240 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002241 return tab;
2242 } else {
2243 // Get rid of the subwindow if it exists
2244 dismissSubWindow(currentTab);
2245 if (!urlData.isEmpty()) {
2246 // Load the given url.
2247 loadUrlDataIn(currentTab, urlData);
2248 }
2249 return currentTab;
2250 }
2251 }
2252
Michael Kolb8233fac2010-10-26 16:08:53 -07002253 @Override
2254 public Tab openIncognitoTab() {
2255 if (mTabControl.canCreateNewTab()) {
2256 Tab currentTab = mTabControl.getCurrentTab();
Michael Kolb8e7178d2011-01-26 19:13:36 -08002257 Tab tab = mTabControl.createNewTab(false, null,
John Reck4bfc0db2011-01-27 17:47:12 -08002258 null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07002259 addTab(tab);
2260 setActiveTab(tab);
John Reck4bfc0db2011-01-27 17:47:12 -08002261 loadUrlDataIn(tab, new UrlData("browser:incognito"));
Michael Kolb8233fac2010-10-26 16:08:53 -07002262 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002263 } else {
2264 mUi.showMaxTabsWarning();
2265 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002266 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002267 }
2268
2269 /**
2270 * @param index Index of the tab to change to, as defined by
2271 * mTabControl.getTabIndex(Tab t).
2272 * @return boolean True if we successfully switched to a different tab. If
2273 * the indexth tab is null, or if that tab is the same as
2274 * the current one, return false.
2275 */
2276 @Override
2277 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002278 // hide combo view if open
2279 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002280 Tab tab = mTabControl.getTab(index);
2281 Tab currentTab = mTabControl.getCurrentTab();
2282 if (tab == null || tab == currentTab) {
2283 return false;
2284 }
2285 setActiveTab(tab);
2286 return true;
2287 }
2288
2289 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002290 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002291 // hide combo view if open
2292 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002293 final Tab current = mTabControl.getCurrentTab();
2294 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002295 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002296 return;
2297 }
2298 final Tab parent = current.getParentTab();
2299 int indexToShow = -1;
2300 if (parent != null) {
2301 indexToShow = mTabControl.getTabIndex(parent);
2302 } else {
2303 final int currentIndex = mTabControl.getCurrentIndex();
2304 // Try to move to the tab to the right
2305 indexToShow = currentIndex + 1;
2306 if (indexToShow > mTabControl.getTabCount() - 1) {
2307 // Try to move to the tab to the left
2308 indexToShow = currentIndex - 1;
2309 }
2310 }
2311 if (switchToTab(indexToShow)) {
2312 // Close window
2313 closeTab(current);
2314 }
2315 }
2316
2317 /**
2318 * Close the tab, remove its associated title bar, and adjust mTabControl's
2319 * current tab to a valid value.
2320 */
2321 @Override
2322 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002323 // hide combo view if open
2324 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002325 int currentIndex = mTabControl.getCurrentIndex();
2326 int removeIndex = mTabControl.getTabIndex(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002327 Tab newtab = mTabControl.getTab(currentIndex);
2328 setActiveTab(newtab);
Michael Kolb2d59c322011-01-25 13:18:55 -08002329 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002330 }
2331
2332 /**************** TODO: Url loading clean up *******************************/
2333
2334 // Called when loading from context menu or LOAD_URL message
2335 protected void loadUrlFromContext(WebView view, String url) {
2336 // In case the user enters nothing.
2337 if (url != null && url.length() != 0 && view != null) {
2338 url = UrlUtils.smartUrlFilter(url);
2339 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2340 loadUrl(view, url);
2341 }
2342 }
2343 }
2344
2345 /**
2346 * Load the URL into the given WebView and update the title bar
2347 * to reflect the new load. Call this instead of WebView.loadUrl
2348 * directly.
2349 * @param view The WebView used to load url.
2350 * @param url The URL to load.
2351 */
2352 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002353 view.loadUrl(url);
2354 }
2355
2356 /**
2357 * Load UrlData into a Tab and update the title bar to reflect the new
2358 * load. Call this instead of UrlData.loadIn directly.
2359 * @param t The Tab used to load.
2360 * @param data The UrlData being loaded.
2361 */
2362 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002363 data.loadIn(t);
2364 }
2365
John Reck30c714c2010-12-16 17:30:34 -08002366 @Override
2367 public void onUserCanceledSsl(Tab tab) {
2368 WebView web = tab.getWebView();
2369 // TODO: Figure out the "right" behavior
2370 if (web.canGoBack()) {
2371 web.goBack();
2372 } else {
2373 web.loadUrl(mSettings.getHomePage());
2374 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002375 }
2376
2377 void goBackOnePageOrQuit() {
2378 Tab current = mTabControl.getCurrentTab();
2379 if (current == null) {
2380 /*
2381 * Instead of finishing the activity, simply push this to the back
2382 * of the stack and let ActivityManager to choose the foreground
2383 * activity. As BrowserActivity is singleTask, it will be always the
2384 * root of the task. So we can use either true or false for
2385 * moveTaskToBack().
2386 */
2387 mActivity.moveTaskToBack(true);
2388 return;
2389 }
2390 WebView w = current.getWebView();
2391 if (w.canGoBack()) {
2392 w.goBack();
2393 } else {
2394 // Check to see if we are closing a window that was created by
2395 // another window. If so, we switch back to that window.
2396 Tab parent = current.getParentTab();
2397 if (parent != null) {
2398 switchToTab(mTabControl.getTabIndex(parent));
2399 // Now we close the other tab
2400 closeTab(current);
2401 } else {
2402 if (current.closeOnExit()) {
Patrick Scottfc1518a2011-02-28 13:57:03 -05002403 // This will finish the activity if there is only one tab
2404 // open or it will switch to the next available tab if
2405 // available.
Michael Kolb96683f72011-02-15 14:24:35 -08002406 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002407 }
2408 /*
2409 * Instead of finishing the activity, simply push this to the back
2410 * of the stack and let ActivityManager to choose the foreground
2411 * activity. As BrowserActivity is singleTask, it will be always the
2412 * root of the task. So we can use either true or false for
2413 * moveTaskToBack().
2414 */
2415 mActivity.moveTaskToBack(true);
2416 }
2417 }
2418 }
2419
2420 /**
2421 * Feed the previously stored results strings to the BrowserProvider so that
2422 * the SearchDialog will show them instead of the standard searches.
2423 * @param result String to show on the editable line of the SearchDialog.
2424 */
2425 @Override
2426 public void showVoiceSearchResults(String result) {
2427 ContentProviderClient client = mActivity.getContentResolver()
2428 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2429 ContentProvider prov = client.getLocalContentProvider();
2430 BrowserProvider bp = (BrowserProvider) prov;
2431 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2432 client.release();
2433
2434 Bundle bundle = createGoogleSearchSourceBundle(
2435 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2436 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2437 startSearch(result, false, bundle, false);
2438 }
2439
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002440 @Override
2441 public void startSearch(String url) {
2442 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
2443 null, false);
2444 }
2445
Michael Kolb8233fac2010-10-26 16:08:53 -07002446 private void startSearch(String initialQuery, boolean selectInitialQuery,
2447 Bundle appSearchData, boolean globalSearch) {
2448 if (appSearchData == null) {
2449 appSearchData = createGoogleSearchSourceBundle(
2450 GOOGLE_SEARCH_SOURCE_TYPE);
2451 }
2452
2453 SearchEngine searchEngine = mSettings.getSearchEngine();
2454 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2455 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2456 }
2457 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2458 globalSearch);
2459 }
2460
2461 private Bundle createGoogleSearchSourceBundle(String source) {
2462 Bundle bundle = new Bundle();
2463 bundle.putString(Search.SOURCE, source);
2464 return bundle;
2465 }
2466
2467 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002468 * helper method for key handler
2469 * returns the current tab if it can't advance
2470 */
2471 private int getNextTabIndex() {
2472 return Math.min(mTabControl.getTabCount() - 1,
2473 mTabControl.getCurrentIndex() + 1);
2474 }
2475
2476 /**
2477 * helper method for key handler
2478 * returns the current tab if it can't advance
2479 */
2480 private int getPrevTabIndex() {
2481 return Math.max(0, mTabControl.getCurrentIndex() - 1);
2482 }
2483
2484 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002485 * handle key events in browser
2486 *
2487 * @param keyCode
2488 * @param event
2489 * @return true if handled, false to pass to super
2490 */
2491 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002492 boolean noModifiers = event.hasNoModifiers();
2493
Michael Kolb8233fac2010-10-26 16:08:53 -07002494 // Even if MENU is already held down, we need to call to super to open
2495 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002496 if (!noModifiers
2497 && ((KeyEvent.KEYCODE_MENU == keyCode)
2498 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2499 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002500 mMenuIsDown = true;
2501 return false;
2502 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002503
Cary Clark8ff8c662010-12-29 15:03:05 -05002504 WebView webView = getCurrentTopWebView();
2505 if (webView == null) return false;
2506
Cary Clark160bbb92011-01-10 11:17:07 -05002507 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2508 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002509
Michael Kolb8233fac2010-10-26 16:08:53 -07002510 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002511 case KeyEvent.KEYCODE_TAB:
2512 if (event.isCtrlPressed()) {
2513 if (event.isShiftPressed()) {
2514 // prev tab
2515 switchToTab(getPrevTabIndex());
2516 } else {
2517 // next tab
2518 switchToTab(getNextTabIndex());
2519 }
2520 return true;
2521 }
2522 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002523 case KeyEvent.KEYCODE_ESCAPE:
Cary Clark160bbb92011-01-10 11:17:07 -05002524 if (!noModifiers) break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002525 stopLoading();
2526 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07002527 case KeyEvent.KEYCODE_SPACE:
2528 // WebView/WebTextView handle the keys in the KeyDown. As
2529 // the Activity's shortcut keys are only handled when WebView
2530 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002531 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002532 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002533 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002534 pageDown();
2535 }
2536 return true;
2537 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002538 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002539 event.startTracking();
2540 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002541 case KeyEvent.KEYCODE_DPAD_LEFT:
2542 if (ctrl) {
2543 webView.goBack();
2544 return true;
2545 }
2546 break;
2547 case KeyEvent.KEYCODE_DPAD_RIGHT:
2548 if (ctrl) {
2549 webView.goForward();
2550 return true;
2551 }
2552 break;
2553 case KeyEvent.KEYCODE_A:
2554 if (ctrl) {
2555 webView.selectAll();
2556 return true;
2557 }
2558 break;
Michael Kolba4183062011-01-16 10:43:21 -08002559// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002560 case KeyEvent.KEYCODE_C:
2561 if (ctrl) {
2562 webView.copySelection();
2563 return true;
2564 }
2565 break;
Michael Kolba4183062011-01-16 10:43:21 -08002566// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002567// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002568// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002569// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002570// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002571// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002572// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002573// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002574// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002575// case KeyEvent.KEYCODE_M: // unused
2576// case KeyEvent.KEYCODE_N: // in Chrome: new window
2577// case KeyEvent.KEYCODE_O: // in Chrome: open file
2578// case KeyEvent.KEYCODE_P: // in Chrome: print page
2579// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002580// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002581// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2582 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002583 // we can't use the ctrl/shift flags, they check for
2584 // exclusive use of a modifier
2585 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002586 if (event.isShiftPressed()) {
2587 openIncognitoTab();
2588 } else {
2589 openTabToHomePage();
2590 }
2591 return true;
2592 }
2593 break;
2594// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2595// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb1a2eba42011-03-16 16:42:49 -07002596 case KeyEvent.KEYCODE_W: // in Chrome: close tab
2597 if (ctrl) {
2598 closeCurrentTab();
2599 return true;
2600 }
2601 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002602// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2603// case KeyEvent.KEYCODE_Y: // unused
2604// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002605 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002606 // it is a regular key and webview is not null
2607 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002608 }
2609
John Recke6bf4ab2011-02-24 15:48:05 -08002610 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2611 switch(keyCode) {
2612 case KeyEvent.KEYCODE_BACK:
2613 if (mUi.showsWeb()) {
2614 bookmarksOrHistoryPicker(true);
2615 return true;
2616 }
2617 break;
2618 }
2619 return false;
2620 }
2621
Michael Kolb8233fac2010-10-26 16:08:53 -07002622 boolean onKeyUp(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002623 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002624 switch(keyCode) {
2625 case KeyEvent.KEYCODE_MENU:
2626 mMenuIsDown = false;
2627 break;
2628 case KeyEvent.KEYCODE_BACK:
2629 if (event.isTracking() && !event.isCanceled()) {
2630 onBackKey();
2631 return true;
2632 }
2633 break;
2634 }
2635 return false;
2636 }
2637
2638 public boolean isMenuDown() {
2639 return mMenuIsDown;
2640 }
2641
Ben Murdoch8029a772010-11-16 11:58:21 +00002642 public void setupAutoFill(Message message) {
2643 // Open the settings activity at the AutoFill profile fragment so that
2644 // the user can create a new profile. When they return, we will dispatch
2645 // the message so that we can autofill the form using their new profile.
2646 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2647 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2648 AutoFillSettingsFragment.class.getName());
2649 mAutoFillSetupMessage = message;
2650 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2651 }
John Reckb3417f02011-01-14 11:01:05 -08002652
2653 @Override
2654 public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
2655 mOptionsMenuHandler = handler;
2656 }
2657
2658 @Override
2659 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
2660 if (mOptionsMenuHandler == handler) {
2661 mOptionsMenuHandler = null;
2662 }
2663 }
2664
Narayan Kamath5119edd2011-02-23 15:49:17 +00002665 @Override
2666 public void registerDropdownChangeListener(DropdownChangeListener d) {
2667 mUi.registerDropdownChangeListener(d);
2668 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002669}