blob: a02888236002561cb166b065b2f4d7a3ae049fae [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 Kolb8233fac2010-10-26 16:08:53 -07001059 public void activateVoiceSearchMode(String title) {
1060 mUi.showVoiceTitleBar(title);
1061 }
1062
1063 public void revertVoiceSearchMode(Tab tab) {
1064 mUi.revertVoiceTitleBar(tab);
1065 }
1066
1067 public void showCustomView(Tab tab, View view,
1068 WebChromeClient.CustomViewCallback callback) {
1069 if (tab.inForeground()) {
1070 if (mUi.isCustomViewShowing()) {
1071 callback.onCustomViewHidden();
1072 return;
1073 }
1074 mUi.showCustomView(view, callback);
1075 // Save the menu state and set it to empty while the custom
1076 // view is showing.
1077 mOldMenuState = mMenuState;
1078 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001079 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001080 }
1081 }
1082
1083 @Override
1084 public void hideCustomView() {
1085 if (mUi.isCustomViewShowing()) {
1086 mUi.onHideCustomView();
1087 // Reset the old menu state.
1088 mMenuState = mOldMenuState;
1089 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001090 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001091 }
1092 }
1093
1094 protected void onActivityResult(int requestCode, int resultCode,
1095 Intent intent) {
1096 if (getCurrentTopWebView() == null) return;
1097 switch (requestCode) {
1098 case PREFERENCES_PAGE:
1099 if (resultCode == Activity.RESULT_OK && intent != null) {
1100 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
1101 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
1102 mTabControl.removeParentChildRelationShips();
1103 }
1104 }
1105 break;
1106 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001107 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001108 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001109 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001110 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001111 case AUTOFILL_SETUP:
1112 // Determine whether a profile was actually set up or not
1113 // and if so, send the message back to the WebTextView to
1114 // fill the form with the new profile.
1115 if (getSettings().getAutoFillProfile() != null) {
1116 mAutoFillSetupMessage.sendToTarget();
1117 mAutoFillSetupMessage = null;
1118 }
1119 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001120 default:
1121 break;
1122 }
1123 getCurrentTopWebView().requestFocus();
1124 }
1125
1126 /**
1127 * Open the Go page.
1128 * @param startWithHistory If true, open starting on the history tab.
1129 * Otherwise, start with the bookmarks tab.
1130 */
1131 @Override
1132 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1133 if (mTabControl.getCurrentWebView() == null) {
1134 return;
1135 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001136 // clear action mode
1137 if (isInCustomActionMode()) {
1138 endActionMode();
1139 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001140 Bundle extras = new Bundle();
1141 // Disable opening in a new window if we have maxed out the windows
1142 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1143 !mTabControl.canCreateNewTab());
1144 mUi.showComboView(startWithHistory, extras);
1145 }
1146
1147 // combo view callbacks
1148
1149 /**
1150 * callback from ComboPage when clear history is requested
1151 */
1152 public void onRemoveParentChildRelationships() {
1153 mTabControl.removeParentChildRelationShips();
1154 }
1155
1156 /**
1157 * callback from ComboPage when bookmark/history selection
1158 */
1159 @Override
1160 public void onUrlSelected(String url, boolean newTab) {
1161 removeComboView();
1162 if (!TextUtils.isEmpty(url)) {
1163 if (newTab) {
Michael Kolb18eb3772010-12-10 14:29:51 -08001164 openTab(mTabControl.getCurrentTab(), url, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001165 } else {
1166 final Tab currentTab = mTabControl.getCurrentTab();
1167 dismissSubWindow(currentTab);
1168 loadUrl(getCurrentTopWebView(), url);
1169 }
1170 }
1171 }
1172
1173 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07001174 * dismiss the ComboPage
1175 */
1176 @Override
1177 public void removeComboView() {
1178 mUi.hideComboView();
1179 }
1180
1181 // active tabs page handling
1182
1183 protected void showActiveTabsPage() {
1184 mMenuState = EMPTY_MENU;
1185 mUi.showActiveTabsPage();
1186 }
1187
1188 /**
1189 * Remove the active tabs page.
1190 * @param needToAttach If true, the active tabs page did not attach a tab
1191 * to the content view, so we need to do that here.
1192 */
1193 @Override
1194 public void removeActiveTabsPage(boolean needToAttach) {
1195 mMenuState = R.id.MAIN_MENU;
1196 mUi.removeActiveTabsPage();
1197 if (needToAttach) {
1198 setActiveTab(mTabControl.getCurrentTab());
1199 }
1200 getCurrentTopWebView().requestFocus();
1201 }
1202
1203 // key handling
1204 protected void onBackKey() {
1205 if (!mUi.onBackKey()) {
1206 WebView subwindow = mTabControl.getCurrentSubWindow();
1207 if (subwindow != null) {
1208 if (subwindow.canGoBack()) {
1209 subwindow.goBack();
1210 } else {
1211 dismissSubWindow(mTabControl.getCurrentTab());
1212 }
1213 } else {
1214 goBackOnePageOrQuit();
1215 }
1216 }
1217 }
1218
1219 // menu handling and state
1220 // TODO: maybe put into separate handler
1221
1222 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckb3417f02011-01-14 11:01:05 -08001223 if (mOptionsMenuHandler != null) {
1224 return mOptionsMenuHandler.onCreateOptionsMenu(menu);
1225 }
1226
John Reckd73c5a22010-12-22 10:22:50 -08001227 if (mMenuState == EMPTY_MENU) {
1228 return false;
1229 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001230 MenuInflater inflater = mActivity.getMenuInflater();
1231 inflater.inflate(R.menu.browser, menu);
1232 updateInLoadMenuItems(menu);
1233 // hold on to the menu reference here; it is used by the page callbacks
1234 // to update the menu based on loading state
1235 mCachedMenu = menu;
1236 return true;
1237 }
1238
1239 protected void onCreateContextMenu(ContextMenu menu, View v,
1240 ContextMenuInfo menuInfo) {
1241 if (v instanceof TitleBarBase) {
1242 return;
1243 }
1244 if (!(v instanceof WebView)) {
1245 return;
1246 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001247 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001248 WebView.HitTestResult result = webview.getHitTestResult();
1249 if (result == null) {
1250 return;
1251 }
1252
1253 int type = result.getType();
1254 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1255 Log.w(LOGTAG,
1256 "We should not show context menu when nothing is touched");
1257 return;
1258 }
1259 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1260 // let TextView handles context menu
1261 return;
1262 }
1263
1264 // Note, http://b/issue?id=1106666 is requesting that
1265 // an inflated menu can be used again. This is not available
1266 // yet, so inflate each time (yuk!)
1267 MenuInflater inflater = mActivity.getMenuInflater();
1268 inflater.inflate(R.menu.browsercontext, menu);
1269
1270 // Show the correct menu group
1271 final String extra = result.getExtra();
1272 menu.setGroupVisible(R.id.PHONE_MENU,
1273 type == WebView.HitTestResult.PHONE_TYPE);
1274 menu.setGroupVisible(R.id.EMAIL_MENU,
1275 type == WebView.HitTestResult.EMAIL_TYPE);
1276 menu.setGroupVisible(R.id.GEO_MENU,
1277 type == WebView.HitTestResult.GEO_TYPE);
1278 menu.setGroupVisible(R.id.IMAGE_MENU,
1279 type == WebView.HitTestResult.IMAGE_TYPE
1280 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1281 menu.setGroupVisible(R.id.ANCHOR_MENU,
1282 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1283 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001284 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1285 || type == WebView.HitTestResult.PHONE_TYPE
1286 || type == WebView.HitTestResult.EMAIL_TYPE
1287 || type == WebView.HitTestResult.GEO_TYPE;
1288 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1289 if (hitText) {
1290 menu.findItem(R.id.select_text_menu_id)
1291 .setOnMenuItemClickListener(new SelectText(webview));
1292 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001293 // Setup custom handling depending on the type
1294 switch (type) {
1295 case WebView.HitTestResult.PHONE_TYPE:
1296 menu.setHeaderTitle(Uri.decode(extra));
1297 menu.findItem(R.id.dial_context_menu_id).setIntent(
1298 new Intent(Intent.ACTION_VIEW, Uri
1299 .parse(WebView.SCHEME_TEL + extra)));
1300 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1301 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1302 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1303 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1304 addIntent);
1305 menu.findItem(R.id.copy_phone_context_menu_id)
1306 .setOnMenuItemClickListener(
1307 new Copy(extra));
1308 break;
1309
1310 case WebView.HitTestResult.EMAIL_TYPE:
1311 menu.setHeaderTitle(extra);
1312 menu.findItem(R.id.email_context_menu_id).setIntent(
1313 new Intent(Intent.ACTION_VIEW, Uri
1314 .parse(WebView.SCHEME_MAILTO + extra)));
1315 menu.findItem(R.id.copy_mail_context_menu_id)
1316 .setOnMenuItemClickListener(
1317 new Copy(extra));
1318 break;
1319
1320 case WebView.HitTestResult.GEO_TYPE:
1321 menu.setHeaderTitle(extra);
1322 menu.findItem(R.id.map_context_menu_id).setIntent(
1323 new Intent(Intent.ACTION_VIEW, Uri
1324 .parse(WebView.SCHEME_GEO
1325 + URLEncoder.encode(extra))));
1326 menu.findItem(R.id.copy_geo_context_menu_id)
1327 .setOnMenuItemClickListener(
1328 new Copy(extra));
1329 break;
1330
1331 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1332 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001333 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001334 // decide whether to show the open link in new tab option
1335 boolean showNewTab = mTabControl.canCreateNewTab();
1336 MenuItem newTabItem
1337 = menu.findItem(R.id.open_newtab_context_menu_id);
Michael Kolb2dd65c82011-01-14 11:07:38 -08001338 newTabItem.setTitle(
1339 BrowserSettings.getInstance().openInBackground()
1340 ? R.string.contextmenu_openlink_newwindow_background
1341 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001342 newTabItem.setVisible(showNewTab);
1343 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001344 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1345 newTabItem.setOnMenuItemClickListener(
1346 new MenuItem.OnMenuItemClickListener() {
1347 @Override
1348 public boolean onMenuItemClick(MenuItem item) {
1349 final HashMap<String, WebView> hrefMap =
1350 new HashMap<String, WebView>();
1351 hrefMap.put("webview", webview);
1352 final Message msg = mHandler.obtainMessage(
1353 FOCUS_NODE_HREF,
1354 R.id.open_newtab_context_menu_id,
1355 0, hrefMap);
1356 webview.requestFocusNodeHref(msg);
1357 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001358 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001359 });
1360 } else {
1361 newTabItem.setOnMenuItemClickListener(
1362 new MenuItem.OnMenuItemClickListener() {
1363 @Override
1364 public boolean onMenuItemClick(MenuItem item) {
1365 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -08001366 final Tab newTab = openTab(parent,
1367 extra, false);
Leon Scroggins026f2542010-11-22 13:26:12 -05001368 if (newTab != parent) {
1369 parent.addChildTab(newTab);
1370 }
1371 return true;
1372 }
1373 });
1374 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001375 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001376 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1377 break;
1378 }
1379 // otherwise fall through to handle image part
1380 case WebView.HitTestResult.IMAGE_TYPE:
1381 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1382 menu.setHeaderTitle(extra);
1383 }
1384 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1385 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1386 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001387 setOnMenuItemClickListener(
1388 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001389 menu.findItem(R.id.set_wallpaper_context_menu_id).
1390 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1391 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001392 break;
1393
1394 default:
1395 Log.w(LOGTAG, "We should not get here.");
1396 break;
1397 }
1398 //update the ui
1399 mUi.onContextMenuCreated(menu);
1400 }
1401
1402 /**
1403 * As the menu can be open when loading state changes
1404 * we must manually update the state of the stop/reload menu
1405 * item
1406 */
1407 private void updateInLoadMenuItems(Menu menu) {
1408 if (menu == null) {
1409 return;
1410 }
1411 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1412 MenuItem src = mInLoad ?
1413 menu.findItem(R.id.stop_menu_id):
1414 menu.findItem(R.id.reload_menu_id);
1415 if (src != null) {
1416 dest.setIcon(src.getIcon());
1417 dest.setTitle(src.getTitle());
1418 }
1419 }
1420
John Reckb3417f02011-01-14 11:01:05 -08001421 boolean onPrepareOptionsMenu(Menu menu) {
1422 if (mOptionsMenuHandler != null) {
1423 return mOptionsMenuHandler.onPrepareOptionsMenu(menu);
1424 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001425 // Note: setVisible will decide whether an item is visible; while
1426 // setEnabled() will decide whether an item is enabled, which also means
1427 // whether the matching shortcut key will function.
1428 switch (mMenuState) {
1429 case EMPTY_MENU:
1430 if (mCurrentMenuState != mMenuState) {
1431 menu.setGroupVisible(R.id.MAIN_MENU, false);
1432 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1433 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1434 }
1435 break;
1436 default:
1437 if (mCurrentMenuState != mMenuState) {
1438 menu.setGroupVisible(R.id.MAIN_MENU, true);
1439 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1440 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1441 }
1442 final WebView w = getCurrentTopWebView();
1443 boolean canGoBack = false;
1444 boolean canGoForward = false;
1445 boolean isHome = false;
1446 if (w != null) {
1447 canGoBack = w.canGoBack();
1448 canGoForward = w.canGoForward();
1449 isHome = mSettings.getHomePage().equals(w.getUrl());
1450 }
1451 final MenuItem back = menu.findItem(R.id.back_menu_id);
1452 back.setEnabled(canGoBack);
1453
1454 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1455 home.setEnabled(!isHome);
1456
1457 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1458 forward.setEnabled(canGoForward);
1459
1460 // decide whether to show the share link option
1461 PackageManager pm = mActivity.getPackageManager();
1462 Intent send = new Intent(Intent.ACTION_SEND);
1463 send.setType("text/plain");
1464 ResolveInfo ri = pm.resolveActivity(send,
1465 PackageManager.MATCH_DEFAULT_ONLY);
1466 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1467
1468 boolean isNavDump = mSettings.isNavDump();
1469 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1470 nav.setVisible(isNavDump);
1471 nav.setEnabled(isNavDump);
1472
1473 boolean showDebugSettings = mSettings.showDebugSettings();
1474 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1475 counter.setVisible(showDebugSettings);
1476 counter.setEnabled(showDebugSettings);
1477
John Reckb3417f02011-01-14 11:01:05 -08001478 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1479 newtab.setEnabled(getTabControl().canCreateNewTab());
Michael Kolb8233fac2010-10-26 16:08:53 -07001480
Leon Scroggins81983762011-02-11 15:17:36 -05001481 MenuItem archive = menu.findItem(R.id.save_webarchive_menu_id);
John Reck51d8bad2011-02-28 15:47:47 -08001482 Tab tab = getTabControl().getCurrentTab();
1483 String url = tab != null ? tab.getUrl() : null;
1484 archive.setVisible(!TextUtils.isEmpty(url)
1485 && !url.endsWith(".webarchivexml"));
Michael Kolb8233fac2010-10-26 16:08:53 -07001486 break;
1487 }
1488 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001489 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001490 }
1491
1492 public boolean onOptionsItemSelected(MenuItem item) {
John Reckb3417f02011-01-14 11:01:05 -08001493 if (mOptionsMenuHandler != null &&
1494 mOptionsMenuHandler.onOptionsItemSelected(item)) {
1495 return true;
1496 }
1497
Michael Kolb8233fac2010-10-26 16:08:53 -07001498 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1499 // menu remains active, so ensure comboview is dismissed
1500 // if main menu option is selected
1501 removeComboView();
1502 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001503 if (null == getCurrentTopWebView()) {
1504 return false;
1505 }
1506 if (mMenuIsDown) {
1507 // The shortcut action consumes the MENU. Even if it is still down,
1508 // it won't trigger the next shortcut action. In the case of the
1509 // shortcut action triggering a new activity, like Bookmarks, we
1510 // won't get onKeyUp for MENU. So it is important to reset it here.
1511 mMenuIsDown = false;
1512 }
1513 switch (item.getItemId()) {
1514 // -- Main menu
1515 case R.id.new_tab_menu_id:
1516 openTabToHomePage();
1517 break;
1518
1519 case R.id.incognito_menu_id:
1520 openIncognitoTab();
1521 break;
1522
1523 case R.id.goto_menu_id:
1524 editUrl();
1525 break;
1526
1527 case R.id.bookmarks_menu_id:
1528 bookmarksOrHistoryPicker(false);
1529 break;
1530
1531 case R.id.active_tabs_menu_id:
1532 showActiveTabsPage();
1533 break;
1534
1535 case R.id.add_bookmark_menu_id:
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001536 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001537 break;
1538
1539 case R.id.stop_reload_menu_id:
1540 if (mInLoad) {
1541 stopLoading();
1542 } else {
1543 getCurrentTopWebView().reload();
1544 }
1545 break;
1546
1547 case R.id.back_menu_id:
1548 getCurrentTopWebView().goBack();
1549 break;
1550
1551 case R.id.forward_menu_id:
1552 getCurrentTopWebView().goForward();
1553 break;
1554
1555 case R.id.close_menu_id:
1556 // Close the subwindow if it exists.
1557 if (mTabControl.getCurrentSubWindow() != null) {
1558 dismissSubWindow(mTabControl.getCurrentTab());
1559 break;
1560 }
1561 closeCurrentTab();
1562 break;
1563
1564 case R.id.homepage_menu_id:
1565 Tab current = mTabControl.getCurrentTab();
1566 if (current != null) {
1567 dismissSubWindow(current);
1568 loadUrl(current.getWebView(), mSettings.getHomePage());
1569 }
1570 break;
1571
1572 case R.id.preferences_menu_id:
1573 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1574 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1575 getCurrentTopWebView().getUrl());
1576 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1577 break;
1578
1579 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001580 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001581 break;
1582
Leon Scrogginsac993842011-02-02 12:54:07 -05001583 case R.id.save_webarchive_menu_id:
1584 String state = Environment.getExternalStorageState();
1585 if (!Environment.MEDIA_MOUNTED.equals(state)) {
1586 Log.e(LOGTAG, "External storage not mounted");
1587 Toast.makeText(mActivity, R.string.webarchive_failed,
1588 Toast.LENGTH_SHORT).show();
1589 break;
1590 }
1591 final String directory = Environment.getExternalStoragePublicDirectory(
1592 Environment.DIRECTORY_DOWNLOADS) + File.separator;
1593 File dir = new File(directory);
1594 if (!dir.exists() && !dir.mkdirs()) {
1595 Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
1596 Toast.makeText(mActivity, R.string.webarchive_failed,
1597 Toast.LENGTH_SHORT).show();
1598 break;
1599 }
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001600 final WebView topWebView = getCurrentTopWebView();
Leon Scrogginsac993842011-02-02 12:54:07 -05001601 final String title = topWebView.getTitle();
John Reck51d8bad2011-02-28 15:47:47 -08001602 final String url = topWebView.getUrl();
Leon Scrogginsac993842011-02-02 12:54:07 -05001603 topWebView.saveWebArchive(directory, true,
1604 new ValueCallback<String>() {
1605 @Override
1606 public void onReceiveValue(final String value) {
1607 if (value != null) {
1608 File file = new File(value);
1609 final long length = file.length();
1610 if (file.exists() && length > 0) {
Leon Scroggins1cb96552011-02-11 14:22:57 -05001611 Toast.makeText(mActivity, R.string.webarchive_saved,
1612 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001613 final DownloadManager manager = (DownloadManager) mActivity
1614 .getSystemService(Context.DOWNLOAD_SERVICE);
1615 new Thread("Add WebArchive to download manager") {
1616 @Override
1617 public void run() {
Vasu Noria9e30a72011-03-07 11:37:34 -08001618 manager.addCompletedDownload(
1619 null == title ? value : title,
Leon Scrogginsac993842011-02-02 12:54:07 -05001620 value, true, "application/x-webarchive-xml",
1621 value, length, true);
1622 }
1623 }.start();
1624 return;
1625 }
1626 }
John Reck51d8bad2011-02-28 15:47:47 -08001627 DownloadHandler.onDownloadStartNoStream(mActivity,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001628 url, null, null, null, topWebView.isPrivateBrowsingEnabled());
Leon Scrogginsac993842011-02-02 12:54:07 -05001629 }
1630 });
1631 break;
1632
Michael Kolb8233fac2010-10-26 16:08:53 -07001633 case R.id.page_info_menu_id:
1634 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1635 false);
1636 break;
1637
1638 case R.id.classic_history_menu_id:
1639 bookmarksOrHistoryPicker(true);
1640 break;
1641
1642 case R.id.title_bar_share_page_url:
1643 case R.id.share_page_menu_id:
1644 Tab currentTab = mTabControl.getCurrentTab();
1645 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001646 return false;
1647 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001648 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001649 break;
1650
1651 case R.id.dump_nav_menu_id:
1652 getCurrentTopWebView().debugDump();
1653 break;
1654
1655 case R.id.dump_counters_menu_id:
1656 getCurrentTopWebView().dumpV8Counters();
1657 break;
1658
1659 case R.id.zoom_in_menu_id:
1660 getCurrentTopWebView().zoomIn();
1661 break;
1662
1663 case R.id.zoom_out_menu_id:
1664 getCurrentTopWebView().zoomOut();
1665 break;
1666
1667 case R.id.view_downloads_menu_id:
1668 viewDownloads();
1669 break;
1670
1671 case R.id.window_one_menu_id:
1672 case R.id.window_two_menu_id:
1673 case R.id.window_three_menu_id:
1674 case R.id.window_four_menu_id:
1675 case R.id.window_five_menu_id:
1676 case R.id.window_six_menu_id:
1677 case R.id.window_seven_menu_id:
1678 case R.id.window_eight_menu_id:
1679 {
1680 int menuid = item.getItemId();
1681 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1682 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1683 Tab desiredTab = mTabControl.getTab(id);
1684 if (desiredTab != null &&
1685 desiredTab != mTabControl.getCurrentTab()) {
1686 switchToTab(id);
1687 }
1688 break;
1689 }
1690 }
1691 }
1692 break;
1693
1694 default:
1695 return false;
1696 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001697 return true;
1698 }
1699
1700 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001701 // Let the History and Bookmark fragments handle menus they created.
1702 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1703 return false;
1704 }
1705
Michael Kolb8233fac2010-10-26 16:08:53 -07001706 int id = item.getItemId();
1707 boolean result = true;
1708 switch (id) {
1709 // For the context menu from the title bar
1710 case R.id.title_bar_copy_page_url:
1711 Tab currentTab = mTabControl.getCurrentTab();
1712 if (null == currentTab) {
1713 result = false;
1714 break;
1715 }
1716 WebView mainView = currentTab.getWebView();
1717 if (null == mainView) {
1718 result = false;
1719 break;
1720 }
1721 copy(mainView.getUrl());
1722 break;
1723 // -- Browser context menu
1724 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001725 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001726 case R.id.copy_link_context_menu_id:
1727 final WebView webView = getCurrentTopWebView();
1728 if (null == webView) {
1729 result = false;
1730 break;
1731 }
1732 final HashMap<String, WebView> hrefMap =
1733 new HashMap<String, WebView>();
1734 hrefMap.put("webview", webView);
1735 final Message msg = mHandler.obtainMessage(
1736 FOCUS_NODE_HREF, id, 0, hrefMap);
1737 webView.requestFocusNodeHref(msg);
1738 break;
1739
1740 default:
1741 // For other context menus
1742 result = onOptionsItemSelected(item);
1743 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001744 return result;
1745 }
1746
1747 /**
1748 * support programmatically opening the context menu
1749 */
1750 public void openContextMenu(View view) {
1751 mActivity.openContextMenu(view);
1752 }
1753
1754 /**
1755 * programmatically open the options menu
1756 */
1757 public void openOptionsMenu() {
1758 mActivity.openOptionsMenu();
1759 }
1760
1761 public boolean onMenuOpened(int featureId, Menu menu) {
1762 if (mOptionsMenuOpen) {
1763 if (mConfigChanged) {
1764 // We do not need to make any changes to the state of the
1765 // title bar, since the only thing that happened was a
1766 // change in orientation
1767 mConfigChanged = false;
1768 } else {
1769 if (!mExtendedMenuOpen) {
1770 mExtendedMenuOpen = true;
1771 mUi.onExtendedMenuOpened();
1772 } else {
1773 // Switching the menu back to icon view, so show the
1774 // title bar once again.
1775 mExtendedMenuOpen = false;
1776 mUi.onExtendedMenuClosed(mInLoad);
1777 mUi.onOptionsMenuOpened();
1778 }
1779 }
1780 } else {
1781 // The options menu is closed, so open it, and show the title
1782 mOptionsMenuOpen = true;
1783 mConfigChanged = false;
1784 mExtendedMenuOpen = false;
1785 mUi.onOptionsMenuOpened();
1786 }
1787 return true;
1788 }
1789
1790 public void onOptionsMenuClosed(Menu menu) {
1791 mOptionsMenuOpen = false;
1792 mUi.onOptionsMenuClosed(mInLoad);
1793 }
1794
1795 public void onContextMenuClosed(Menu menu) {
1796 mUi.onContextMenuClosed(menu, mInLoad);
1797 }
1798
1799 // Helper method for getting the top window.
1800 @Override
1801 public WebView getCurrentTopWebView() {
1802 return mTabControl.getCurrentTopWebView();
1803 }
1804
1805 @Override
1806 public WebView getCurrentWebView() {
1807 return mTabControl.getCurrentWebView();
1808 }
1809
1810 /*
1811 * This method is called as a result of the user selecting the options
1812 * menu to see the download window. It shows the download window on top of
1813 * the current window.
1814 */
1815 void viewDownloads() {
1816 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1817 mActivity.startActivity(intent);
1818 }
1819
1820 // action mode
1821
1822 void onActionModeStarted(ActionMode mode) {
1823 mUi.onActionModeStarted(mode);
1824 mActionMode = mode;
1825 }
1826
1827 /*
1828 * True if a custom ActionMode (i.e. find or select) is in use.
1829 */
1830 @Override
1831 public boolean isInCustomActionMode() {
1832 return mActionMode != null;
1833 }
1834
1835 /*
1836 * End the current ActionMode.
1837 */
1838 @Override
1839 public void endActionMode() {
1840 if (mActionMode != null) {
1841 mActionMode.finish();
1842 }
1843 }
1844
1845 /*
1846 * Called by find and select when they are finished. Replace title bars
1847 * as necessary.
1848 */
1849 public void onActionModeFinished(ActionMode mode) {
1850 if (!isInCustomActionMode()) return;
1851 mUi.onActionModeFinished(mInLoad);
1852 mActionMode = null;
1853 }
1854
1855 boolean isInLoad() {
1856 return mInLoad;
1857 }
1858
1859 // bookmark handling
1860
1861 /**
1862 * add the current page as a bookmark to the given folder id
1863 * @param folderId use -1 for the default folder
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001864 * @param canBeAnEdit If true, check to see whether the site is already
1865 * bookmarked, and if it is, edit that bookmark. If false, and
1866 * the site is already bookmarked, do not attempt to edit the
1867 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001868 */
1869 @Override
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001870 public void bookmarkCurrentPage(long folderId, boolean canBeAnEdit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001871 Intent i = new Intent(mActivity,
1872 AddBookmarkPage.class);
1873 WebView w = getCurrentTopWebView();
1874 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1875 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1876 String touchIconUrl = w.getTouchIconUrl();
1877 if (touchIconUrl != null) {
1878 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1879 WebSettings settings = w.getSettings();
1880 if (settings != null) {
1881 i.putExtra(AddBookmarkPage.USER_AGENT,
1882 settings.getUserAgentString());
1883 }
1884 }
1885 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1886 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1887 getDesiredThumbnailHeight(mActivity)));
1888 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1889 i.putExtra(BrowserContract.Bookmarks.PARENT,
1890 folderId);
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001891 if (canBeAnEdit) {
1892 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1893 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001894 // Put the dialog at the upper right of the screen, covering the
1895 // star on the title bar.
1896 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1897 mActivity.startActivity(i);
1898 }
1899
1900 // file chooser
1901 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1902 mUploadHandler = new UploadHandler(this);
1903 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1904 }
1905
1906 // thumbnails
1907
1908 /**
1909 * Return the desired width for thumbnail screenshots, which are stored in
1910 * the database, and used on the bookmarks screen.
1911 * @param context Context for finding out the density of the screen.
1912 * @return desired width for thumbnail screenshot.
1913 */
1914 static int getDesiredThumbnailWidth(Context context) {
1915 return context.getResources().getDimensionPixelOffset(
1916 R.dimen.bookmarkThumbnailWidth);
1917 }
1918
1919 /**
1920 * Return the desired height for thumbnail screenshots, which are stored in
1921 * the database, and used on the bookmarks screen.
1922 * @param context Context for finding out the density of the screen.
1923 * @return desired height for thumbnail screenshot.
1924 */
1925 static int getDesiredThumbnailHeight(Context context) {
1926 return context.getResources().getDimensionPixelOffset(
1927 R.dimen.bookmarkThumbnailHeight);
1928 }
1929
Michael Kolb1acef692011-03-08 14:12:06 -08001930 static Bitmap createScreenshot(Tab tab, int width, int height) {
1931 if ((tab != null) && (tab.getWebView() != null)) {
1932 return createScreenshot(tab.getWebView(), width, height);
1933 }
1934 return null;
1935 }
1936
Michael Kolb8233fac2010-10-26 16:08:53 -07001937 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001938 // We render to a bitmap 2x the desired size so that we can then
1939 // re-scale it with filtering since canvas.scale doesn't filter
1940 // This helps reduce aliasing at the cost of being slightly blurry
1941 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001942 Picture thumbnail = view.capturePicture();
1943 if (thumbnail == null) {
1944 return null;
1945 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001946 width *= filter_scale;
1947 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001948 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1949 Canvas canvas = new Canvas(bm);
1950 // May need to tweak these values to determine what is the
1951 // best scale factor
1952 int thumbnailWidth = thumbnail.getWidth();
1953 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001954 float scaleFactor = 1.0f;
Michael Kolbeb95db42011-03-03 10:38:40 -08001955 if (thumbnailWidth > 0 && thumbnailHeight > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001956 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001957 } else {
1958 return null;
1959 }
John Reckfe49ab42010-11-16 17:09:37 -08001960
Michael Kolbeb95db42011-03-03 10:38:40 -08001961 float scaleFactorY = (float) height / (float)thumbnailHeight;
1962 if (scaleFactorY > scaleFactor) {
1963 // The picture is narrower than the requested AR
1964 // Center the thumnail and crop the sides
1965 scaleFactor = scaleFactorY;
John Reckfe49ab42010-11-16 17:09:37 -08001966 float wx = (thumbnailWidth * scaleFactor) - width;
1967 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001968 }
1969
John Reckfe49ab42010-11-16 17:09:37 -08001970 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001971
1972 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001973 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
1974 height / filter_scale, true);
1975 bm.recycle();
1976 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001977 }
1978
John Reck34ef2672011-02-10 11:30:55 -08001979 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001980 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07001981 // FIXME: Would like to make sure there is actually something to
1982 // draw, but the API for that (WebViewCore.pictureReady()) is not
1983 // currently accessible here.
1984
John Reck34ef2672011-02-10 11:30:55 -08001985 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08001986 if (view == null) {
1987 // Tab was destroyed
1988 return;
1989 }
John Reck34ef2672011-02-10 11:30:55 -08001990 final String url = tab.getUrl();
1991 final String originalUrl = view.getOriginalUrl();
1992
1993 if (TextUtils.isEmpty(url)) {
1994 return;
1995 }
1996
1997 // Only update thumbnails for web urls (http(s)://), not for
1998 // about:, javascript:, data:, etc...
1999 // Unless it is a bookmarked site, then always update
2000 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2001 return;
2002 }
2003
Michael Kolb8233fac2010-10-26 16:08:53 -07002004 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2005 getDesiredThumbnailHeight(mActivity));
2006 if (bm == null) {
2007 return;
2008 }
2009
2010 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002011 new AsyncTask<Void, Void, Void>() {
2012 @Override
2013 protected Void doInBackground(Void... unused) {
2014 Cursor cursor = null;
2015 try {
2016 // TODO: Clean this up
2017 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2018 if (cursor != null && cursor.moveToFirst()) {
2019 final ByteArrayOutputStream os =
2020 new ByteArrayOutputStream();
2021 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002022
John Reck34ef2672011-02-10 11:30:55 -08002023 ContentValues values = new ContentValues();
2024 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002025
John Reck34ef2672011-02-10 11:30:55 -08002026 do {
John Reck617fd832011-02-16 14:35:59 -08002027 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002028 cr.update(Images.CONTENT_URI, values, null, null);
2029 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002030 }
John Reck34ef2672011-02-10 11:30:55 -08002031 } catch (IllegalStateException e) {
2032 // Ignore
2033 } finally {
2034 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002035 }
John Reck34ef2672011-02-10 11:30:55 -08002036 return null;
2037 }
2038 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002039 }
2040
2041 private class Copy implements OnMenuItemClickListener {
2042 private CharSequence mText;
2043
2044 public boolean onMenuItemClick(MenuItem item) {
2045 copy(mText);
2046 return true;
2047 }
2048
2049 public Copy(CharSequence toCopy) {
2050 mText = toCopy;
2051 }
2052 }
2053
Leon Scroggins63c02662010-11-18 15:16:27 -05002054 private static class Download implements OnMenuItemClickListener {
2055 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002056 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002057 private boolean mPrivateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002058
2059 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002060 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002061 null, null, mPrivateBrowsing);
Michael Kolb8233fac2010-10-26 16:08:53 -07002062 return true;
2063 }
2064
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002065 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002066 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002067 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002068 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002069 }
2070 }
2071
Cary Clark8974d282010-11-22 10:46:05 -05002072 private static class SelectText implements OnMenuItemClickListener {
2073 private WebView mWebView;
2074
2075 public boolean onMenuItemClick(MenuItem item) {
2076 if (mWebView != null) {
2077 return mWebView.selectText();
2078 }
2079 return false;
2080 }
2081
2082 public SelectText(WebView webView) {
2083 mWebView = webView;
2084 }
2085
2086 }
2087
Michael Kolb8233fac2010-10-26 16:08:53 -07002088 /********************** TODO: UI stuff *****************************/
2089
2090 // these methods have been copied, they still need to be cleaned up
2091
2092 /****************** tabs ***************************************************/
2093
2094 // basic tab interactions:
2095
2096 // it is assumed that tabcontrol already knows about the tab
2097 protected void addTab(Tab tab) {
2098 mUi.addTab(tab);
2099 }
2100
2101 protected void removeTab(Tab tab) {
2102 mUi.removeTab(tab);
2103 mTabControl.removeTab(tab);
2104 }
2105
2106 protected void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002107 // monkey protection against delayed start
2108 if (tab != null) {
2109 mTabControl.setCurrentTab(tab);
2110 // the tab is guaranteed to have a webview after setCurrentTab
2111 mUi.setActiveTab(tab);
2112 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002113 }
2114
2115 protected void closeEmptyChildTab() {
2116 Tab current = mTabControl.getCurrentTab();
2117 if (current != null
2118 && current.getWebView().copyBackForwardList().getSize() == 0) {
2119 Tab parent = current.getParentTab();
2120 if (parent != null) {
2121 switchToTab(mTabControl.getTabIndex(parent));
2122 closeTab(current);
2123 }
2124 }
2125 }
2126
2127 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002128 // Dismiss the subwindow if applicable.
2129 dismissSubWindow(appTab);
2130 // Since we might kill the WebView, remove it from the
2131 // content view first.
2132 mUi.detachTab(appTab);
2133 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002134 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002135 // TODO: analyze why the remove and add are necessary
2136 mUi.attachTab(appTab);
2137 if (mTabControl.getCurrentTab() != appTab) {
2138 switchToTab(mTabControl.getTabIndex(appTab));
John Reck30c714c2010-12-16 17:30:34 -08002139 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002140 } else {
2141 // If the tab was the current tab, we have to attach
2142 // it to the view system again.
2143 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002144 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002145 }
2146 }
2147
2148 // Remove the sub window if it exists. Also called by TabControl when the
2149 // user clicks the 'X' to dismiss a sub window.
2150 public void dismissSubWindow(Tab tab) {
2151 removeSubWindow(tab);
2152 // dismiss the subwindow. This will destroy the WebView.
2153 tab.dismissSubWindow();
2154 getCurrentTopWebView().requestFocus();
2155 }
2156
2157 @Override
2158 public void removeSubWindow(Tab t) {
2159 if (t.getSubWebView() != null) {
2160 mUi.removeSubWindow(t.getSubViewContainer());
2161 }
2162 }
2163
2164 @Override
2165 public void attachSubWindow(Tab tab) {
2166 if (tab.getSubWebView() != null) {
2167 mUi.attachSubWindow(tab.getSubViewContainer());
2168 getCurrentTopWebView().requestFocus();
2169 }
2170 }
2171
Michael Kolb843510f2010-12-09 10:51:49 -08002172 @Override
2173 public Tab openTabToHomePage() {
2174 // check for max tabs
2175 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002176 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2177 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002178 } else {
2179 mUi.showMaxTabsWarning();
2180 return null;
2181 }
2182 }
2183
Michael Kolb18eb3772010-12-10 14:29:51 -08002184 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2185 if (mSettings.openInBackground() && !forceForeground) {
2186 Tab tab = mTabControl.createNewTab(false, null, null,
2187 (parent != null) && parent.isPrivateBrowsingEnabled());
2188 if (tab != null) {
2189 addTab(tab);
2190 WebView view = tab.getWebView();
2191 loadUrl(view, url);
2192 }
2193 return tab;
2194 } else {
2195 return openTabAndShow(parent, new UrlData(url), false, null);
2196 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002197 }
2198
Michael Kolb18eb3772010-12-10 14:29:51 -08002199
Michael Kolb8233fac2010-10-26 16:08:53 -07002200 // This method does a ton of stuff. It will attempt to create a new tab
2201 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2202 // url isn't null, it will load the given url.
Patrick Scottcd135082011-01-31 18:21:58 -05002203 public Tab openTabAndShow(Tab parent, final UrlData urlData,
2204 boolean closeOnExit, String appId) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002205 final Tab currentTab = mTabControl.getCurrentTab();
2206 if (mTabControl.canCreateNewTab()) {
2207 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Michael Kolb18eb3772010-12-10 14:29:51 -08002208 urlData.mUrl,
2209 (parent != null) && parent.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -07002210 WebView webview = tab.getWebView();
2211 // We must set the new tab as the current tab to reflect the old
2212 // animation behavior.
2213 addTab(tab);
2214 setActiveTab(tab);
Patrick Scottd43e75a2011-03-14 14:47:23 -04002215 if (!urlData.isEmpty()) {
2216 loadUrlDataIn(tab, urlData);
2217 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002218 return tab;
2219 } else {
2220 // Get rid of the subwindow if it exists
2221 dismissSubWindow(currentTab);
2222 if (!urlData.isEmpty()) {
2223 // Load the given url.
2224 loadUrlDataIn(currentTab, urlData);
2225 }
2226 return currentTab;
2227 }
2228 }
2229
Michael Kolb8233fac2010-10-26 16:08:53 -07002230 @Override
2231 public Tab openIncognitoTab() {
2232 if (mTabControl.canCreateNewTab()) {
2233 Tab currentTab = mTabControl.getCurrentTab();
Michael Kolb8e7178d2011-01-26 19:13:36 -08002234 Tab tab = mTabControl.createNewTab(false, null,
John Reck4bfc0db2011-01-27 17:47:12 -08002235 null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07002236 addTab(tab);
2237 setActiveTab(tab);
John Reck4bfc0db2011-01-27 17:47:12 -08002238 loadUrlDataIn(tab, new UrlData("browser:incognito"));
Michael Kolb8233fac2010-10-26 16:08:53 -07002239 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002240 } else {
2241 mUi.showMaxTabsWarning();
2242 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002243 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002244 }
2245
2246 /**
2247 * @param index Index of the tab to change to, as defined by
2248 * mTabControl.getTabIndex(Tab t).
2249 * @return boolean True if we successfully switched to a different tab. If
2250 * the indexth tab is null, or if that tab is the same as
2251 * the current one, return false.
2252 */
2253 @Override
2254 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002255 // hide combo view if open
2256 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002257 Tab tab = mTabControl.getTab(index);
2258 Tab currentTab = mTabControl.getCurrentTab();
2259 if (tab == null || tab == currentTab) {
2260 return false;
2261 }
2262 setActiveTab(tab);
2263 return true;
2264 }
2265
2266 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002267 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002268 // hide combo view if open
2269 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002270 final Tab current = mTabControl.getCurrentTab();
2271 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002272 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002273 return;
2274 }
2275 final Tab parent = current.getParentTab();
2276 int indexToShow = -1;
2277 if (parent != null) {
2278 indexToShow = mTabControl.getTabIndex(parent);
2279 } else {
2280 final int currentIndex = mTabControl.getCurrentIndex();
2281 // Try to move to the tab to the right
2282 indexToShow = currentIndex + 1;
2283 if (indexToShow > mTabControl.getTabCount() - 1) {
2284 // Try to move to the tab to the left
2285 indexToShow = currentIndex - 1;
2286 }
2287 }
2288 if (switchToTab(indexToShow)) {
2289 // Close window
2290 closeTab(current);
2291 }
2292 }
2293
2294 /**
2295 * Close the tab, remove its associated title bar, and adjust mTabControl's
2296 * current tab to a valid value.
2297 */
2298 @Override
2299 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002300 // hide combo view if open
2301 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002302 int currentIndex = mTabControl.getCurrentIndex();
2303 int removeIndex = mTabControl.getTabIndex(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002304 Tab newtab = mTabControl.getTab(currentIndex);
2305 setActiveTab(newtab);
Michael Kolb2d59c322011-01-25 13:18:55 -08002306 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002307 }
2308
2309 /**************** TODO: Url loading clean up *******************************/
2310
2311 // Called when loading from context menu or LOAD_URL message
2312 protected void loadUrlFromContext(WebView view, String url) {
2313 // In case the user enters nothing.
2314 if (url != null && url.length() != 0 && view != null) {
2315 url = UrlUtils.smartUrlFilter(url);
2316 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2317 loadUrl(view, url);
2318 }
2319 }
2320 }
2321
2322 /**
2323 * Load the URL into the given WebView and update the title bar
2324 * to reflect the new load. Call this instead of WebView.loadUrl
2325 * directly.
2326 * @param view The WebView used to load url.
2327 * @param url The URL to load.
2328 */
2329 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002330 view.loadUrl(url);
2331 }
2332
2333 /**
2334 * Load UrlData into a Tab and update the title bar to reflect the new
2335 * load. Call this instead of UrlData.loadIn directly.
2336 * @param t The Tab used to load.
2337 * @param data The UrlData being loaded.
2338 */
2339 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002340 data.loadIn(t);
2341 }
2342
John Reck30c714c2010-12-16 17:30:34 -08002343 @Override
2344 public void onUserCanceledSsl(Tab tab) {
2345 WebView web = tab.getWebView();
2346 // TODO: Figure out the "right" behavior
2347 if (web.canGoBack()) {
2348 web.goBack();
2349 } else {
2350 web.loadUrl(mSettings.getHomePage());
2351 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002352 }
2353
2354 void goBackOnePageOrQuit() {
2355 Tab current = mTabControl.getCurrentTab();
2356 if (current == null) {
2357 /*
2358 * Instead of finishing the activity, simply push this to the back
2359 * of the stack and let ActivityManager to choose the foreground
2360 * activity. As BrowserActivity is singleTask, it will be always the
2361 * root of the task. So we can use either true or false for
2362 * moveTaskToBack().
2363 */
2364 mActivity.moveTaskToBack(true);
2365 return;
2366 }
2367 WebView w = current.getWebView();
2368 if (w.canGoBack()) {
2369 w.goBack();
2370 } else {
2371 // Check to see if we are closing a window that was created by
2372 // another window. If so, we switch back to that window.
2373 Tab parent = current.getParentTab();
2374 if (parent != null) {
2375 switchToTab(mTabControl.getTabIndex(parent));
2376 // Now we close the other tab
2377 closeTab(current);
2378 } else {
2379 if (current.closeOnExit()) {
Patrick Scottfc1518a2011-02-28 13:57:03 -05002380 // This will finish the activity if there is only one tab
2381 // open or it will switch to the next available tab if
2382 // available.
Michael Kolb96683f72011-02-15 14:24:35 -08002383 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002384 }
2385 /*
2386 * Instead of finishing the activity, simply push this to the back
2387 * of the stack and let ActivityManager to choose the foreground
2388 * activity. As BrowserActivity is singleTask, it will be always the
2389 * root of the task. So we can use either true or false for
2390 * moveTaskToBack().
2391 */
2392 mActivity.moveTaskToBack(true);
2393 }
2394 }
2395 }
2396
2397 /**
2398 * Feed the previously stored results strings to the BrowserProvider so that
2399 * the SearchDialog will show them instead of the standard searches.
2400 * @param result String to show on the editable line of the SearchDialog.
2401 */
2402 @Override
2403 public void showVoiceSearchResults(String result) {
2404 ContentProviderClient client = mActivity.getContentResolver()
2405 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2406 ContentProvider prov = client.getLocalContentProvider();
2407 BrowserProvider bp = (BrowserProvider) prov;
2408 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2409 client.release();
2410
2411 Bundle bundle = createGoogleSearchSourceBundle(
2412 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2413 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2414 startSearch(result, false, bundle, false);
2415 }
2416
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002417 @Override
2418 public void startSearch(String url) {
2419 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
2420 null, false);
2421 }
2422
Michael Kolb8233fac2010-10-26 16:08:53 -07002423 private void startSearch(String initialQuery, boolean selectInitialQuery,
2424 Bundle appSearchData, boolean globalSearch) {
2425 if (appSearchData == null) {
2426 appSearchData = createGoogleSearchSourceBundle(
2427 GOOGLE_SEARCH_SOURCE_TYPE);
2428 }
2429
2430 SearchEngine searchEngine = mSettings.getSearchEngine();
2431 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2432 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2433 }
2434 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2435 globalSearch);
2436 }
2437
2438 private Bundle createGoogleSearchSourceBundle(String source) {
2439 Bundle bundle = new Bundle();
2440 bundle.putString(Search.SOURCE, source);
2441 return bundle;
2442 }
2443
2444 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002445 * helper method for key handler
2446 * returns the current tab if it can't advance
2447 */
2448 private int getNextTabIndex() {
2449 return Math.min(mTabControl.getTabCount() - 1,
2450 mTabControl.getCurrentIndex() + 1);
2451 }
2452
2453 /**
2454 * helper method for key handler
2455 * returns the current tab if it can't advance
2456 */
2457 private int getPrevTabIndex() {
2458 return Math.max(0, mTabControl.getCurrentIndex() - 1);
2459 }
2460
2461 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002462 * handle key events in browser
2463 *
2464 * @param keyCode
2465 * @param event
2466 * @return true if handled, false to pass to super
2467 */
2468 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002469 boolean noModifiers = event.hasNoModifiers();
2470
Michael Kolb8233fac2010-10-26 16:08:53 -07002471 // Even if MENU is already held down, we need to call to super to open
2472 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002473 if (!noModifiers
2474 && ((KeyEvent.KEYCODE_MENU == keyCode)
2475 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2476 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002477 mMenuIsDown = true;
2478 return false;
2479 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002480
Cary Clark8ff8c662010-12-29 15:03:05 -05002481 WebView webView = getCurrentTopWebView();
2482 if (webView == null) return false;
2483
Cary Clark160bbb92011-01-10 11:17:07 -05002484 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2485 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002486
Michael Kolb8233fac2010-10-26 16:08:53 -07002487 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002488 case KeyEvent.KEYCODE_TAB:
2489 if (event.isCtrlPressed()) {
2490 if (event.isShiftPressed()) {
2491 // prev tab
2492 switchToTab(getPrevTabIndex());
2493 } else {
2494 // next tab
2495 switchToTab(getNextTabIndex());
2496 }
2497 return true;
2498 }
2499 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002500 case KeyEvent.KEYCODE_SPACE:
2501 // WebView/WebTextView handle the keys in the KeyDown. As
2502 // the Activity's shortcut keys are only handled when WebView
2503 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002504 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002505 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002506 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002507 pageDown();
2508 }
2509 return true;
2510 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002511 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002512 event.startTracking();
2513 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002514 case KeyEvent.KEYCODE_DPAD_LEFT:
2515 if (ctrl) {
2516 webView.goBack();
2517 return true;
2518 }
2519 break;
2520 case KeyEvent.KEYCODE_DPAD_RIGHT:
2521 if (ctrl) {
2522 webView.goForward();
2523 return true;
2524 }
2525 break;
2526 case KeyEvent.KEYCODE_A:
2527 if (ctrl) {
2528 webView.selectAll();
2529 return true;
2530 }
2531 break;
Michael Kolba4183062011-01-16 10:43:21 -08002532// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002533 case KeyEvent.KEYCODE_C:
2534 if (ctrl) {
2535 webView.copySelection();
2536 return true;
2537 }
2538 break;
Michael Kolba4183062011-01-16 10:43:21 -08002539// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002540// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002541// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002542// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002543// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002544// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002545// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002546// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002547// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002548// case KeyEvent.KEYCODE_M: // unused
2549// case KeyEvent.KEYCODE_N: // in Chrome: new window
2550// case KeyEvent.KEYCODE_O: // in Chrome: open file
2551// case KeyEvent.KEYCODE_P: // in Chrome: print page
2552// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002553// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002554// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2555 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002556 // we can't use the ctrl/shift flags, they check for
2557 // exclusive use of a modifier
2558 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002559 if (event.isShiftPressed()) {
2560 openIncognitoTab();
2561 } else {
2562 openTabToHomePage();
2563 }
2564 return true;
2565 }
2566 break;
2567// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2568// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb1a2eba42011-03-16 16:42:49 -07002569 case KeyEvent.KEYCODE_W: // in Chrome: close tab
2570 if (ctrl) {
2571 closeCurrentTab();
2572 return true;
2573 }
2574 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002575// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2576// case KeyEvent.KEYCODE_Y: // unused
2577// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002578 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002579 // it is a regular key and webview is not null
2580 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002581 }
2582
John Recke6bf4ab2011-02-24 15:48:05 -08002583 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2584 switch(keyCode) {
2585 case KeyEvent.KEYCODE_BACK:
2586 if (mUi.showsWeb()) {
2587 bookmarksOrHistoryPicker(true);
2588 return true;
2589 }
2590 break;
2591 }
2592 return false;
2593 }
2594
Michael Kolb8233fac2010-10-26 16:08:53 -07002595 boolean onKeyUp(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002596 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002597 switch(keyCode) {
2598 case KeyEvent.KEYCODE_MENU:
2599 mMenuIsDown = false;
2600 break;
2601 case KeyEvent.KEYCODE_BACK:
2602 if (event.isTracking() && !event.isCanceled()) {
2603 onBackKey();
2604 return true;
2605 }
2606 break;
2607 }
2608 return false;
2609 }
2610
2611 public boolean isMenuDown() {
2612 return mMenuIsDown;
2613 }
2614
Ben Murdoch8029a772010-11-16 11:58:21 +00002615 public void setupAutoFill(Message message) {
2616 // Open the settings activity at the AutoFill profile fragment so that
2617 // the user can create a new profile. When they return, we will dispatch
2618 // the message so that we can autofill the form using their new profile.
2619 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2620 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2621 AutoFillSettingsFragment.class.getName());
2622 mAutoFillSetupMessage = message;
2623 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2624 }
John Reckb3417f02011-01-14 11:01:05 -08002625
2626 @Override
2627 public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
2628 mOptionsMenuHandler = handler;
2629 }
2630
2631 @Override
2632 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
2633 if (mOptionsMenuHandler == handler) {
2634 mOptionsMenuHandler = null;
2635 }
2636 }
2637
Narayan Kamath5119edd2011-02-23 15:49:17 +00002638 @Override
2639 public void registerDropdownChangeListener(DropdownChangeListener d) {
2640 mUi.registerDropdownChangeListener(d);
2641 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002642}