blob: 47b817cae0d57528671b5ab265a5e198ca4b17da [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
Michael Kolb8233fac2010-10-26 16:08:53 -0700164 private boolean mMenuIsDown;
165
166 // For select and find, we keep track of the ActionMode so that
167 // finish() can be called as desired.
168 private ActionMode mActionMode;
169
170 /**
171 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
172 * of whether the configuration has changed. The first onMenuOpened call
173 * after a configuration change is simply a reopening of the same menu
174 * (i.e. mIconView did not change).
175 */
176 private boolean mConfigChanged;
177
178 /**
179 * Keeps track of whether the options menu is open. This is important in
180 * determining whether to show or hide the title bar overlay
181 */
182 private boolean mOptionsMenuOpen;
183
184 /**
185 * Whether or not the options menu is in its bigger, popup menu form. When
186 * true, we want the title bar overlay to be gone. When false, we do not.
187 * Only meaningful if mOptionsMenuOpen is true.
188 */
189 private boolean mExtendedMenuOpen;
190
191 private boolean mInLoad;
192
193 private boolean mActivityPaused = true;
194 private boolean mLoadStopped;
195
196 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500197 // Checks to see when the bookmarks database has changed, and updates the
198 // Tabs' notion of whether they represent bookmarked sites.
199 private ContentObserver mBookmarksObserver;
John Reck0ebd3ac2010-12-09 11:14:04 -0800200 private DataController mDataController;
Michael Kolb8233fac2010-10-26 16:08:53 -0700201
202 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
203 @Override
204 public Void doInBackground(File... files) {
205 if (files != null) {
206 for (File f : files) {
207 if (!f.delete()) {
208 Log.e(LOGTAG, f.getPath() + " was not deleted");
209 }
210 }
211 }
212 return null;
213 }
214 }
215
216 public Controller(Activity browser) {
217 mActivity = browser;
218 mSettings = BrowserSettings.getInstance();
John Reck0ebd3ac2010-12-09 11:14:04 -0800219 mDataController = DataController.getInstance(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700220 mTabControl = new TabControl(this);
221 mSettings.setController(this);
222
223 mUrlHandler = new UrlHandler(this);
224 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700225 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
226
227 PowerManager pm = (PowerManager) mActivity
228 .getSystemService(Context.POWER_SERVICE);
229 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
230
231 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500232 mBookmarksObserver = new ContentObserver(mHandler) {
233 @Override
234 public void onChange(boolean selfChange) {
235 int size = mTabControl.getTabCount();
236 for (int i = 0; i < size; i++) {
237 mTabControl.getTab(i).updateBookmarkedStatus();
238 }
239 }
240
241 };
242 browser.getContentResolver().registerContentObserver(
243 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700244
245 mNetworkHandler = new NetworkStateHandler(mActivity, this);
246 // Start watching the default geolocation permissions
247 mSystemAllowGeolocationOrigins =
248 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
249 mSystemAllowGeolocationOrigins.start();
250
251 retainIconsOnStartup();
252 }
253
Patrick Scott7d50a932011-02-04 09:27:26 -0500254 void start(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700255 // Unless the last browser usage was within 24 hours, destroy any
256 // remaining incognito tabs.
257
258 Calendar lastActiveDate = icicle != null ?
259 (Calendar) icicle.getSerializable("lastActiveDate") : null;
260 Calendar today = Calendar.getInstance();
261 Calendar yesterday = Calendar.getInstance();
262 yesterday.add(Calendar.DATE, -1);
263
Patrick Scott7d50a932011-02-04 09:27:26 -0500264 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700265 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800266 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700267
Patrick Scott7d50a932011-02-04 09:27:26 -0500268 // Find out if we will restore any state and remember the tab.
269 final int currentTab =
270 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000271
Patrick Scott7d50a932011-02-04 09:27:26 -0500272 if (currentTab == -1) {
273 // Not able to restore so we go ahead and clear session cookies. We
274 // must do this before trying to login the user as we don't want to
275 // clear any session cookies set during login.
276 CookieManager.getInstance().removeSessionCookie();
277 }
278
Patrick Scottd43e75a2011-03-14 14:47:23 -0400279 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500280 new Runnable() {
281 @Override public void run() {
282 start(icicle, intent, currentTab, restoreIncognitoTabs);
283 }
284 });
285 }
286
287 private void start(Bundle icicle, Intent intent, int currentTab,
288 boolean restoreIncognitoTabs) {
289 if (currentTab == -1) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700290 final Bundle extra = intent.getExtras();
291 // Create an initial tab.
292 // If the intent is ACTION_VIEW and data is not null, the Browser is
293 // invoked to view the content by another application. In this case,
294 // the tab will be close when exit.
295 UrlData urlData = mIntentHandler.getUrlDataFromIntent(intent);
296
297 String action = intent.getAction();
298 final Tab t = mTabControl.createNewTab(
299 (Intent.ACTION_VIEW.equals(action) &&
300 intent.getData() != null)
301 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
302 .equals(action),
303 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
304 urlData.mUrl, false);
305 addTab(t);
306 setActiveTab(t);
307 WebView webView = t.getWebView();
308 if (extra != null) {
309 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
310 if (scale > 0 && scale <= 1000) {
311 webView.setInitialScale(scale);
312 }
313 }
314
315 if (urlData.isEmpty()) {
316 loadUrl(webView, mSettings.getHomePage());
317 } else {
Michael Kolbcd424e92011-02-24 10:26:26 -0800318 // monkey protection against delayed start
319 if (t != null) {
320 loadUrlDataIn(t, urlData);
321 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700322 }
323 } else {
Patrick Scott7d50a932011-02-04 09:27:26 -0500324 mTabControl.restoreState(icicle, currentTab, restoreIncognitoTabs,
325 mUi.needsRestoreAllTabs());
Michael Kolb1bf23132010-11-19 12:55:12 -0800326 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700327 // TabControl.restoreState() will create a new tab even if
328 // restoring the state fails.
329 setActiveTab(mTabControl.getCurrentTab());
330 }
331 // clear up the thumbnail directory, which is no longer used;
332 // ideally this should only be run once after an upgrade from
333 // a previous version of the browser
334 new ClearThumbnails().execute(mTabControl.getThumbnailDir()
335 .listFiles());
336 // Read JavaScript flags if it exists.
337 String jsFlags = getSettings().getJsFlags();
338 if (jsFlags.trim().length() != 0) {
339 getCurrentWebView().setJsFlags(jsFlags);
340 }
John Reck439c9a52010-12-14 10:04:39 -0800341 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
342 bookmarksOrHistoryPicker(false);
343 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700344 }
345
346 void setWebViewFactory(WebViewFactory factory) {
347 mFactory = factory;
348 }
349
Michael Kolb1514bb72010-11-22 09:11:48 -0800350 @Override
351 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700352 return mFactory;
353 }
354
355 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800356 public void onSetWebView(Tab tab, WebView view) {
357 mUi.onSetWebView(tab, view);
358 }
359
360 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800361 public void createSubWindow(Tab tab) {
362 endActionMode();
363 WebView mainView = tab.getWebView();
364 WebView subView = mFactory.createWebView((mainView == null)
365 ? false
366 : mainView.isPrivateBrowsingEnabled());
367 mUi.createSubWindow(tab, subView);
368 }
369
370 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700371 public Activity getActivity() {
372 return mActivity;
373 }
374
375 void setUi(UI ui) {
376 mUi = ui;
377 }
378
379 BrowserSettings getSettings() {
380 return mSettings;
381 }
382
383 IntentHandler getIntentHandler() {
384 return mIntentHandler;
385 }
386
387 @Override
388 public UI getUi() {
389 return mUi;
390 }
391
392 int getMaxTabs() {
393 return mActivity.getResources().getInteger(R.integer.max_tabs);
394 }
395
396 @Override
397 public TabControl getTabControl() {
398 return mTabControl;
399 }
400
Michael Kolb1bf23132010-11-19 12:55:12 -0800401 @Override
402 public List<Tab> getTabs() {
403 return mTabControl.getTabs();
404 }
405
Michael Kolb8233fac2010-10-26 16:08:53 -0700406 // Open the icon database and retain all the icons for visited sites.
Ben Murdoch9446b932010-11-25 16:20:14 +0000407 // This is done on a background thread so as not to stall startup.
Michael Kolb8233fac2010-10-26 16:08:53 -0700408 private void retainIconsOnStartup() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000409 // WebIconDatabase needs to be retrieved on the UI thread so that if
410 // it has not been created successfully yet the Handler is started on the
411 // UI thread.
412 new RetainIconsOnStartupTask(WebIconDatabase.getInstance()).execute();
413 }
414
415 private class RetainIconsOnStartupTask extends AsyncTask<Void, Void, Void> {
416 private WebIconDatabase mDb;
417
418 public RetainIconsOnStartupTask(WebIconDatabase db) {
419 mDb = db;
420 }
421
John Recka00cbbd2010-12-16 12:38:19 -0800422 @Override
Ben Murdoch9446b932010-11-25 16:20:14 +0000423 protected Void doInBackground(Void... unused) {
424 mDb.open(mActivity.getDir("icons", 0).getPath());
425 Cursor c = null;
426 try {
427 c = Browser.getAllBookmarks(mActivity.getContentResolver());
428 if (c.moveToFirst()) {
429 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
430 do {
431 String url = c.getString(urlIndex);
432 mDb.retainIconForPageUrl(url);
433 } while (c.moveToNext());
434 }
435 } catch (IllegalStateException e) {
436 Log.e(LOGTAG, "retainIconsOnStartup", e);
437 } finally {
438 if (c != null) c.close();
Michael Kolb8233fac2010-10-26 16:08:53 -0700439 }
Ben Murdoch9446b932010-11-25 16:20:14 +0000440
441 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700442 }
443 }
444
445 private void startHandler() {
446 mHandler = new Handler() {
447
448 @Override
449 public void handleMessage(Message msg) {
450 switch (msg.what) {
451 case OPEN_BOOKMARKS:
452 bookmarksOrHistoryPicker(false);
453 break;
454 case FOCUS_NODE_HREF:
455 {
456 String url = (String) msg.getData().get("url");
457 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500458 String src = (String) msg.getData().get("src");
459 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700460 if (TextUtils.isEmpty(url)) {
461 break;
462 }
463 HashMap focusNodeMap = (HashMap) msg.obj;
464 WebView view = (WebView) focusNodeMap.get("webview");
465 // Only apply the action if the top window did not change.
466 if (getCurrentTopWebView() != view) {
467 break;
468 }
469 switch (msg.arg1) {
470 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -0700471 loadUrlFromContext(getCurrentTopWebView(), url);
472 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500473 case R.id.view_image_context_menu_id:
474 loadUrlFromContext(getCurrentTopWebView(), src);
475 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500476 case R.id.open_newtab_context_menu_id:
477 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -0800478 final Tab newTab = openTab(parent, url, false);
Leon Scroggins026f2542010-11-22 13:26:12 -0500479 if (newTab != null && newTab != parent) {
480 parent.addChildTab(newTab);
481 }
482 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700483 case R.id.copy_link_context_menu_id:
484 copy(url);
485 break;
486 case R.id.save_link_context_menu_id:
487 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500488 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000489 mActivity, url, null, null, null,
490 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700491 break;
492 }
493 break;
494 }
495
496 case LOAD_URL:
497 loadUrlFromContext(getCurrentTopWebView(), (String) msg.obj);
498 break;
499
500 case STOP_LOAD:
501 stopLoading();
502 break;
503
504 case RELEASE_WAKELOCK:
505 if (mWakeLock.isHeld()) {
506 mWakeLock.release();
507 // if we reach here, Browser should be still in the
508 // background loading after WAKELOCK_TIMEOUT (5-min).
509 // To avoid burning the battery, stop loading.
510 mTabControl.stopAllLoading();
511 }
512 break;
513
514 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800515 Tab tab = (Tab) msg.obj;
516 if (tab != null) {
517 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700518 }
519 break;
520 }
521 }
522 };
523
524 }
525
Michael Kolbba99c5d2010-11-29 14:57:41 -0800526 @Override
527 public void shareCurrentPage() {
528 shareCurrentPage(mTabControl.getCurrentTab());
529 }
530
531 private void shareCurrentPage(Tab tab) {
532 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800533 sharePage(mActivity, tab.getTitle(),
534 tab.getUrl(), tab.getFavicon(),
535 createScreenshot(tab.getWebView(),
536 getDesiredThumbnailWidth(mActivity),
537 getDesiredThumbnailHeight(mActivity)));
538 }
539 }
540
Michael Kolb8233fac2010-10-26 16:08:53 -0700541 /**
542 * Share a page, providing the title, url, favicon, and a screenshot. Uses
543 * an {@link Intent} to launch the Activity chooser.
544 * @param c Context used to launch a new Activity.
545 * @param title Title of the page. Stored in the Intent with
546 * {@link Intent#EXTRA_SUBJECT}
547 * @param url URL of the page. Stored in the Intent with
548 * {@link Intent#EXTRA_TEXT}
549 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
550 * with {@link Browser#EXTRA_SHARE_FAVICON}
551 * @param screenshot Bitmap of a screenshot of the page. Stored in the
552 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
553 */
554 static final void sharePage(Context c, String title, String url,
555 Bitmap favicon, Bitmap screenshot) {
556 Intent send = new Intent(Intent.ACTION_SEND);
557 send.setType("text/plain");
558 send.putExtra(Intent.EXTRA_TEXT, url);
559 send.putExtra(Intent.EXTRA_SUBJECT, title);
560 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
561 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
562 try {
563 c.startActivity(Intent.createChooser(send, c.getString(
564 R.string.choosertitle_sharevia)));
565 } catch(android.content.ActivityNotFoundException ex) {
566 // if no app handles it, do nothing
567 }
568 }
569
570 private void copy(CharSequence text) {
571 ClipboardManager cm = (ClipboardManager) mActivity
572 .getSystemService(Context.CLIPBOARD_SERVICE);
573 cm.setText(text);
574 }
575
576 // lifecycle
577
578 protected void onConfgurationChanged(Configuration config) {
579 mConfigChanged = true;
580 if (mPageDialogsHandler != null) {
581 mPageDialogsHandler.onConfigurationChanged(config);
582 }
583 mUi.onConfigurationChanged(config);
584 }
585
586 @Override
587 public void handleNewIntent(Intent intent) {
588 mIntentHandler.onNewIntent(intent);
589 }
590
591 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800592 if (mUi.isCustomViewShowing()) {
593 hideCustomView();
594 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700595 if (mActivityPaused) {
596 Log.e(LOGTAG, "BrowserActivity is already paused.");
597 return;
598 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700599 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800600 Tab tab = mTabControl.getCurrentTab();
601 if (tab != null) {
602 tab.pause();
603 if (!pauseWebViewTimers(tab)) {
604 mWakeLock.acquire();
605 mHandler.sendMessageDelayed(mHandler
606 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
607 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700608 }
609 mUi.onPause();
610 mNetworkHandler.onPause();
611
612 WebView.disablePlatformNotifications();
613 }
614
615 void onSaveInstanceState(Bundle outState) {
616 // the default implementation requires each view to have an id. As the
617 // browser handles the state itself and it doesn't use id for the views,
618 // don't call the default implementation. Otherwise it will trigger the
619 // warning like this, "couldn't save which view has focus because the
620 // focused view XXX has no id".
621
622 // Save all the tabs
623 mTabControl.saveState(outState);
624 // Save time so that we know how old incognito tabs (if any) are.
625 outState.putSerializable("lastActiveDate", Calendar.getInstance());
626 }
627
628 void onResume() {
629 if (!mActivityPaused) {
630 Log.e(LOGTAG, "BrowserActivity is already resumed.");
631 return;
632 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700633 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800634 Tab current = mTabControl.getCurrentTab();
635 if (current != null) {
636 current.resume();
637 resumeWebViewTimers(current);
638 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700639 if (mWakeLock.isHeld()) {
640 mHandler.removeMessages(RELEASE_WAKELOCK);
641 mWakeLock.release();
642 }
643 mUi.onResume();
644 mNetworkHandler.onResume();
645 WebView.enablePlatformNotifications();
646 }
647
Michael Kolb70976932010-11-30 11:34:01 -0800648 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800649 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800650 * @param tab guaranteed non-null
651 */
652 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700653 boolean inLoad = tab.inPageLoad();
654 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
655 CookieSyncManager.getInstance().startSync();
656 WebView w = tab.getWebView();
657 if (w != null) {
658 w.resumeTimers();
659 }
660 }
661 }
662
Michael Kolb70976932010-11-30 11:34:01 -0800663 /**
664 * Pause all WebView timers using the WebView of the given tab
665 * @param tab
666 * @return true if the timers are paused or tab is null
667 */
668 private boolean pauseWebViewTimers(Tab tab) {
669 if (tab == null) {
670 return true;
671 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700672 CookieSyncManager.getInstance().stopSync();
673 WebView w = getCurrentWebView();
674 if (w != null) {
675 w.pauseTimers();
676 }
677 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700678 }
Michael Kolb70976932010-11-30 11:34:01 -0800679 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700680 }
681
682 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800683 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700684 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
685 mUploadHandler = null;
686 }
687 if (mTabControl == null) return;
688 mUi.onDestroy();
689 // Remove the current tab and sub window
690 Tab t = mTabControl.getCurrentTab();
691 if (t != null) {
692 dismissSubWindow(t);
693 removeTab(t);
694 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500695 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700696 // Destroy all the tabs
697 mTabControl.destroy();
698 WebIconDatabase.getInstance().close();
699 // Stop watching the default geolocation permissions
700 mSystemAllowGeolocationOrigins.stop();
701 mSystemAllowGeolocationOrigins = null;
702 }
703
704 protected boolean isActivityPaused() {
705 return mActivityPaused;
706 }
707
708 protected void onLowMemory() {
709 mTabControl.freeMemory();
710 }
711
712 @Override
713 public boolean shouldShowErrorConsole() {
714 return mShouldShowErrorConsole;
715 }
716
717 protected void setShouldShowErrorConsole(boolean show) {
718 if (show == mShouldShowErrorConsole) {
719 // Nothing to do.
720 return;
721 }
722 mShouldShowErrorConsole = show;
723 Tab t = mTabControl.getCurrentTab();
724 if (t == null) {
725 // There is no current tab so we cannot toggle the error console
726 return;
727 }
728 mUi.setShouldShowErrorConsole(t, show);
729 }
730
731 @Override
732 public void stopLoading() {
733 mLoadStopped = true;
734 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700735 WebView w = getCurrentTopWebView();
736 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700737 mUi.onPageStopped(tab);
738 }
739
740 boolean didUserStopLoading() {
741 return mLoadStopped;
742 }
743
744 // WebViewController
745
746 @Override
John Reck324d4402011-01-11 16:56:42 -0800747 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700748
749 // We've started to load a new page. If there was a pending message
750 // to save a screenshot then we will now take the new page and save
751 // an incorrect screenshot. Therefore, remove any pending thumbnail
752 // messages from the queue.
753 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800754 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700755
756 // reset sync timer to avoid sync starts during loading a page
757 CookieSyncManager.getInstance().resetSync();
758
759 if (!mNetworkHandler.isNetworkUp()) {
760 view.setNetworkAvailable(false);
761 }
762
763 // when BrowserActivity just starts, onPageStarted may be called before
764 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
765 // to start the timer. As we won't switch tabs while an activity is in
766 // pause state, we can ensure calling resume and pause in pair.
767 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800768 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700769 }
770 mLoadStopped = false;
771 if (!mNetworkHandler.isNetworkUp()) {
772 mNetworkHandler.createAndShowNetworkDialog();
773 }
774 endActionMode();
775
John Reck30c714c2010-12-16 17:30:34 -0800776 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700777
John Reck324d4402011-01-11 16:56:42 -0800778 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700779 // update the bookmark database for favicon
780 maybeUpdateFavicon(tab, null, url, favicon);
781
782 Performance.tracePageStart(url);
783
784 // Performance probe
785 if (false) {
786 Performance.onPageStarted();
787 }
788
789 }
790
791 @Override
John Reck324d4402011-01-11 16:56:42 -0800792 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800793 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800794 if (!tab.isPrivateBrowsingEnabled()
795 && !TextUtils.isEmpty(tab.getUrl())) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700796 if (tab.inForeground() && !didUserStopLoading()
797 || !tab.inForeground()) {
798 // Only update the bookmark screenshot if the user did not
799 // cancel the load early.
800 mHandler.sendMessageDelayed(mHandler.obtainMessage(
John Reck34ef2672011-02-10 11:30:55 -0800801 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
Michael Kolb8233fac2010-10-26 16:08:53 -0700802 500);
803 }
804 }
805 // pause the WebView timer and release the wake lock if it is finished
806 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800807 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700808 if (mWakeLock.isHeld()) {
809 mHandler.removeMessages(RELEASE_WAKELOCK);
810 mWakeLock.release();
811 }
812 }
813 // Performance probe
814 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800815 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700816 }
817
818 Performance.tracePageFinished();
819 }
820
821 @Override
John Reck30c714c2010-12-16 17:30:34 -0800822 public void onProgressChanged(Tab tab) {
823 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700824
825 if (newProgress == 100) {
826 CookieSyncManager.getInstance().sync();
827 // onProgressChanged() may continue to be called after the main
828 // frame has finished loading, as any remaining sub frames continue
829 // to load. We'll only get called once though with newProgress as
830 // 100 when everything is loaded. (onPageFinished is called once
831 // when the main frame completes loading regardless of the state of
832 // any sub frames so calls to onProgressChanges may continue after
833 // onPageFinished has executed)
834 if (mInLoad) {
835 mInLoad = false;
836 updateInLoadMenuItems(mCachedMenu);
837 }
838 } else {
839 if (!mInLoad) {
840 // onPageFinished may have already been called but a subframe is
841 // still loading and updating the progress. Reset mInLoad and
842 // update the menu items.
843 mInLoad = true;
844 updateInLoadMenuItems(mCachedMenu);
845 }
846 }
John Reck30c714c2010-12-16 17:30:34 -0800847 mUi.onProgressChanged(tab);
848 }
849
850 @Override
851 public void onUpdatedLockIcon(Tab tab) {
852 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700853 }
854
855 @Override
856 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800857 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800858 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800859 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700860 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
861 return;
862 }
863 // Update the title in the history database if not in private browsing mode
864 if (!tab.isPrivateBrowsingEnabled()) {
John Reck0ebd3ac2010-12-09 11:14:04 -0800865 mDataController.updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700866 }
867 }
868
869 @Override
870 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800871 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700872 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
873 }
874
875 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800876 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
877 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700878 }
879
880 @Override
881 public boolean shouldOverrideKeyEvent(KeyEvent event) {
882 if (mMenuIsDown) {
883 // only check shortcut key when MENU is held
884 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
885 event);
886 } else {
887 return false;
888 }
889 }
890
891 @Override
892 public void onUnhandledKeyEvent(KeyEvent event) {
893 if (!isActivityPaused()) {
894 if (event.getAction() == KeyEvent.ACTION_DOWN) {
895 mActivity.onKeyDown(event.getKeyCode(), event);
896 } else {
897 mActivity.onKeyUp(event.getKeyCode(), event);
898 }
899 }
900 }
901
902 @Override
John Reck324d4402011-01-11 16:56:42 -0800903 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700904 // Don't save anything in private browsing mode
905 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800906 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700907
John Reck324d4402011-01-11 16:56:42 -0800908 if (TextUtils.isEmpty(url)
909 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700910 return;
911 }
John Reck0ebd3ac2010-12-09 11:14:04 -0800912 mDataController.updateVisitedHistory(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700913 WebIconDatabase.getInstance().retainIconForPageUrl(url);
914 }
915
916 @Override
917 public void getVisitedHistory(final ValueCallback<String[]> callback) {
918 AsyncTask<Void, Void, String[]> task =
919 new AsyncTask<Void, Void, String[]>() {
920 @Override
921 public String[] doInBackground(Void... unused) {
922 return Browser.getVisitedHistory(mActivity.getContentResolver());
923 }
924 @Override
925 public void onPostExecute(String[] result) {
926 callback.onReceiveValue(result);
927 }
928 };
929 task.execute();
930 }
931
932 @Override
933 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
934 final HttpAuthHandler handler, final String host,
935 final String realm) {
936 String username = null;
937 String password = null;
938
939 boolean reuseHttpAuthUsernamePassword
940 = handler.useHttpAuthUsernamePassword();
941
942 if (reuseHttpAuthUsernamePassword && view != null) {
943 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
944 if (credentials != null && credentials.length == 2) {
945 username = credentials[0];
946 password = credentials[1];
947 }
948 }
949
950 if (username != null && password != null) {
951 handler.proceed(username, password);
952 } else {
953 if (tab.inForeground()) {
954 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
955 } else {
956 handler.cancel();
957 }
958 }
959 }
960
961 @Override
962 public void onDownloadStart(Tab tab, String url, String userAgent,
963 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000964 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -0500965 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000966 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
967 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700968 // This Tab was opened for the sole purpose of downloading a
969 // file. Remove it.
970 if (tab == mTabControl.getCurrentTab()) {
971 // In this case, the Tab is still on top.
972 goBackOnePageOrQuit();
973 } else {
974 // In this case, it is not.
975 closeTab(tab);
976 }
977 }
978 }
979
980 @Override
981 public Bitmap getDefaultVideoPoster() {
982 return mUi.getDefaultVideoPoster();
983 }
984
985 @Override
986 public View getVideoLoadingProgressView() {
987 return mUi.getVideoLoadingProgressView();
988 }
989
990 @Override
991 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
992 SslError error) {
993 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
994 }
995
Patrick Scott92066772011-03-10 08:46:27 -0500996 @Override
997 public void showAutoLogin(Tab tab) {
998 assert tab.inForeground();
999 // Update the title bar to show the auto-login request.
1000 mUi.showAutoLogin(tab);
1001 }
1002
1003 @Override
1004 public void hideAutoLogin(Tab tab) {
1005 assert tab.inForeground();
1006 mUi.hideAutoLogin(tab);
1007 }
1008
Michael Kolb8233fac2010-10-26 16:08:53 -07001009 // helper method
1010
1011 /*
1012 * Update the favorites icon if the private browsing isn't enabled and the
1013 * icon is valid.
1014 */
1015 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1016 final String url, Bitmap favicon) {
1017 if (favicon == null) {
1018 return;
1019 }
1020 if (!tab.isPrivateBrowsingEnabled()) {
1021 Bookmarks.updateFavicon(mActivity
1022 .getContentResolver(), originalUrl, url, favicon);
1023 }
1024 }
1025
Leon Scroggins4cd97792010-12-03 15:31:56 -05001026 @Override
1027 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001028 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001029 mUi.bookmarkedStatusHasChanged(tab);
1030 }
1031
Michael Kolb8233fac2010-10-26 16:08:53 -07001032 // end WebViewController
1033
1034 protected void pageUp() {
1035 getCurrentTopWebView().pageUp(false);
1036 }
1037
1038 protected void pageDown() {
1039 getCurrentTopWebView().pageDown(false);
1040 }
1041
1042 // callback from phone title bar
1043 public void editUrl() {
1044 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001045 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001046 }
1047
Michael Kolbcfa3af52010-12-14 10:36:11 -08001048 public void startVoiceSearch() {
1049 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1050 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1051 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1052 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1053 mActivity.getComponentName().flattenToString());
1054 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001055 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001056 mActivity.startActivity(intent);
1057 }
1058
Michael Kolb11d19782011-03-20 10:17:40 -07001059 @Override
1060 public void activateVoiceSearchMode(String title, List<String> results) {
1061 mUi.showVoiceTitleBar(title, results);
Michael Kolb8233fac2010-10-26 16:08:53 -07001062 }
1063
1064 public void revertVoiceSearchMode(Tab tab) {
1065 mUi.revertVoiceTitleBar(tab);
1066 }
1067
Michael Kolb736990c2011-03-20 10:01:20 -07001068 public boolean supportsVoiceSearch() {
1069 SearchEngine searchEngine = BrowserSettings.getInstance()
1070 .getSearchEngine();
1071 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1072 }
1073
Michael Kolb8233fac2010-10-26 16:08:53 -07001074 public void showCustomView(Tab tab, View view,
1075 WebChromeClient.CustomViewCallback callback) {
1076 if (tab.inForeground()) {
1077 if (mUi.isCustomViewShowing()) {
1078 callback.onCustomViewHidden();
1079 return;
1080 }
1081 mUi.showCustomView(view, callback);
1082 // Save the menu state and set it to empty while the custom
1083 // view is showing.
1084 mOldMenuState = mMenuState;
1085 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001086 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001087 }
1088 }
1089
1090 @Override
1091 public void hideCustomView() {
1092 if (mUi.isCustomViewShowing()) {
1093 mUi.onHideCustomView();
1094 // Reset the old menu state.
1095 mMenuState = mOldMenuState;
1096 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001097 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001098 }
1099 }
1100
1101 protected void onActivityResult(int requestCode, int resultCode,
1102 Intent intent) {
1103 if (getCurrentTopWebView() == null) return;
1104 switch (requestCode) {
1105 case PREFERENCES_PAGE:
1106 if (resultCode == Activity.RESULT_OK && intent != null) {
1107 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
1108 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
1109 mTabControl.removeParentChildRelationShips();
1110 }
1111 }
1112 break;
1113 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001114 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001115 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001116 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001117 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001118 case AUTOFILL_SETUP:
1119 // Determine whether a profile was actually set up or not
1120 // and if so, send the message back to the WebTextView to
1121 // fill the form with the new profile.
1122 if (getSettings().getAutoFillProfile() != null) {
1123 mAutoFillSetupMessage.sendToTarget();
1124 mAutoFillSetupMessage = null;
1125 }
1126 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001127 default:
1128 break;
1129 }
1130 getCurrentTopWebView().requestFocus();
1131 }
1132
1133 /**
1134 * Open the Go page.
1135 * @param startWithHistory If true, open starting on the history tab.
1136 * Otherwise, start with the bookmarks tab.
1137 */
1138 @Override
1139 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1140 if (mTabControl.getCurrentWebView() == null) {
1141 return;
1142 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001143 // clear action mode
1144 if (isInCustomActionMode()) {
1145 endActionMode();
1146 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001147 Bundle extras = new Bundle();
1148 // Disable opening in a new window if we have maxed out the windows
1149 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1150 !mTabControl.canCreateNewTab());
1151 mUi.showComboView(startWithHistory, extras);
1152 }
1153
1154 // combo view callbacks
1155
1156 /**
1157 * callback from ComboPage when clear history is requested
1158 */
1159 public void onRemoveParentChildRelationships() {
1160 mTabControl.removeParentChildRelationShips();
1161 }
1162
1163 /**
1164 * callback from ComboPage when bookmark/history selection
1165 */
1166 @Override
1167 public void onUrlSelected(String url, boolean newTab) {
1168 removeComboView();
1169 if (!TextUtils.isEmpty(url)) {
1170 if (newTab) {
Michael Kolb18eb3772010-12-10 14:29:51 -08001171 openTab(mTabControl.getCurrentTab(), url, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001172 } else {
1173 final Tab currentTab = mTabControl.getCurrentTab();
1174 dismissSubWindow(currentTab);
1175 loadUrl(getCurrentTopWebView(), url);
1176 }
1177 }
1178 }
1179
1180 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07001181 * dismiss the ComboPage
1182 */
1183 @Override
1184 public void removeComboView() {
1185 mUi.hideComboView();
1186 }
1187
1188 // active tabs page handling
1189
1190 protected void showActiveTabsPage() {
1191 mMenuState = EMPTY_MENU;
1192 mUi.showActiveTabsPage();
1193 }
1194
1195 /**
1196 * Remove the active tabs page.
1197 * @param needToAttach If true, the active tabs page did not attach a tab
1198 * to the content view, so we need to do that here.
1199 */
1200 @Override
1201 public void removeActiveTabsPage(boolean needToAttach) {
1202 mMenuState = R.id.MAIN_MENU;
1203 mUi.removeActiveTabsPage();
1204 if (needToAttach) {
1205 setActiveTab(mTabControl.getCurrentTab());
1206 }
1207 getCurrentTopWebView().requestFocus();
1208 }
1209
1210 // key handling
1211 protected void onBackKey() {
1212 if (!mUi.onBackKey()) {
1213 WebView subwindow = mTabControl.getCurrentSubWindow();
1214 if (subwindow != null) {
1215 if (subwindow.canGoBack()) {
1216 subwindow.goBack();
1217 } else {
1218 dismissSubWindow(mTabControl.getCurrentTab());
1219 }
1220 } else {
1221 goBackOnePageOrQuit();
1222 }
1223 }
1224 }
1225
1226 // menu handling and state
1227 // TODO: maybe put into separate handler
1228
1229 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckb3417f02011-01-14 11:01:05 -08001230 if (mOptionsMenuHandler != null) {
1231 return mOptionsMenuHandler.onCreateOptionsMenu(menu);
1232 }
1233
John Reckd73c5a22010-12-22 10:22:50 -08001234 if (mMenuState == EMPTY_MENU) {
1235 return false;
1236 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001237 MenuInflater inflater = mActivity.getMenuInflater();
1238 inflater.inflate(R.menu.browser, menu);
1239 updateInLoadMenuItems(menu);
1240 // hold on to the menu reference here; it is used by the page callbacks
1241 // to update the menu based on loading state
1242 mCachedMenu = menu;
1243 return true;
1244 }
1245
1246 protected void onCreateContextMenu(ContextMenu menu, View v,
1247 ContextMenuInfo menuInfo) {
1248 if (v instanceof TitleBarBase) {
1249 return;
1250 }
1251 if (!(v instanceof WebView)) {
1252 return;
1253 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001254 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001255 WebView.HitTestResult result = webview.getHitTestResult();
1256 if (result == null) {
1257 return;
1258 }
1259
1260 int type = result.getType();
1261 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1262 Log.w(LOGTAG,
1263 "We should not show context menu when nothing is touched");
1264 return;
1265 }
1266 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1267 // let TextView handles context menu
1268 return;
1269 }
1270
1271 // Note, http://b/issue?id=1106666 is requesting that
1272 // an inflated menu can be used again. This is not available
1273 // yet, so inflate each time (yuk!)
1274 MenuInflater inflater = mActivity.getMenuInflater();
1275 inflater.inflate(R.menu.browsercontext, menu);
1276
1277 // Show the correct menu group
1278 final String extra = result.getExtra();
1279 menu.setGroupVisible(R.id.PHONE_MENU,
1280 type == WebView.HitTestResult.PHONE_TYPE);
1281 menu.setGroupVisible(R.id.EMAIL_MENU,
1282 type == WebView.HitTestResult.EMAIL_TYPE);
1283 menu.setGroupVisible(R.id.GEO_MENU,
1284 type == WebView.HitTestResult.GEO_TYPE);
1285 menu.setGroupVisible(R.id.IMAGE_MENU,
1286 type == WebView.HitTestResult.IMAGE_TYPE
1287 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1288 menu.setGroupVisible(R.id.ANCHOR_MENU,
1289 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1290 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001291 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1292 || type == WebView.HitTestResult.PHONE_TYPE
1293 || type == WebView.HitTestResult.EMAIL_TYPE
1294 || type == WebView.HitTestResult.GEO_TYPE;
1295 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1296 if (hitText) {
1297 menu.findItem(R.id.select_text_menu_id)
1298 .setOnMenuItemClickListener(new SelectText(webview));
1299 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001300 // Setup custom handling depending on the type
1301 switch (type) {
1302 case WebView.HitTestResult.PHONE_TYPE:
1303 menu.setHeaderTitle(Uri.decode(extra));
1304 menu.findItem(R.id.dial_context_menu_id).setIntent(
1305 new Intent(Intent.ACTION_VIEW, Uri
1306 .parse(WebView.SCHEME_TEL + extra)));
1307 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1308 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1309 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1310 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1311 addIntent);
1312 menu.findItem(R.id.copy_phone_context_menu_id)
1313 .setOnMenuItemClickListener(
1314 new Copy(extra));
1315 break;
1316
1317 case WebView.HitTestResult.EMAIL_TYPE:
1318 menu.setHeaderTitle(extra);
1319 menu.findItem(R.id.email_context_menu_id).setIntent(
1320 new Intent(Intent.ACTION_VIEW, Uri
1321 .parse(WebView.SCHEME_MAILTO + extra)));
1322 menu.findItem(R.id.copy_mail_context_menu_id)
1323 .setOnMenuItemClickListener(
1324 new Copy(extra));
1325 break;
1326
1327 case WebView.HitTestResult.GEO_TYPE:
1328 menu.setHeaderTitle(extra);
1329 menu.findItem(R.id.map_context_menu_id).setIntent(
1330 new Intent(Intent.ACTION_VIEW, Uri
1331 .parse(WebView.SCHEME_GEO
1332 + URLEncoder.encode(extra))));
1333 menu.findItem(R.id.copy_geo_context_menu_id)
1334 .setOnMenuItemClickListener(
1335 new Copy(extra));
1336 break;
1337
1338 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1339 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001340 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001341 // decide whether to show the open link in new tab option
1342 boolean showNewTab = mTabControl.canCreateNewTab();
1343 MenuItem newTabItem
1344 = menu.findItem(R.id.open_newtab_context_menu_id);
Michael Kolb2dd65c82011-01-14 11:07:38 -08001345 newTabItem.setTitle(
1346 BrowserSettings.getInstance().openInBackground()
1347 ? R.string.contextmenu_openlink_newwindow_background
1348 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001349 newTabItem.setVisible(showNewTab);
1350 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001351 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1352 newTabItem.setOnMenuItemClickListener(
1353 new MenuItem.OnMenuItemClickListener() {
1354 @Override
1355 public boolean onMenuItemClick(MenuItem item) {
1356 final HashMap<String, WebView> hrefMap =
1357 new HashMap<String, WebView>();
1358 hrefMap.put("webview", webview);
1359 final Message msg = mHandler.obtainMessage(
1360 FOCUS_NODE_HREF,
1361 R.id.open_newtab_context_menu_id,
1362 0, hrefMap);
1363 webview.requestFocusNodeHref(msg);
1364 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001365 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001366 });
1367 } else {
1368 newTabItem.setOnMenuItemClickListener(
1369 new MenuItem.OnMenuItemClickListener() {
1370 @Override
1371 public boolean onMenuItemClick(MenuItem item) {
1372 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -08001373 final Tab newTab = openTab(parent,
1374 extra, false);
Leon Scroggins026f2542010-11-22 13:26:12 -05001375 if (newTab != parent) {
1376 parent.addChildTab(newTab);
1377 }
1378 return true;
1379 }
1380 });
1381 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001382 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001383 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1384 break;
1385 }
1386 // otherwise fall through to handle image part
1387 case WebView.HitTestResult.IMAGE_TYPE:
1388 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1389 menu.setHeaderTitle(extra);
1390 }
1391 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1392 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1393 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001394 setOnMenuItemClickListener(
1395 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001396 menu.findItem(R.id.set_wallpaper_context_menu_id).
1397 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1398 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001399 break;
1400
1401 default:
1402 Log.w(LOGTAG, "We should not get here.");
1403 break;
1404 }
1405 //update the ui
1406 mUi.onContextMenuCreated(menu);
1407 }
1408
1409 /**
1410 * As the menu can be open when loading state changes
1411 * we must manually update the state of the stop/reload menu
1412 * item
1413 */
1414 private void updateInLoadMenuItems(Menu menu) {
1415 if (menu == null) {
1416 return;
1417 }
1418 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1419 MenuItem src = mInLoad ?
1420 menu.findItem(R.id.stop_menu_id):
1421 menu.findItem(R.id.reload_menu_id);
1422 if (src != null) {
1423 dest.setIcon(src.getIcon());
1424 dest.setTitle(src.getTitle());
1425 }
1426 }
1427
John Reckb3417f02011-01-14 11:01:05 -08001428 boolean onPrepareOptionsMenu(Menu menu) {
1429 if (mOptionsMenuHandler != null) {
1430 return mOptionsMenuHandler.onPrepareOptionsMenu(menu);
1431 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001432 // Note: setVisible will decide whether an item is visible; while
1433 // setEnabled() will decide whether an item is enabled, which also means
1434 // whether the matching shortcut key will function.
1435 switch (mMenuState) {
1436 case EMPTY_MENU:
1437 if (mCurrentMenuState != mMenuState) {
1438 menu.setGroupVisible(R.id.MAIN_MENU, false);
1439 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1440 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1441 }
1442 break;
1443 default:
1444 if (mCurrentMenuState != mMenuState) {
1445 menu.setGroupVisible(R.id.MAIN_MENU, true);
1446 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1447 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1448 }
1449 final WebView w = getCurrentTopWebView();
1450 boolean canGoBack = false;
1451 boolean canGoForward = false;
1452 boolean isHome = false;
1453 if (w != null) {
1454 canGoBack = w.canGoBack();
1455 canGoForward = w.canGoForward();
1456 isHome = mSettings.getHomePage().equals(w.getUrl());
1457 }
1458 final MenuItem back = menu.findItem(R.id.back_menu_id);
1459 back.setEnabled(canGoBack);
1460
1461 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1462 home.setEnabled(!isHome);
1463
1464 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1465 forward.setEnabled(canGoForward);
1466
1467 // decide whether to show the share link option
1468 PackageManager pm = mActivity.getPackageManager();
1469 Intent send = new Intent(Intent.ACTION_SEND);
1470 send.setType("text/plain");
1471 ResolveInfo ri = pm.resolveActivity(send,
1472 PackageManager.MATCH_DEFAULT_ONLY);
1473 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1474
1475 boolean isNavDump = mSettings.isNavDump();
1476 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1477 nav.setVisible(isNavDump);
1478 nav.setEnabled(isNavDump);
1479
1480 boolean showDebugSettings = mSettings.showDebugSettings();
1481 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1482 counter.setVisible(showDebugSettings);
1483 counter.setEnabled(showDebugSettings);
1484
John Reckb3417f02011-01-14 11:01:05 -08001485 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1486 newtab.setEnabled(getTabControl().canCreateNewTab());
Michael Kolb8233fac2010-10-26 16:08:53 -07001487
Leon Scroggins81983762011-02-11 15:17:36 -05001488 MenuItem archive = menu.findItem(R.id.save_webarchive_menu_id);
John Reck51d8bad2011-02-28 15:47:47 -08001489 Tab tab = getTabControl().getCurrentTab();
1490 String url = tab != null ? tab.getUrl() : null;
1491 archive.setVisible(!TextUtils.isEmpty(url)
1492 && !url.endsWith(".webarchivexml"));
Michael Kolb8233fac2010-10-26 16:08:53 -07001493 break;
1494 }
1495 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001496 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001497 }
1498
1499 public boolean onOptionsItemSelected(MenuItem item) {
John Reckb3417f02011-01-14 11:01:05 -08001500 if (mOptionsMenuHandler != null &&
1501 mOptionsMenuHandler.onOptionsItemSelected(item)) {
1502 return true;
1503 }
1504
Michael Kolb8233fac2010-10-26 16:08:53 -07001505 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1506 // menu remains active, so ensure comboview is dismissed
1507 // if main menu option is selected
1508 removeComboView();
1509 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001510 if (null == getCurrentTopWebView()) {
1511 return false;
1512 }
1513 if (mMenuIsDown) {
1514 // The shortcut action consumes the MENU. Even if it is still down,
1515 // it won't trigger the next shortcut action. In the case of the
1516 // shortcut action triggering a new activity, like Bookmarks, we
1517 // won't get onKeyUp for MENU. So it is important to reset it here.
1518 mMenuIsDown = false;
1519 }
1520 switch (item.getItemId()) {
1521 // -- Main menu
1522 case R.id.new_tab_menu_id:
1523 openTabToHomePage();
1524 break;
1525
1526 case R.id.incognito_menu_id:
1527 openIncognitoTab();
1528 break;
1529
1530 case R.id.goto_menu_id:
1531 editUrl();
1532 break;
1533
1534 case R.id.bookmarks_menu_id:
1535 bookmarksOrHistoryPicker(false);
1536 break;
1537
1538 case R.id.active_tabs_menu_id:
1539 showActiveTabsPage();
1540 break;
1541
1542 case R.id.add_bookmark_menu_id:
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001543 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001544 break;
1545
1546 case R.id.stop_reload_menu_id:
1547 if (mInLoad) {
1548 stopLoading();
1549 } else {
1550 getCurrentTopWebView().reload();
1551 }
1552 break;
1553
1554 case R.id.back_menu_id:
1555 getCurrentTopWebView().goBack();
1556 break;
1557
1558 case R.id.forward_menu_id:
1559 getCurrentTopWebView().goForward();
1560 break;
1561
1562 case R.id.close_menu_id:
1563 // Close the subwindow if it exists.
1564 if (mTabControl.getCurrentSubWindow() != null) {
1565 dismissSubWindow(mTabControl.getCurrentTab());
1566 break;
1567 }
1568 closeCurrentTab();
1569 break;
1570
1571 case R.id.homepage_menu_id:
1572 Tab current = mTabControl.getCurrentTab();
1573 if (current != null) {
1574 dismissSubWindow(current);
1575 loadUrl(current.getWebView(), mSettings.getHomePage());
1576 }
1577 break;
1578
1579 case R.id.preferences_menu_id:
1580 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1581 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1582 getCurrentTopWebView().getUrl());
1583 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1584 break;
1585
1586 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001587 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001588 break;
1589
Leon Scrogginsac993842011-02-02 12:54:07 -05001590 case R.id.save_webarchive_menu_id:
1591 String state = Environment.getExternalStorageState();
1592 if (!Environment.MEDIA_MOUNTED.equals(state)) {
1593 Log.e(LOGTAG, "External storage not mounted");
1594 Toast.makeText(mActivity, R.string.webarchive_failed,
1595 Toast.LENGTH_SHORT).show();
1596 break;
1597 }
1598 final String directory = Environment.getExternalStoragePublicDirectory(
1599 Environment.DIRECTORY_DOWNLOADS) + File.separator;
1600 File dir = new File(directory);
1601 if (!dir.exists() && !dir.mkdirs()) {
1602 Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
1603 Toast.makeText(mActivity, R.string.webarchive_failed,
1604 Toast.LENGTH_SHORT).show();
1605 break;
1606 }
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001607 final WebView topWebView = getCurrentTopWebView();
Leon Scrogginsac993842011-02-02 12:54:07 -05001608 final String title = topWebView.getTitle();
John Reck51d8bad2011-02-28 15:47:47 -08001609 final String url = topWebView.getUrl();
Leon Scrogginsac993842011-02-02 12:54:07 -05001610 topWebView.saveWebArchive(directory, true,
1611 new ValueCallback<String>() {
1612 @Override
1613 public void onReceiveValue(final String value) {
1614 if (value != null) {
1615 File file = new File(value);
1616 final long length = file.length();
1617 if (file.exists() && length > 0) {
Leon Scroggins1cb96552011-02-11 14:22:57 -05001618 Toast.makeText(mActivity, R.string.webarchive_saved,
1619 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001620 final DownloadManager manager = (DownloadManager) mActivity
1621 .getSystemService(Context.DOWNLOAD_SERVICE);
1622 new Thread("Add WebArchive to download manager") {
1623 @Override
1624 public void run() {
Vasu Noria9e30a72011-03-07 11:37:34 -08001625 manager.addCompletedDownload(
1626 null == title ? value : title,
Leon Scrogginsac993842011-02-02 12:54:07 -05001627 value, true, "application/x-webarchive-xml",
1628 value, length, true);
1629 }
1630 }.start();
1631 return;
1632 }
1633 }
John Reck51d8bad2011-02-28 15:47:47 -08001634 DownloadHandler.onDownloadStartNoStream(mActivity,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001635 url, null, null, null, topWebView.isPrivateBrowsingEnabled());
Leon Scrogginsac993842011-02-02 12:54:07 -05001636 }
1637 });
1638 break;
1639
Michael Kolb8233fac2010-10-26 16:08:53 -07001640 case R.id.page_info_menu_id:
1641 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1642 false);
1643 break;
1644
1645 case R.id.classic_history_menu_id:
1646 bookmarksOrHistoryPicker(true);
1647 break;
1648
1649 case R.id.title_bar_share_page_url:
1650 case R.id.share_page_menu_id:
1651 Tab currentTab = mTabControl.getCurrentTab();
1652 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001653 return false;
1654 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001655 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001656 break;
1657
1658 case R.id.dump_nav_menu_id:
1659 getCurrentTopWebView().debugDump();
1660 break;
1661
1662 case R.id.dump_counters_menu_id:
1663 getCurrentTopWebView().dumpV8Counters();
1664 break;
1665
1666 case R.id.zoom_in_menu_id:
1667 getCurrentTopWebView().zoomIn();
1668 break;
1669
1670 case R.id.zoom_out_menu_id:
1671 getCurrentTopWebView().zoomOut();
1672 break;
1673
1674 case R.id.view_downloads_menu_id:
1675 viewDownloads();
1676 break;
1677
1678 case R.id.window_one_menu_id:
1679 case R.id.window_two_menu_id:
1680 case R.id.window_three_menu_id:
1681 case R.id.window_four_menu_id:
1682 case R.id.window_five_menu_id:
1683 case R.id.window_six_menu_id:
1684 case R.id.window_seven_menu_id:
1685 case R.id.window_eight_menu_id:
1686 {
1687 int menuid = item.getItemId();
1688 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1689 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1690 Tab desiredTab = mTabControl.getTab(id);
1691 if (desiredTab != null &&
1692 desiredTab != mTabControl.getCurrentTab()) {
1693 switchToTab(id);
1694 }
1695 break;
1696 }
1697 }
1698 }
1699 break;
1700
1701 default:
1702 return false;
1703 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001704 return true;
1705 }
1706
1707 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001708 // Let the History and Bookmark fragments handle menus they created.
1709 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1710 return false;
1711 }
1712
Michael Kolb8233fac2010-10-26 16:08:53 -07001713 int id = item.getItemId();
1714 boolean result = true;
1715 switch (id) {
1716 // For the context menu from the title bar
1717 case R.id.title_bar_copy_page_url:
1718 Tab currentTab = mTabControl.getCurrentTab();
1719 if (null == currentTab) {
1720 result = false;
1721 break;
1722 }
1723 WebView mainView = currentTab.getWebView();
1724 if (null == mainView) {
1725 result = false;
1726 break;
1727 }
1728 copy(mainView.getUrl());
1729 break;
1730 // -- Browser context menu
1731 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001732 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001733 case R.id.copy_link_context_menu_id:
1734 final WebView webView = getCurrentTopWebView();
1735 if (null == webView) {
1736 result = false;
1737 break;
1738 }
1739 final HashMap<String, WebView> hrefMap =
1740 new HashMap<String, WebView>();
1741 hrefMap.put("webview", webView);
1742 final Message msg = mHandler.obtainMessage(
1743 FOCUS_NODE_HREF, id, 0, hrefMap);
1744 webView.requestFocusNodeHref(msg);
1745 break;
1746
1747 default:
1748 // For other context menus
1749 result = onOptionsItemSelected(item);
1750 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001751 return result;
1752 }
1753
1754 /**
1755 * support programmatically opening the context menu
1756 */
1757 public void openContextMenu(View view) {
1758 mActivity.openContextMenu(view);
1759 }
1760
1761 /**
1762 * programmatically open the options menu
1763 */
1764 public void openOptionsMenu() {
1765 mActivity.openOptionsMenu();
1766 }
1767
1768 public boolean onMenuOpened(int featureId, Menu menu) {
1769 if (mOptionsMenuOpen) {
1770 if (mConfigChanged) {
1771 // We do not need to make any changes to the state of the
1772 // title bar, since the only thing that happened was a
1773 // change in orientation
1774 mConfigChanged = false;
1775 } else {
1776 if (!mExtendedMenuOpen) {
1777 mExtendedMenuOpen = true;
1778 mUi.onExtendedMenuOpened();
1779 } else {
1780 // Switching the menu back to icon view, so show the
1781 // title bar once again.
1782 mExtendedMenuOpen = false;
1783 mUi.onExtendedMenuClosed(mInLoad);
Michael Kolb8233fac2010-10-26 16:08:53 -07001784 }
1785 }
1786 } else {
1787 // The options menu is closed, so open it, and show the title
1788 mOptionsMenuOpen = true;
1789 mConfigChanged = false;
1790 mExtendedMenuOpen = false;
1791 mUi.onOptionsMenuOpened();
1792 }
1793 return true;
1794 }
1795
1796 public void onOptionsMenuClosed(Menu menu) {
1797 mOptionsMenuOpen = false;
1798 mUi.onOptionsMenuClosed(mInLoad);
1799 }
1800
1801 public void onContextMenuClosed(Menu menu) {
1802 mUi.onContextMenuClosed(menu, mInLoad);
1803 }
1804
1805 // Helper method for getting the top window.
1806 @Override
1807 public WebView getCurrentTopWebView() {
1808 return mTabControl.getCurrentTopWebView();
1809 }
1810
1811 @Override
1812 public WebView getCurrentWebView() {
1813 return mTabControl.getCurrentWebView();
1814 }
1815
1816 /*
1817 * This method is called as a result of the user selecting the options
1818 * menu to see the download window. It shows the download window on top of
1819 * the current window.
1820 */
1821 void viewDownloads() {
1822 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1823 mActivity.startActivity(intent);
1824 }
1825
1826 // action mode
1827
1828 void onActionModeStarted(ActionMode mode) {
1829 mUi.onActionModeStarted(mode);
1830 mActionMode = mode;
1831 }
1832
1833 /*
1834 * True if a custom ActionMode (i.e. find or select) is in use.
1835 */
1836 @Override
1837 public boolean isInCustomActionMode() {
1838 return mActionMode != null;
1839 }
1840
1841 /*
1842 * End the current ActionMode.
1843 */
1844 @Override
1845 public void endActionMode() {
1846 if (mActionMode != null) {
1847 mActionMode.finish();
1848 }
1849 }
1850
1851 /*
1852 * Called by find and select when they are finished. Replace title bars
1853 * as necessary.
1854 */
1855 public void onActionModeFinished(ActionMode mode) {
1856 if (!isInCustomActionMode()) return;
1857 mUi.onActionModeFinished(mInLoad);
1858 mActionMode = null;
1859 }
1860
1861 boolean isInLoad() {
1862 return mInLoad;
1863 }
1864
1865 // bookmark handling
1866
1867 /**
1868 * add the current page as a bookmark to the given folder id
1869 * @param folderId use -1 for the default folder
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001870 * @param canBeAnEdit If true, check to see whether the site is already
1871 * bookmarked, and if it is, edit that bookmark. If false, and
1872 * the site is already bookmarked, do not attempt to edit the
1873 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001874 */
1875 @Override
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001876 public void bookmarkCurrentPage(long folderId, boolean canBeAnEdit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001877 Intent i = new Intent(mActivity,
1878 AddBookmarkPage.class);
1879 WebView w = getCurrentTopWebView();
1880 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1881 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1882 String touchIconUrl = w.getTouchIconUrl();
1883 if (touchIconUrl != null) {
1884 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1885 WebSettings settings = w.getSettings();
1886 if (settings != null) {
1887 i.putExtra(AddBookmarkPage.USER_AGENT,
1888 settings.getUserAgentString());
1889 }
1890 }
1891 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1892 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1893 getDesiredThumbnailHeight(mActivity)));
1894 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1895 i.putExtra(BrowserContract.Bookmarks.PARENT,
1896 folderId);
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001897 if (canBeAnEdit) {
1898 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1899 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001900 // Put the dialog at the upper right of the screen, covering the
1901 // star on the title bar.
1902 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1903 mActivity.startActivity(i);
1904 }
1905
1906 // file chooser
1907 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1908 mUploadHandler = new UploadHandler(this);
1909 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1910 }
1911
1912 // thumbnails
1913
1914 /**
1915 * Return the desired width for thumbnail screenshots, which are stored in
1916 * the database, and used on the bookmarks screen.
1917 * @param context Context for finding out the density of the screen.
1918 * @return desired width for thumbnail screenshot.
1919 */
1920 static int getDesiredThumbnailWidth(Context context) {
1921 return context.getResources().getDimensionPixelOffset(
1922 R.dimen.bookmarkThumbnailWidth);
1923 }
1924
1925 /**
1926 * Return the desired height for thumbnail screenshots, which are stored in
1927 * the database, and used on the bookmarks screen.
1928 * @param context Context for finding out the density of the screen.
1929 * @return desired height for thumbnail screenshot.
1930 */
1931 static int getDesiredThumbnailHeight(Context context) {
1932 return context.getResources().getDimensionPixelOffset(
1933 R.dimen.bookmarkThumbnailHeight);
1934 }
1935
Michael Kolb1acef692011-03-08 14:12:06 -08001936 static Bitmap createScreenshot(Tab tab, int width, int height) {
1937 if ((tab != null) && (tab.getWebView() != null)) {
1938 return createScreenshot(tab.getWebView(), width, height);
1939 }
1940 return null;
1941 }
1942
Michael Kolb8233fac2010-10-26 16:08:53 -07001943 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001944 // We render to a bitmap 2x the desired size so that we can then
1945 // re-scale it with filtering since canvas.scale doesn't filter
1946 // This helps reduce aliasing at the cost of being slightly blurry
1947 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001948 Picture thumbnail = view.capturePicture();
1949 if (thumbnail == null) {
1950 return null;
1951 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001952 width *= filter_scale;
1953 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001954 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1955 Canvas canvas = new Canvas(bm);
1956 // May need to tweak these values to determine what is the
1957 // best scale factor
1958 int thumbnailWidth = thumbnail.getWidth();
1959 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001960 float scaleFactor = 1.0f;
Michael Kolbeb95db42011-03-03 10:38:40 -08001961 if (thumbnailWidth > 0 && thumbnailHeight > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001962 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001963 } else {
1964 return null;
1965 }
John Reckfe49ab42010-11-16 17:09:37 -08001966
Michael Kolbeb95db42011-03-03 10:38:40 -08001967 float scaleFactorY = (float) height / (float)thumbnailHeight;
1968 if (scaleFactorY > scaleFactor) {
1969 // The picture is narrower than the requested AR
1970 // Center the thumnail and crop the sides
1971 scaleFactor = scaleFactorY;
John Reckfe49ab42010-11-16 17:09:37 -08001972 float wx = (thumbnailWidth * scaleFactor) - width;
1973 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001974 }
1975
John Reckfe49ab42010-11-16 17:09:37 -08001976 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001977
1978 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001979 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
1980 height / filter_scale, true);
1981 bm.recycle();
1982 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001983 }
1984
John Reck34ef2672011-02-10 11:30:55 -08001985 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001986 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07001987 // FIXME: Would like to make sure there is actually something to
1988 // draw, but the API for that (WebViewCore.pictureReady()) is not
1989 // currently accessible here.
1990
John Reck34ef2672011-02-10 11:30:55 -08001991 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08001992 if (view == null) {
1993 // Tab was destroyed
1994 return;
1995 }
John Reck34ef2672011-02-10 11:30:55 -08001996 final String url = tab.getUrl();
1997 final String originalUrl = view.getOriginalUrl();
1998
1999 if (TextUtils.isEmpty(url)) {
2000 return;
2001 }
2002
2003 // Only update thumbnails for web urls (http(s)://), not for
2004 // about:, javascript:, data:, etc...
2005 // Unless it is a bookmarked site, then always update
2006 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2007 return;
2008 }
2009
Michael Kolb8233fac2010-10-26 16:08:53 -07002010 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2011 getDesiredThumbnailHeight(mActivity));
2012 if (bm == null) {
2013 return;
2014 }
2015
2016 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002017 new AsyncTask<Void, Void, Void>() {
2018 @Override
2019 protected Void doInBackground(Void... unused) {
2020 Cursor cursor = null;
2021 try {
2022 // TODO: Clean this up
2023 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2024 if (cursor != null && cursor.moveToFirst()) {
2025 final ByteArrayOutputStream os =
2026 new ByteArrayOutputStream();
2027 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002028
John Reck34ef2672011-02-10 11:30:55 -08002029 ContentValues values = new ContentValues();
2030 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002031
John Reck34ef2672011-02-10 11:30:55 -08002032 do {
John Reck617fd832011-02-16 14:35:59 -08002033 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002034 cr.update(Images.CONTENT_URI, values, null, null);
2035 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002036 }
John Reck34ef2672011-02-10 11:30:55 -08002037 } catch (IllegalStateException e) {
2038 // Ignore
2039 } finally {
2040 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002041 }
John Reck34ef2672011-02-10 11:30:55 -08002042 return null;
2043 }
2044 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002045 }
2046
2047 private class Copy implements OnMenuItemClickListener {
2048 private CharSequence mText;
2049
2050 public boolean onMenuItemClick(MenuItem item) {
2051 copy(mText);
2052 return true;
2053 }
2054
2055 public Copy(CharSequence toCopy) {
2056 mText = toCopy;
2057 }
2058 }
2059
Leon Scroggins63c02662010-11-18 15:16:27 -05002060 private static class Download implements OnMenuItemClickListener {
2061 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002062 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002063 private boolean mPrivateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002064
2065 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002066 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002067 null, null, mPrivateBrowsing);
Michael Kolb8233fac2010-10-26 16:08:53 -07002068 return true;
2069 }
2070
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002071 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002072 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002073 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002074 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002075 }
2076 }
2077
Cary Clark8974d282010-11-22 10:46:05 -05002078 private static class SelectText implements OnMenuItemClickListener {
2079 private WebView mWebView;
2080
2081 public boolean onMenuItemClick(MenuItem item) {
2082 if (mWebView != null) {
2083 return mWebView.selectText();
2084 }
2085 return false;
2086 }
2087
2088 public SelectText(WebView webView) {
2089 mWebView = webView;
2090 }
2091
2092 }
2093
Michael Kolb8233fac2010-10-26 16:08:53 -07002094 /********************** TODO: UI stuff *****************************/
2095
2096 // these methods have been copied, they still need to be cleaned up
2097
2098 /****************** tabs ***************************************************/
2099
2100 // basic tab interactions:
2101
2102 // it is assumed that tabcontrol already knows about the tab
2103 protected void addTab(Tab tab) {
2104 mUi.addTab(tab);
2105 }
2106
2107 protected void removeTab(Tab tab) {
2108 mUi.removeTab(tab);
2109 mTabControl.removeTab(tab);
2110 }
2111
2112 protected void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002113 // monkey protection against delayed start
2114 if (tab != null) {
2115 mTabControl.setCurrentTab(tab);
2116 // the tab is guaranteed to have a webview after setCurrentTab
2117 mUi.setActiveTab(tab);
2118 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002119 }
2120
2121 protected void closeEmptyChildTab() {
2122 Tab current = mTabControl.getCurrentTab();
2123 if (current != null
2124 && current.getWebView().copyBackForwardList().getSize() == 0) {
2125 Tab parent = current.getParentTab();
2126 if (parent != null) {
2127 switchToTab(mTabControl.getTabIndex(parent));
2128 closeTab(current);
2129 }
2130 }
2131 }
2132
2133 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002134 // Dismiss the subwindow if applicable.
2135 dismissSubWindow(appTab);
2136 // Since we might kill the WebView, remove it from the
2137 // content view first.
2138 mUi.detachTab(appTab);
2139 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002140 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002141 // TODO: analyze why the remove and add are necessary
2142 mUi.attachTab(appTab);
2143 if (mTabControl.getCurrentTab() != appTab) {
2144 switchToTab(mTabControl.getTabIndex(appTab));
John Reck30c714c2010-12-16 17:30:34 -08002145 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002146 } else {
2147 // If the tab was the current tab, we have to attach
2148 // it to the view system again.
2149 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002150 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002151 }
2152 }
2153
2154 // Remove the sub window if it exists. Also called by TabControl when the
2155 // user clicks the 'X' to dismiss a sub window.
2156 public void dismissSubWindow(Tab tab) {
2157 removeSubWindow(tab);
2158 // dismiss the subwindow. This will destroy the WebView.
2159 tab.dismissSubWindow();
2160 getCurrentTopWebView().requestFocus();
2161 }
2162
2163 @Override
2164 public void removeSubWindow(Tab t) {
2165 if (t.getSubWebView() != null) {
2166 mUi.removeSubWindow(t.getSubViewContainer());
2167 }
2168 }
2169
2170 @Override
2171 public void attachSubWindow(Tab tab) {
2172 if (tab.getSubWebView() != null) {
2173 mUi.attachSubWindow(tab.getSubViewContainer());
2174 getCurrentTopWebView().requestFocus();
2175 }
2176 }
2177
Michael Kolb843510f2010-12-09 10:51:49 -08002178 @Override
2179 public Tab openTabToHomePage() {
2180 // check for max tabs
2181 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002182 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2183 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002184 } else {
2185 mUi.showMaxTabsWarning();
2186 return null;
2187 }
2188 }
2189
Michael Kolb18eb3772010-12-10 14:29:51 -08002190 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2191 if (mSettings.openInBackground() && !forceForeground) {
2192 Tab tab = mTabControl.createNewTab(false, null, null,
2193 (parent != null) && parent.isPrivateBrowsingEnabled());
2194 if (tab != null) {
2195 addTab(tab);
2196 WebView view = tab.getWebView();
2197 loadUrl(view, url);
2198 }
2199 return tab;
2200 } else {
2201 return openTabAndShow(parent, new UrlData(url), false, null);
2202 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002203 }
2204
Michael Kolb18eb3772010-12-10 14:29:51 -08002205
Michael Kolb8233fac2010-10-26 16:08:53 -07002206 // This method does a ton of stuff. It will attempt to create a new tab
2207 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2208 // url isn't null, it will load the given url.
Patrick Scottcd135082011-01-31 18:21:58 -05002209 public Tab openTabAndShow(Tab parent, final UrlData urlData,
2210 boolean closeOnExit, String appId) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002211 final Tab currentTab = mTabControl.getCurrentTab();
2212 if (mTabControl.canCreateNewTab()) {
2213 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Michael Kolb18eb3772010-12-10 14:29:51 -08002214 urlData.mUrl,
2215 (parent != null) && parent.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -07002216 WebView webview = tab.getWebView();
2217 // We must set the new tab as the current tab to reflect the old
2218 // animation behavior.
2219 addTab(tab);
2220 setActiveTab(tab);
Patrick Scottd43e75a2011-03-14 14:47:23 -04002221 if (!urlData.isEmpty()) {
2222 loadUrlDataIn(tab, urlData);
2223 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002224 return tab;
2225 } else {
2226 // Get rid of the subwindow if it exists
2227 dismissSubWindow(currentTab);
2228 if (!urlData.isEmpty()) {
2229 // Load the given url.
2230 loadUrlDataIn(currentTab, urlData);
2231 }
2232 return currentTab;
2233 }
2234 }
2235
Michael Kolb8233fac2010-10-26 16:08:53 -07002236 @Override
2237 public Tab openIncognitoTab() {
2238 if (mTabControl.canCreateNewTab()) {
2239 Tab currentTab = mTabControl.getCurrentTab();
Michael Kolb8e7178d2011-01-26 19:13:36 -08002240 Tab tab = mTabControl.createNewTab(false, null,
John Reck4bfc0db2011-01-27 17:47:12 -08002241 null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07002242 addTab(tab);
2243 setActiveTab(tab);
John Reck4bfc0db2011-01-27 17:47:12 -08002244 loadUrlDataIn(tab, new UrlData("browser:incognito"));
Michael Kolb8233fac2010-10-26 16:08:53 -07002245 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002246 } else {
2247 mUi.showMaxTabsWarning();
2248 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002249 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002250 }
2251
2252 /**
2253 * @param index Index of the tab to change to, as defined by
2254 * mTabControl.getTabIndex(Tab t).
2255 * @return boolean True if we successfully switched to a different tab. If
2256 * the indexth tab is null, or if that tab is the same as
2257 * the current one, return false.
2258 */
2259 @Override
2260 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002261 // hide combo view if open
2262 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002263 Tab tab = mTabControl.getTab(index);
2264 Tab currentTab = mTabControl.getCurrentTab();
2265 if (tab == null || tab == currentTab) {
2266 return false;
2267 }
2268 setActiveTab(tab);
2269 return true;
2270 }
2271
2272 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002273 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002274 // hide combo view if open
2275 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002276 final Tab current = mTabControl.getCurrentTab();
2277 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002278 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002279 return;
2280 }
2281 final Tab parent = current.getParentTab();
2282 int indexToShow = -1;
2283 if (parent != null) {
2284 indexToShow = mTabControl.getTabIndex(parent);
2285 } else {
2286 final int currentIndex = mTabControl.getCurrentIndex();
2287 // Try to move to the tab to the right
2288 indexToShow = currentIndex + 1;
2289 if (indexToShow > mTabControl.getTabCount() - 1) {
2290 // Try to move to the tab to the left
2291 indexToShow = currentIndex - 1;
2292 }
2293 }
2294 if (switchToTab(indexToShow)) {
2295 // Close window
2296 closeTab(current);
2297 }
2298 }
2299
2300 /**
2301 * Close the tab, remove its associated title bar, and adjust mTabControl's
2302 * current tab to a valid value.
2303 */
2304 @Override
2305 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002306 // hide combo view if open
2307 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002308 int currentIndex = mTabControl.getCurrentIndex();
2309 int removeIndex = mTabControl.getTabIndex(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002310 Tab newtab = mTabControl.getTab(currentIndex);
2311 setActiveTab(newtab);
Michael Kolb2d59c322011-01-25 13:18:55 -08002312 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002313 }
2314
2315 /**************** TODO: Url loading clean up *******************************/
2316
2317 // Called when loading from context menu or LOAD_URL message
2318 protected void loadUrlFromContext(WebView view, String url) {
2319 // In case the user enters nothing.
2320 if (url != null && url.length() != 0 && view != null) {
2321 url = UrlUtils.smartUrlFilter(url);
2322 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2323 loadUrl(view, url);
2324 }
2325 }
2326 }
2327
2328 /**
2329 * Load the URL into the given WebView and update the title bar
2330 * to reflect the new load. Call this instead of WebView.loadUrl
2331 * directly.
2332 * @param view The WebView used to load url.
2333 * @param url The URL to load.
2334 */
2335 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002336 view.loadUrl(url);
2337 }
2338
2339 /**
2340 * Load UrlData into a Tab and update the title bar to reflect the new
2341 * load. Call this instead of UrlData.loadIn directly.
2342 * @param t The Tab used to load.
2343 * @param data The UrlData being loaded.
2344 */
2345 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002346 data.loadIn(t);
2347 }
2348
John Reck30c714c2010-12-16 17:30:34 -08002349 @Override
2350 public void onUserCanceledSsl(Tab tab) {
2351 WebView web = tab.getWebView();
2352 // TODO: Figure out the "right" behavior
2353 if (web.canGoBack()) {
2354 web.goBack();
2355 } else {
2356 web.loadUrl(mSettings.getHomePage());
2357 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002358 }
2359
2360 void goBackOnePageOrQuit() {
2361 Tab current = mTabControl.getCurrentTab();
2362 if (current == null) {
2363 /*
2364 * Instead of finishing the activity, simply push this to the back
2365 * of the stack and let ActivityManager to choose the foreground
2366 * activity. As BrowserActivity is singleTask, it will be always the
2367 * root of the task. So we can use either true or false for
2368 * moveTaskToBack().
2369 */
2370 mActivity.moveTaskToBack(true);
2371 return;
2372 }
2373 WebView w = current.getWebView();
2374 if (w.canGoBack()) {
2375 w.goBack();
2376 } else {
2377 // Check to see if we are closing a window that was created by
2378 // another window. If so, we switch back to that window.
2379 Tab parent = current.getParentTab();
2380 if (parent != null) {
2381 switchToTab(mTabControl.getTabIndex(parent));
2382 // Now we close the other tab
2383 closeTab(current);
2384 } else {
2385 if (current.closeOnExit()) {
Patrick Scottfc1518a2011-02-28 13:57:03 -05002386 // This will finish the activity if there is only one tab
2387 // open or it will switch to the next available tab if
2388 // available.
Michael Kolb96683f72011-02-15 14:24:35 -08002389 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002390 }
2391 /*
2392 * Instead of finishing the activity, simply push this to the back
2393 * of the stack and let ActivityManager to choose the foreground
2394 * activity. As BrowserActivity is singleTask, it will be always the
2395 * root of the task. So we can use either true or false for
2396 * moveTaskToBack().
2397 */
2398 mActivity.moveTaskToBack(true);
2399 }
2400 }
2401 }
2402
2403 /**
2404 * Feed the previously stored results strings to the BrowserProvider so that
2405 * the SearchDialog will show them instead of the standard searches.
2406 * @param result String to show on the editable line of the SearchDialog.
2407 */
2408 @Override
2409 public void showVoiceSearchResults(String result) {
2410 ContentProviderClient client = mActivity.getContentResolver()
2411 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2412 ContentProvider prov = client.getLocalContentProvider();
2413 BrowserProvider bp = (BrowserProvider) prov;
2414 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2415 client.release();
2416
2417 Bundle bundle = createGoogleSearchSourceBundle(
2418 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2419 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2420 startSearch(result, false, bundle, false);
2421 }
2422
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002423 @Override
2424 public void startSearch(String url) {
2425 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
2426 null, false);
2427 }
2428
Michael Kolb8233fac2010-10-26 16:08:53 -07002429 private void startSearch(String initialQuery, boolean selectInitialQuery,
2430 Bundle appSearchData, boolean globalSearch) {
2431 if (appSearchData == null) {
2432 appSearchData = createGoogleSearchSourceBundle(
2433 GOOGLE_SEARCH_SOURCE_TYPE);
2434 }
2435
2436 SearchEngine searchEngine = mSettings.getSearchEngine();
2437 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2438 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2439 }
2440 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2441 globalSearch);
2442 }
2443
2444 private Bundle createGoogleSearchSourceBundle(String source) {
2445 Bundle bundle = new Bundle();
2446 bundle.putString(Search.SOURCE, source);
2447 return bundle;
2448 }
2449
2450 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002451 * helper method for key handler
2452 * returns the current tab if it can't advance
2453 */
2454 private int getNextTabIndex() {
2455 return Math.min(mTabControl.getTabCount() - 1,
2456 mTabControl.getCurrentIndex() + 1);
2457 }
2458
2459 /**
2460 * helper method for key handler
2461 * returns the current tab if it can't advance
2462 */
2463 private int getPrevTabIndex() {
2464 return Math.max(0, mTabControl.getCurrentIndex() - 1);
2465 }
2466
2467 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002468 * handle key events in browser
2469 *
2470 * @param keyCode
2471 * @param event
2472 * @return true if handled, false to pass to super
2473 */
2474 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002475 boolean noModifiers = event.hasNoModifiers();
2476
Michael Kolb8233fac2010-10-26 16:08:53 -07002477 // Even if MENU is already held down, we need to call to super to open
2478 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002479 if (!noModifiers
2480 && ((KeyEvent.KEYCODE_MENU == keyCode)
2481 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2482 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002483 mMenuIsDown = true;
2484 return false;
2485 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002486
Cary Clark8ff8c662010-12-29 15:03:05 -05002487 WebView webView = getCurrentTopWebView();
2488 if (webView == null) return false;
2489
Cary Clark160bbb92011-01-10 11:17:07 -05002490 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2491 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002492
Michael Kolb8233fac2010-10-26 16:08:53 -07002493 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002494 case KeyEvent.KEYCODE_TAB:
2495 if (event.isCtrlPressed()) {
2496 if (event.isShiftPressed()) {
2497 // prev tab
2498 switchToTab(getPrevTabIndex());
2499 } else {
2500 // next tab
2501 switchToTab(getNextTabIndex());
2502 }
2503 return true;
2504 }
2505 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002506 case KeyEvent.KEYCODE_SPACE:
2507 // WebView/WebTextView handle the keys in the KeyDown. As
2508 // the Activity's shortcut keys are only handled when WebView
2509 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002510 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002511 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002512 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002513 pageDown();
2514 }
2515 return true;
2516 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002517 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002518 event.startTracking();
2519 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002520 case KeyEvent.KEYCODE_DPAD_LEFT:
2521 if (ctrl) {
2522 webView.goBack();
2523 return true;
2524 }
2525 break;
2526 case KeyEvent.KEYCODE_DPAD_RIGHT:
2527 if (ctrl) {
2528 webView.goForward();
2529 return true;
2530 }
2531 break;
2532 case KeyEvent.KEYCODE_A:
2533 if (ctrl) {
2534 webView.selectAll();
2535 return true;
2536 }
2537 break;
Michael Kolba4183062011-01-16 10:43:21 -08002538// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002539 case KeyEvent.KEYCODE_C:
2540 if (ctrl) {
2541 webView.copySelection();
2542 return true;
2543 }
2544 break;
Michael Kolba4183062011-01-16 10:43:21 -08002545// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002546// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002547// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002548// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002549// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002550// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002551// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002552// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002553// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002554// case KeyEvent.KEYCODE_M: // unused
2555// case KeyEvent.KEYCODE_N: // in Chrome: new window
2556// case KeyEvent.KEYCODE_O: // in Chrome: open file
2557// case KeyEvent.KEYCODE_P: // in Chrome: print page
2558// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002559// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002560// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2561 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002562 // we can't use the ctrl/shift flags, they check for
2563 // exclusive use of a modifier
2564 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002565 if (event.isShiftPressed()) {
2566 openIncognitoTab();
2567 } else {
2568 openTabToHomePage();
2569 }
2570 return true;
2571 }
2572 break;
2573// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2574// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb1a2eba42011-03-16 16:42:49 -07002575 case KeyEvent.KEYCODE_W: // in Chrome: close tab
2576 if (ctrl) {
2577 closeCurrentTab();
2578 return true;
2579 }
2580 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002581// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2582// case KeyEvent.KEYCODE_Y: // unused
2583// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002584 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002585 // it is a regular key and webview is not null
2586 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002587 }
2588
John Recke6bf4ab2011-02-24 15:48:05 -08002589 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2590 switch(keyCode) {
2591 case KeyEvent.KEYCODE_BACK:
2592 if (mUi.showsWeb()) {
2593 bookmarksOrHistoryPicker(true);
2594 return true;
2595 }
2596 break;
2597 }
2598 return false;
2599 }
2600
Michael Kolb8233fac2010-10-26 16:08:53 -07002601 boolean onKeyUp(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002602 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002603 switch(keyCode) {
2604 case KeyEvent.KEYCODE_MENU:
2605 mMenuIsDown = false;
2606 break;
2607 case KeyEvent.KEYCODE_BACK:
2608 if (event.isTracking() && !event.isCanceled()) {
2609 onBackKey();
2610 return true;
2611 }
2612 break;
2613 }
2614 return false;
2615 }
2616
2617 public boolean isMenuDown() {
2618 return mMenuIsDown;
2619 }
2620
Ben Murdoch8029a772010-11-16 11:58:21 +00002621 public void setupAutoFill(Message message) {
2622 // Open the settings activity at the AutoFill profile fragment so that
2623 // the user can create a new profile. When they return, we will dispatch
2624 // the message so that we can autofill the form using their new profile.
2625 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2626 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2627 AutoFillSettingsFragment.class.getName());
2628 mAutoFillSetupMessage = message;
2629 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2630 }
John Reckb3417f02011-01-14 11:01:05 -08002631
2632 @Override
2633 public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
2634 mOptionsMenuHandler = handler;
2635 }
2636
2637 @Override
2638 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
2639 if (mOptionsMenuHandler == handler) {
2640 mOptionsMenuHandler = null;
2641 }
2642 }
2643
Narayan Kamath5119edd2011-02-23 15:49:17 +00002644 @Override
2645 public void registerDropdownChangeListener(DropdownChangeListener d) {
2646 mUi.registerDropdownChangeListener(d);
2647 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002648}