blob: efc58b108ab05b321f7e957eaed0036e587c20b9 [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
Michael Kolb736990c2011-03-20 10:01:20 -07001067 public boolean supportsVoiceSearch() {
1068 SearchEngine searchEngine = BrowserSettings.getInstance()
1069 .getSearchEngine();
1070 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1071 }
1072
Michael Kolb8233fac2010-10-26 16:08:53 -07001073 public void showCustomView(Tab tab, View view,
1074 WebChromeClient.CustomViewCallback callback) {
1075 if (tab.inForeground()) {
1076 if (mUi.isCustomViewShowing()) {
1077 callback.onCustomViewHidden();
1078 return;
1079 }
1080 mUi.showCustomView(view, callback);
1081 // Save the menu state and set it to empty while the custom
1082 // view is showing.
1083 mOldMenuState = mMenuState;
1084 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001085 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001086 }
1087 }
1088
1089 @Override
1090 public void hideCustomView() {
1091 if (mUi.isCustomViewShowing()) {
1092 mUi.onHideCustomView();
1093 // Reset the old menu state.
1094 mMenuState = mOldMenuState;
1095 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001096 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001097 }
1098 }
1099
1100 protected void onActivityResult(int requestCode, int resultCode,
1101 Intent intent) {
1102 if (getCurrentTopWebView() == null) return;
1103 switch (requestCode) {
1104 case PREFERENCES_PAGE:
1105 if (resultCode == Activity.RESULT_OK && intent != null) {
1106 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
1107 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
1108 mTabControl.removeParentChildRelationShips();
1109 }
1110 }
1111 break;
1112 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001113 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001114 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001115 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001116 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001117 case AUTOFILL_SETUP:
1118 // Determine whether a profile was actually set up or not
1119 // and if so, send the message back to the WebTextView to
1120 // fill the form with the new profile.
1121 if (getSettings().getAutoFillProfile() != null) {
1122 mAutoFillSetupMessage.sendToTarget();
1123 mAutoFillSetupMessage = null;
1124 }
1125 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001126 default:
1127 break;
1128 }
1129 getCurrentTopWebView().requestFocus();
1130 }
1131
1132 /**
1133 * Open the Go page.
1134 * @param startWithHistory If true, open starting on the history tab.
1135 * Otherwise, start with the bookmarks tab.
1136 */
1137 @Override
1138 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1139 if (mTabControl.getCurrentWebView() == null) {
1140 return;
1141 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001142 // clear action mode
1143 if (isInCustomActionMode()) {
1144 endActionMode();
1145 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001146 Bundle extras = new Bundle();
1147 // Disable opening in a new window if we have maxed out the windows
1148 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1149 !mTabControl.canCreateNewTab());
1150 mUi.showComboView(startWithHistory, extras);
1151 }
1152
1153 // combo view callbacks
1154
1155 /**
1156 * callback from ComboPage when clear history is requested
1157 */
1158 public void onRemoveParentChildRelationships() {
1159 mTabControl.removeParentChildRelationShips();
1160 }
1161
1162 /**
1163 * callback from ComboPage when bookmark/history selection
1164 */
1165 @Override
1166 public void onUrlSelected(String url, boolean newTab) {
1167 removeComboView();
1168 if (!TextUtils.isEmpty(url)) {
1169 if (newTab) {
Michael Kolb18eb3772010-12-10 14:29:51 -08001170 openTab(mTabControl.getCurrentTab(), url, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001171 } else {
1172 final Tab currentTab = mTabControl.getCurrentTab();
1173 dismissSubWindow(currentTab);
1174 loadUrl(getCurrentTopWebView(), url);
1175 }
1176 }
1177 }
1178
1179 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07001180 * dismiss the ComboPage
1181 */
1182 @Override
1183 public void removeComboView() {
1184 mUi.hideComboView();
1185 }
1186
1187 // active tabs page handling
1188
1189 protected void showActiveTabsPage() {
1190 mMenuState = EMPTY_MENU;
1191 mUi.showActiveTabsPage();
1192 }
1193
1194 /**
1195 * Remove the active tabs page.
1196 * @param needToAttach If true, the active tabs page did not attach a tab
1197 * to the content view, so we need to do that here.
1198 */
1199 @Override
1200 public void removeActiveTabsPage(boolean needToAttach) {
1201 mMenuState = R.id.MAIN_MENU;
1202 mUi.removeActiveTabsPage();
1203 if (needToAttach) {
1204 setActiveTab(mTabControl.getCurrentTab());
1205 }
1206 getCurrentTopWebView().requestFocus();
1207 }
1208
1209 // key handling
1210 protected void onBackKey() {
1211 if (!mUi.onBackKey()) {
1212 WebView subwindow = mTabControl.getCurrentSubWindow();
1213 if (subwindow != null) {
1214 if (subwindow.canGoBack()) {
1215 subwindow.goBack();
1216 } else {
1217 dismissSubWindow(mTabControl.getCurrentTab());
1218 }
1219 } else {
1220 goBackOnePageOrQuit();
1221 }
1222 }
1223 }
1224
1225 // menu handling and state
1226 // TODO: maybe put into separate handler
1227
1228 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckb3417f02011-01-14 11:01:05 -08001229 if (mOptionsMenuHandler != null) {
1230 return mOptionsMenuHandler.onCreateOptionsMenu(menu);
1231 }
1232
John Reckd73c5a22010-12-22 10:22:50 -08001233 if (mMenuState == EMPTY_MENU) {
1234 return false;
1235 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001236 MenuInflater inflater = mActivity.getMenuInflater();
1237 inflater.inflate(R.menu.browser, menu);
1238 updateInLoadMenuItems(menu);
1239 // hold on to the menu reference here; it is used by the page callbacks
1240 // to update the menu based on loading state
1241 mCachedMenu = menu;
1242 return true;
1243 }
1244
1245 protected void onCreateContextMenu(ContextMenu menu, View v,
1246 ContextMenuInfo menuInfo) {
1247 if (v instanceof TitleBarBase) {
1248 return;
1249 }
1250 if (!(v instanceof WebView)) {
1251 return;
1252 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001253 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001254 WebView.HitTestResult result = webview.getHitTestResult();
1255 if (result == null) {
1256 return;
1257 }
1258
1259 int type = result.getType();
1260 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1261 Log.w(LOGTAG,
1262 "We should not show context menu when nothing is touched");
1263 return;
1264 }
1265 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1266 // let TextView handles context menu
1267 return;
1268 }
1269
1270 // Note, http://b/issue?id=1106666 is requesting that
1271 // an inflated menu can be used again. This is not available
1272 // yet, so inflate each time (yuk!)
1273 MenuInflater inflater = mActivity.getMenuInflater();
1274 inflater.inflate(R.menu.browsercontext, menu);
1275
1276 // Show the correct menu group
1277 final String extra = result.getExtra();
1278 menu.setGroupVisible(R.id.PHONE_MENU,
1279 type == WebView.HitTestResult.PHONE_TYPE);
1280 menu.setGroupVisible(R.id.EMAIL_MENU,
1281 type == WebView.HitTestResult.EMAIL_TYPE);
1282 menu.setGroupVisible(R.id.GEO_MENU,
1283 type == WebView.HitTestResult.GEO_TYPE);
1284 menu.setGroupVisible(R.id.IMAGE_MENU,
1285 type == WebView.HitTestResult.IMAGE_TYPE
1286 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1287 menu.setGroupVisible(R.id.ANCHOR_MENU,
1288 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1289 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001290 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1291 || type == WebView.HitTestResult.PHONE_TYPE
1292 || type == WebView.HitTestResult.EMAIL_TYPE
1293 || type == WebView.HitTestResult.GEO_TYPE;
1294 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1295 if (hitText) {
1296 menu.findItem(R.id.select_text_menu_id)
1297 .setOnMenuItemClickListener(new SelectText(webview));
1298 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001299 // Setup custom handling depending on the type
1300 switch (type) {
1301 case WebView.HitTestResult.PHONE_TYPE:
1302 menu.setHeaderTitle(Uri.decode(extra));
1303 menu.findItem(R.id.dial_context_menu_id).setIntent(
1304 new Intent(Intent.ACTION_VIEW, Uri
1305 .parse(WebView.SCHEME_TEL + extra)));
1306 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1307 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1308 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1309 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1310 addIntent);
1311 menu.findItem(R.id.copy_phone_context_menu_id)
1312 .setOnMenuItemClickListener(
1313 new Copy(extra));
1314 break;
1315
1316 case WebView.HitTestResult.EMAIL_TYPE:
1317 menu.setHeaderTitle(extra);
1318 menu.findItem(R.id.email_context_menu_id).setIntent(
1319 new Intent(Intent.ACTION_VIEW, Uri
1320 .parse(WebView.SCHEME_MAILTO + extra)));
1321 menu.findItem(R.id.copy_mail_context_menu_id)
1322 .setOnMenuItemClickListener(
1323 new Copy(extra));
1324 break;
1325
1326 case WebView.HitTestResult.GEO_TYPE:
1327 menu.setHeaderTitle(extra);
1328 menu.findItem(R.id.map_context_menu_id).setIntent(
1329 new Intent(Intent.ACTION_VIEW, Uri
1330 .parse(WebView.SCHEME_GEO
1331 + URLEncoder.encode(extra))));
1332 menu.findItem(R.id.copy_geo_context_menu_id)
1333 .setOnMenuItemClickListener(
1334 new Copy(extra));
1335 break;
1336
1337 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1338 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001339 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001340 // decide whether to show the open link in new tab option
1341 boolean showNewTab = mTabControl.canCreateNewTab();
1342 MenuItem newTabItem
1343 = menu.findItem(R.id.open_newtab_context_menu_id);
Michael Kolb2dd65c82011-01-14 11:07:38 -08001344 newTabItem.setTitle(
1345 BrowserSettings.getInstance().openInBackground()
1346 ? R.string.contextmenu_openlink_newwindow_background
1347 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001348 newTabItem.setVisible(showNewTab);
1349 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001350 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1351 newTabItem.setOnMenuItemClickListener(
1352 new MenuItem.OnMenuItemClickListener() {
1353 @Override
1354 public boolean onMenuItemClick(MenuItem item) {
1355 final HashMap<String, WebView> hrefMap =
1356 new HashMap<String, WebView>();
1357 hrefMap.put("webview", webview);
1358 final Message msg = mHandler.obtainMessage(
1359 FOCUS_NODE_HREF,
1360 R.id.open_newtab_context_menu_id,
1361 0, hrefMap);
1362 webview.requestFocusNodeHref(msg);
1363 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001364 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001365 });
1366 } else {
1367 newTabItem.setOnMenuItemClickListener(
1368 new MenuItem.OnMenuItemClickListener() {
1369 @Override
1370 public boolean onMenuItemClick(MenuItem item) {
1371 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -08001372 final Tab newTab = openTab(parent,
1373 extra, false);
Leon Scroggins026f2542010-11-22 13:26:12 -05001374 if (newTab != parent) {
1375 parent.addChildTab(newTab);
1376 }
1377 return true;
1378 }
1379 });
1380 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001381 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001382 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1383 break;
1384 }
1385 // otherwise fall through to handle image part
1386 case WebView.HitTestResult.IMAGE_TYPE:
1387 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1388 menu.setHeaderTitle(extra);
1389 }
1390 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1391 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1392 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001393 setOnMenuItemClickListener(
1394 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001395 menu.findItem(R.id.set_wallpaper_context_menu_id).
1396 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1397 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001398 break;
1399
1400 default:
1401 Log.w(LOGTAG, "We should not get here.");
1402 break;
1403 }
1404 //update the ui
1405 mUi.onContextMenuCreated(menu);
1406 }
1407
1408 /**
1409 * As the menu can be open when loading state changes
1410 * we must manually update the state of the stop/reload menu
1411 * item
1412 */
1413 private void updateInLoadMenuItems(Menu menu) {
1414 if (menu == null) {
1415 return;
1416 }
1417 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1418 MenuItem src = mInLoad ?
1419 menu.findItem(R.id.stop_menu_id):
1420 menu.findItem(R.id.reload_menu_id);
1421 if (src != null) {
1422 dest.setIcon(src.getIcon());
1423 dest.setTitle(src.getTitle());
1424 }
1425 }
1426
John Reckb3417f02011-01-14 11:01:05 -08001427 boolean onPrepareOptionsMenu(Menu menu) {
1428 if (mOptionsMenuHandler != null) {
1429 return mOptionsMenuHandler.onPrepareOptionsMenu(menu);
1430 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001431 // Note: setVisible will decide whether an item is visible; while
1432 // setEnabled() will decide whether an item is enabled, which also means
1433 // whether the matching shortcut key will function.
1434 switch (mMenuState) {
1435 case EMPTY_MENU:
1436 if (mCurrentMenuState != mMenuState) {
1437 menu.setGroupVisible(R.id.MAIN_MENU, false);
1438 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1439 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1440 }
1441 break;
1442 default:
1443 if (mCurrentMenuState != mMenuState) {
1444 menu.setGroupVisible(R.id.MAIN_MENU, true);
1445 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1446 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1447 }
1448 final WebView w = getCurrentTopWebView();
1449 boolean canGoBack = false;
1450 boolean canGoForward = false;
1451 boolean isHome = false;
1452 if (w != null) {
1453 canGoBack = w.canGoBack();
1454 canGoForward = w.canGoForward();
1455 isHome = mSettings.getHomePage().equals(w.getUrl());
1456 }
1457 final MenuItem back = menu.findItem(R.id.back_menu_id);
1458 back.setEnabled(canGoBack);
1459
1460 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1461 home.setEnabled(!isHome);
1462
1463 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1464 forward.setEnabled(canGoForward);
1465
1466 // decide whether to show the share link option
1467 PackageManager pm = mActivity.getPackageManager();
1468 Intent send = new Intent(Intent.ACTION_SEND);
1469 send.setType("text/plain");
1470 ResolveInfo ri = pm.resolveActivity(send,
1471 PackageManager.MATCH_DEFAULT_ONLY);
1472 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1473
1474 boolean isNavDump = mSettings.isNavDump();
1475 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1476 nav.setVisible(isNavDump);
1477 nav.setEnabled(isNavDump);
1478
1479 boolean showDebugSettings = mSettings.showDebugSettings();
1480 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1481 counter.setVisible(showDebugSettings);
1482 counter.setEnabled(showDebugSettings);
1483
John Reckb3417f02011-01-14 11:01:05 -08001484 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1485 newtab.setEnabled(getTabControl().canCreateNewTab());
Michael Kolb8233fac2010-10-26 16:08:53 -07001486
Leon Scroggins81983762011-02-11 15:17:36 -05001487 MenuItem archive = menu.findItem(R.id.save_webarchive_menu_id);
John Reck51d8bad2011-02-28 15:47:47 -08001488 Tab tab = getTabControl().getCurrentTab();
1489 String url = tab != null ? tab.getUrl() : null;
1490 archive.setVisible(!TextUtils.isEmpty(url)
1491 && !url.endsWith(".webarchivexml"));
Michael Kolb8233fac2010-10-26 16:08:53 -07001492 break;
1493 }
1494 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001495 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001496 }
1497
1498 public boolean onOptionsItemSelected(MenuItem item) {
John Reckb3417f02011-01-14 11:01:05 -08001499 if (mOptionsMenuHandler != null &&
1500 mOptionsMenuHandler.onOptionsItemSelected(item)) {
1501 return true;
1502 }
1503
Michael Kolb8233fac2010-10-26 16:08:53 -07001504 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1505 // menu remains active, so ensure comboview is dismissed
1506 // if main menu option is selected
1507 removeComboView();
1508 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001509 if (null == getCurrentTopWebView()) {
1510 return false;
1511 }
1512 if (mMenuIsDown) {
1513 // The shortcut action consumes the MENU. Even if it is still down,
1514 // it won't trigger the next shortcut action. In the case of the
1515 // shortcut action triggering a new activity, like Bookmarks, we
1516 // won't get onKeyUp for MENU. So it is important to reset it here.
1517 mMenuIsDown = false;
1518 }
1519 switch (item.getItemId()) {
1520 // -- Main menu
1521 case R.id.new_tab_menu_id:
1522 openTabToHomePage();
1523 break;
1524
1525 case R.id.incognito_menu_id:
1526 openIncognitoTab();
1527 break;
1528
1529 case R.id.goto_menu_id:
1530 editUrl();
1531 break;
1532
1533 case R.id.bookmarks_menu_id:
1534 bookmarksOrHistoryPicker(false);
1535 break;
1536
1537 case R.id.active_tabs_menu_id:
1538 showActiveTabsPage();
1539 break;
1540
1541 case R.id.add_bookmark_menu_id:
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001542 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001543 break;
1544
1545 case R.id.stop_reload_menu_id:
1546 if (mInLoad) {
1547 stopLoading();
1548 } else {
1549 getCurrentTopWebView().reload();
1550 }
1551 break;
1552
1553 case R.id.back_menu_id:
1554 getCurrentTopWebView().goBack();
1555 break;
1556
1557 case R.id.forward_menu_id:
1558 getCurrentTopWebView().goForward();
1559 break;
1560
1561 case R.id.close_menu_id:
1562 // Close the subwindow if it exists.
1563 if (mTabControl.getCurrentSubWindow() != null) {
1564 dismissSubWindow(mTabControl.getCurrentTab());
1565 break;
1566 }
1567 closeCurrentTab();
1568 break;
1569
1570 case R.id.homepage_menu_id:
1571 Tab current = mTabControl.getCurrentTab();
1572 if (current != null) {
1573 dismissSubWindow(current);
1574 loadUrl(current.getWebView(), mSettings.getHomePage());
1575 }
1576 break;
1577
1578 case R.id.preferences_menu_id:
1579 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1580 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1581 getCurrentTopWebView().getUrl());
1582 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1583 break;
1584
1585 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001586 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001587 break;
1588
Leon Scrogginsac993842011-02-02 12:54:07 -05001589 case R.id.save_webarchive_menu_id:
1590 String state = Environment.getExternalStorageState();
1591 if (!Environment.MEDIA_MOUNTED.equals(state)) {
1592 Log.e(LOGTAG, "External storage not mounted");
1593 Toast.makeText(mActivity, R.string.webarchive_failed,
1594 Toast.LENGTH_SHORT).show();
1595 break;
1596 }
1597 final String directory = Environment.getExternalStoragePublicDirectory(
1598 Environment.DIRECTORY_DOWNLOADS) + File.separator;
1599 File dir = new File(directory);
1600 if (!dir.exists() && !dir.mkdirs()) {
1601 Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
1602 Toast.makeText(mActivity, R.string.webarchive_failed,
1603 Toast.LENGTH_SHORT).show();
1604 break;
1605 }
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001606 final WebView topWebView = getCurrentTopWebView();
Leon Scrogginsac993842011-02-02 12:54:07 -05001607 final String title = topWebView.getTitle();
John Reck51d8bad2011-02-28 15:47:47 -08001608 final String url = topWebView.getUrl();
Leon Scrogginsac993842011-02-02 12:54:07 -05001609 topWebView.saveWebArchive(directory, true,
1610 new ValueCallback<String>() {
1611 @Override
1612 public void onReceiveValue(final String value) {
1613 if (value != null) {
1614 File file = new File(value);
1615 final long length = file.length();
1616 if (file.exists() && length > 0) {
Leon Scroggins1cb96552011-02-11 14:22:57 -05001617 Toast.makeText(mActivity, R.string.webarchive_saved,
1618 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001619 final DownloadManager manager = (DownloadManager) mActivity
1620 .getSystemService(Context.DOWNLOAD_SERVICE);
1621 new Thread("Add WebArchive to download manager") {
1622 @Override
1623 public void run() {
Vasu Noria9e30a72011-03-07 11:37:34 -08001624 manager.addCompletedDownload(
1625 null == title ? value : title,
Leon Scrogginsac993842011-02-02 12:54:07 -05001626 value, true, "application/x-webarchive-xml",
1627 value, length, true);
1628 }
1629 }.start();
1630 return;
1631 }
1632 }
John Reck51d8bad2011-02-28 15:47:47 -08001633 DownloadHandler.onDownloadStartNoStream(mActivity,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001634 url, null, null, null, topWebView.isPrivateBrowsingEnabled());
Leon Scrogginsac993842011-02-02 12:54:07 -05001635 }
1636 });
1637 break;
1638
Michael Kolb8233fac2010-10-26 16:08:53 -07001639 case R.id.page_info_menu_id:
1640 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1641 false);
1642 break;
1643
1644 case R.id.classic_history_menu_id:
1645 bookmarksOrHistoryPicker(true);
1646 break;
1647
1648 case R.id.title_bar_share_page_url:
1649 case R.id.share_page_menu_id:
1650 Tab currentTab = mTabControl.getCurrentTab();
1651 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001652 return false;
1653 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001654 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001655 break;
1656
1657 case R.id.dump_nav_menu_id:
1658 getCurrentTopWebView().debugDump();
1659 break;
1660
1661 case R.id.dump_counters_menu_id:
1662 getCurrentTopWebView().dumpV8Counters();
1663 break;
1664
1665 case R.id.zoom_in_menu_id:
1666 getCurrentTopWebView().zoomIn();
1667 break;
1668
1669 case R.id.zoom_out_menu_id:
1670 getCurrentTopWebView().zoomOut();
1671 break;
1672
1673 case R.id.view_downloads_menu_id:
1674 viewDownloads();
1675 break;
1676
1677 case R.id.window_one_menu_id:
1678 case R.id.window_two_menu_id:
1679 case R.id.window_three_menu_id:
1680 case R.id.window_four_menu_id:
1681 case R.id.window_five_menu_id:
1682 case R.id.window_six_menu_id:
1683 case R.id.window_seven_menu_id:
1684 case R.id.window_eight_menu_id:
1685 {
1686 int menuid = item.getItemId();
1687 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1688 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1689 Tab desiredTab = mTabControl.getTab(id);
1690 if (desiredTab != null &&
1691 desiredTab != mTabControl.getCurrentTab()) {
1692 switchToTab(id);
1693 }
1694 break;
1695 }
1696 }
1697 }
1698 break;
1699
1700 default:
1701 return false;
1702 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001703 return true;
1704 }
1705
1706 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001707 // Let the History and Bookmark fragments handle menus they created.
1708 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1709 return false;
1710 }
1711
Michael Kolb8233fac2010-10-26 16:08:53 -07001712 int id = item.getItemId();
1713 boolean result = true;
1714 switch (id) {
1715 // For the context menu from the title bar
1716 case R.id.title_bar_copy_page_url:
1717 Tab currentTab = mTabControl.getCurrentTab();
1718 if (null == currentTab) {
1719 result = false;
1720 break;
1721 }
1722 WebView mainView = currentTab.getWebView();
1723 if (null == mainView) {
1724 result = false;
1725 break;
1726 }
1727 copy(mainView.getUrl());
1728 break;
1729 // -- Browser context menu
1730 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001731 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001732 case R.id.copy_link_context_menu_id:
1733 final WebView webView = getCurrentTopWebView();
1734 if (null == webView) {
1735 result = false;
1736 break;
1737 }
1738 final HashMap<String, WebView> hrefMap =
1739 new HashMap<String, WebView>();
1740 hrefMap.put("webview", webView);
1741 final Message msg = mHandler.obtainMessage(
1742 FOCUS_NODE_HREF, id, 0, hrefMap);
1743 webView.requestFocusNodeHref(msg);
1744 break;
1745
1746 default:
1747 // For other context menus
1748 result = onOptionsItemSelected(item);
1749 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001750 return result;
1751 }
1752
1753 /**
1754 * support programmatically opening the context menu
1755 */
1756 public void openContextMenu(View view) {
1757 mActivity.openContextMenu(view);
1758 }
1759
1760 /**
1761 * programmatically open the options menu
1762 */
1763 public void openOptionsMenu() {
1764 mActivity.openOptionsMenu();
1765 }
1766
1767 public boolean onMenuOpened(int featureId, Menu menu) {
1768 if (mOptionsMenuOpen) {
1769 if (mConfigChanged) {
1770 // We do not need to make any changes to the state of the
1771 // title bar, since the only thing that happened was a
1772 // change in orientation
1773 mConfigChanged = false;
1774 } else {
1775 if (!mExtendedMenuOpen) {
1776 mExtendedMenuOpen = true;
1777 mUi.onExtendedMenuOpened();
1778 } else {
1779 // Switching the menu back to icon view, so show the
1780 // title bar once again.
1781 mExtendedMenuOpen = false;
1782 mUi.onExtendedMenuClosed(mInLoad);
Michael Kolb8233fac2010-10-26 16:08:53 -07001783 }
1784 }
1785 } else {
1786 // The options menu is closed, so open it, and show the title
1787 mOptionsMenuOpen = true;
1788 mConfigChanged = false;
1789 mExtendedMenuOpen = false;
1790 mUi.onOptionsMenuOpened();
1791 }
1792 return true;
1793 }
1794
1795 public void onOptionsMenuClosed(Menu menu) {
1796 mOptionsMenuOpen = false;
1797 mUi.onOptionsMenuClosed(mInLoad);
1798 }
1799
1800 public void onContextMenuClosed(Menu menu) {
1801 mUi.onContextMenuClosed(menu, mInLoad);
1802 }
1803
1804 // Helper method for getting the top window.
1805 @Override
1806 public WebView getCurrentTopWebView() {
1807 return mTabControl.getCurrentTopWebView();
1808 }
1809
1810 @Override
1811 public WebView getCurrentWebView() {
1812 return mTabControl.getCurrentWebView();
1813 }
1814
1815 /*
1816 * This method is called as a result of the user selecting the options
1817 * menu to see the download window. It shows the download window on top of
1818 * the current window.
1819 */
1820 void viewDownloads() {
1821 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1822 mActivity.startActivity(intent);
1823 }
1824
1825 // action mode
1826
1827 void onActionModeStarted(ActionMode mode) {
1828 mUi.onActionModeStarted(mode);
1829 mActionMode = mode;
1830 }
1831
1832 /*
1833 * True if a custom ActionMode (i.e. find or select) is in use.
1834 */
1835 @Override
1836 public boolean isInCustomActionMode() {
1837 return mActionMode != null;
1838 }
1839
1840 /*
1841 * End the current ActionMode.
1842 */
1843 @Override
1844 public void endActionMode() {
1845 if (mActionMode != null) {
1846 mActionMode.finish();
1847 }
1848 }
1849
1850 /*
1851 * Called by find and select when they are finished. Replace title bars
1852 * as necessary.
1853 */
1854 public void onActionModeFinished(ActionMode mode) {
1855 if (!isInCustomActionMode()) return;
1856 mUi.onActionModeFinished(mInLoad);
1857 mActionMode = null;
1858 }
1859
1860 boolean isInLoad() {
1861 return mInLoad;
1862 }
1863
1864 // bookmark handling
1865
1866 /**
1867 * add the current page as a bookmark to the given folder id
1868 * @param folderId use -1 for the default folder
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001869 * @param canBeAnEdit If true, check to see whether the site is already
1870 * bookmarked, and if it is, edit that bookmark. If false, and
1871 * the site is already bookmarked, do not attempt to edit the
1872 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001873 */
1874 @Override
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001875 public void bookmarkCurrentPage(long folderId, boolean canBeAnEdit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001876 Intent i = new Intent(mActivity,
1877 AddBookmarkPage.class);
1878 WebView w = getCurrentTopWebView();
1879 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1880 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1881 String touchIconUrl = w.getTouchIconUrl();
1882 if (touchIconUrl != null) {
1883 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1884 WebSettings settings = w.getSettings();
1885 if (settings != null) {
1886 i.putExtra(AddBookmarkPage.USER_AGENT,
1887 settings.getUserAgentString());
1888 }
1889 }
1890 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1891 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1892 getDesiredThumbnailHeight(mActivity)));
1893 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1894 i.putExtra(BrowserContract.Bookmarks.PARENT,
1895 folderId);
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001896 if (canBeAnEdit) {
1897 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1898 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001899 // Put the dialog at the upper right of the screen, covering the
1900 // star on the title bar.
1901 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1902 mActivity.startActivity(i);
1903 }
1904
1905 // file chooser
1906 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1907 mUploadHandler = new UploadHandler(this);
1908 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1909 }
1910
1911 // thumbnails
1912
1913 /**
1914 * Return the desired width for thumbnail screenshots, which are stored in
1915 * the database, and used on the bookmarks screen.
1916 * @param context Context for finding out the density of the screen.
1917 * @return desired width for thumbnail screenshot.
1918 */
1919 static int getDesiredThumbnailWidth(Context context) {
1920 return context.getResources().getDimensionPixelOffset(
1921 R.dimen.bookmarkThumbnailWidth);
1922 }
1923
1924 /**
1925 * Return the desired height for thumbnail screenshots, which are stored in
1926 * the database, and used on the bookmarks screen.
1927 * @param context Context for finding out the density of the screen.
1928 * @return desired height for thumbnail screenshot.
1929 */
1930 static int getDesiredThumbnailHeight(Context context) {
1931 return context.getResources().getDimensionPixelOffset(
1932 R.dimen.bookmarkThumbnailHeight);
1933 }
1934
Michael Kolb1acef692011-03-08 14:12:06 -08001935 static Bitmap createScreenshot(Tab tab, int width, int height) {
1936 if ((tab != null) && (tab.getWebView() != null)) {
1937 return createScreenshot(tab.getWebView(), width, height);
1938 }
1939 return null;
1940 }
1941
Michael Kolb8233fac2010-10-26 16:08:53 -07001942 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001943 // We render to a bitmap 2x the desired size so that we can then
1944 // re-scale it with filtering since canvas.scale doesn't filter
1945 // This helps reduce aliasing at the cost of being slightly blurry
1946 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001947 Picture thumbnail = view.capturePicture();
1948 if (thumbnail == null) {
1949 return null;
1950 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001951 width *= filter_scale;
1952 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001953 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1954 Canvas canvas = new Canvas(bm);
1955 // May need to tweak these values to determine what is the
1956 // best scale factor
1957 int thumbnailWidth = thumbnail.getWidth();
1958 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001959 float scaleFactor = 1.0f;
Michael Kolbeb95db42011-03-03 10:38:40 -08001960 if (thumbnailWidth > 0 && thumbnailHeight > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001961 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001962 } else {
1963 return null;
1964 }
John Reckfe49ab42010-11-16 17:09:37 -08001965
Michael Kolbeb95db42011-03-03 10:38:40 -08001966 float scaleFactorY = (float) height / (float)thumbnailHeight;
1967 if (scaleFactorY > scaleFactor) {
1968 // The picture is narrower than the requested AR
1969 // Center the thumnail and crop the sides
1970 scaleFactor = scaleFactorY;
John Reckfe49ab42010-11-16 17:09:37 -08001971 float wx = (thumbnailWidth * scaleFactor) - width;
1972 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001973 }
1974
John Reckfe49ab42010-11-16 17:09:37 -08001975 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001976
1977 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001978 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
1979 height / filter_scale, true);
1980 bm.recycle();
1981 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001982 }
1983
John Reck34ef2672011-02-10 11:30:55 -08001984 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001985 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07001986 // FIXME: Would like to make sure there is actually something to
1987 // draw, but the API for that (WebViewCore.pictureReady()) is not
1988 // currently accessible here.
1989
John Reck34ef2672011-02-10 11:30:55 -08001990 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08001991 if (view == null) {
1992 // Tab was destroyed
1993 return;
1994 }
John Reck34ef2672011-02-10 11:30:55 -08001995 final String url = tab.getUrl();
1996 final String originalUrl = view.getOriginalUrl();
1997
1998 if (TextUtils.isEmpty(url)) {
1999 return;
2000 }
2001
2002 // Only update thumbnails for web urls (http(s)://), not for
2003 // about:, javascript:, data:, etc...
2004 // Unless it is a bookmarked site, then always update
2005 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2006 return;
2007 }
2008
Michael Kolb8233fac2010-10-26 16:08:53 -07002009 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2010 getDesiredThumbnailHeight(mActivity));
2011 if (bm == null) {
2012 return;
2013 }
2014
2015 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002016 new AsyncTask<Void, Void, Void>() {
2017 @Override
2018 protected Void doInBackground(Void... unused) {
2019 Cursor cursor = null;
2020 try {
2021 // TODO: Clean this up
2022 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2023 if (cursor != null && cursor.moveToFirst()) {
2024 final ByteArrayOutputStream os =
2025 new ByteArrayOutputStream();
2026 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002027
John Reck34ef2672011-02-10 11:30:55 -08002028 ContentValues values = new ContentValues();
2029 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002030
John Reck34ef2672011-02-10 11:30:55 -08002031 do {
John Reck617fd832011-02-16 14:35:59 -08002032 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002033 cr.update(Images.CONTENT_URI, values, null, null);
2034 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002035 }
John Reck34ef2672011-02-10 11:30:55 -08002036 } catch (IllegalStateException e) {
2037 // Ignore
2038 } finally {
2039 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002040 }
John Reck34ef2672011-02-10 11:30:55 -08002041 return null;
2042 }
2043 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002044 }
2045
2046 private class Copy implements OnMenuItemClickListener {
2047 private CharSequence mText;
2048
2049 public boolean onMenuItemClick(MenuItem item) {
2050 copy(mText);
2051 return true;
2052 }
2053
2054 public Copy(CharSequence toCopy) {
2055 mText = toCopy;
2056 }
2057 }
2058
Leon Scroggins63c02662010-11-18 15:16:27 -05002059 private static class Download implements OnMenuItemClickListener {
2060 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002061 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002062 private boolean mPrivateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002063
2064 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002065 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002066 null, null, mPrivateBrowsing);
Michael Kolb8233fac2010-10-26 16:08:53 -07002067 return true;
2068 }
2069
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002070 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002071 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002072 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002073 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002074 }
2075 }
2076
Cary Clark8974d282010-11-22 10:46:05 -05002077 private static class SelectText implements OnMenuItemClickListener {
2078 private WebView mWebView;
2079
2080 public boolean onMenuItemClick(MenuItem item) {
2081 if (mWebView != null) {
2082 return mWebView.selectText();
2083 }
2084 return false;
2085 }
2086
2087 public SelectText(WebView webView) {
2088 mWebView = webView;
2089 }
2090
2091 }
2092
Michael Kolb8233fac2010-10-26 16:08:53 -07002093 /********************** TODO: UI stuff *****************************/
2094
2095 // these methods have been copied, they still need to be cleaned up
2096
2097 /****************** tabs ***************************************************/
2098
2099 // basic tab interactions:
2100
2101 // it is assumed that tabcontrol already knows about the tab
2102 protected void addTab(Tab tab) {
2103 mUi.addTab(tab);
2104 }
2105
2106 protected void removeTab(Tab tab) {
2107 mUi.removeTab(tab);
2108 mTabControl.removeTab(tab);
2109 }
2110
2111 protected void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002112 // monkey protection against delayed start
2113 if (tab != null) {
2114 mTabControl.setCurrentTab(tab);
2115 // the tab is guaranteed to have a webview after setCurrentTab
2116 mUi.setActiveTab(tab);
2117 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002118 }
2119
2120 protected void closeEmptyChildTab() {
2121 Tab current = mTabControl.getCurrentTab();
2122 if (current != null
2123 && current.getWebView().copyBackForwardList().getSize() == 0) {
2124 Tab parent = current.getParentTab();
2125 if (parent != null) {
2126 switchToTab(mTabControl.getTabIndex(parent));
2127 closeTab(current);
2128 }
2129 }
2130 }
2131
2132 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002133 // Dismiss the subwindow if applicable.
2134 dismissSubWindow(appTab);
2135 // Since we might kill the WebView, remove it from the
2136 // content view first.
2137 mUi.detachTab(appTab);
2138 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002139 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002140 // TODO: analyze why the remove and add are necessary
2141 mUi.attachTab(appTab);
2142 if (mTabControl.getCurrentTab() != appTab) {
2143 switchToTab(mTabControl.getTabIndex(appTab));
John Reck30c714c2010-12-16 17:30:34 -08002144 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002145 } else {
2146 // If the tab was the current tab, we have to attach
2147 // it to the view system again.
2148 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002149 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002150 }
2151 }
2152
2153 // Remove the sub window if it exists. Also called by TabControl when the
2154 // user clicks the 'X' to dismiss a sub window.
2155 public void dismissSubWindow(Tab tab) {
2156 removeSubWindow(tab);
2157 // dismiss the subwindow. This will destroy the WebView.
2158 tab.dismissSubWindow();
2159 getCurrentTopWebView().requestFocus();
2160 }
2161
2162 @Override
2163 public void removeSubWindow(Tab t) {
2164 if (t.getSubWebView() != null) {
2165 mUi.removeSubWindow(t.getSubViewContainer());
2166 }
2167 }
2168
2169 @Override
2170 public void attachSubWindow(Tab tab) {
2171 if (tab.getSubWebView() != null) {
2172 mUi.attachSubWindow(tab.getSubViewContainer());
2173 getCurrentTopWebView().requestFocus();
2174 }
2175 }
2176
Michael Kolb843510f2010-12-09 10:51:49 -08002177 @Override
2178 public Tab openTabToHomePage() {
2179 // check for max tabs
2180 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002181 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2182 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002183 } else {
2184 mUi.showMaxTabsWarning();
2185 return null;
2186 }
2187 }
2188
Michael Kolb18eb3772010-12-10 14:29:51 -08002189 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2190 if (mSettings.openInBackground() && !forceForeground) {
2191 Tab tab = mTabControl.createNewTab(false, null, null,
2192 (parent != null) && parent.isPrivateBrowsingEnabled());
2193 if (tab != null) {
2194 addTab(tab);
2195 WebView view = tab.getWebView();
2196 loadUrl(view, url);
2197 }
2198 return tab;
2199 } else {
2200 return openTabAndShow(parent, new UrlData(url), false, null);
2201 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002202 }
2203
Michael Kolb18eb3772010-12-10 14:29:51 -08002204
Michael Kolb8233fac2010-10-26 16:08:53 -07002205 // This method does a ton of stuff. It will attempt to create a new tab
2206 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2207 // url isn't null, it will load the given url.
Patrick Scottcd135082011-01-31 18:21:58 -05002208 public Tab openTabAndShow(Tab parent, final UrlData urlData,
2209 boolean closeOnExit, String appId) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002210 final Tab currentTab = mTabControl.getCurrentTab();
2211 if (mTabControl.canCreateNewTab()) {
2212 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Michael Kolb18eb3772010-12-10 14:29:51 -08002213 urlData.mUrl,
2214 (parent != null) && parent.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -07002215 WebView webview = tab.getWebView();
2216 // We must set the new tab as the current tab to reflect the old
2217 // animation behavior.
2218 addTab(tab);
2219 setActiveTab(tab);
Patrick Scottd43e75a2011-03-14 14:47:23 -04002220 if (!urlData.isEmpty()) {
2221 loadUrlDataIn(tab, urlData);
2222 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002223 return tab;
2224 } else {
2225 // Get rid of the subwindow if it exists
2226 dismissSubWindow(currentTab);
2227 if (!urlData.isEmpty()) {
2228 // Load the given url.
2229 loadUrlDataIn(currentTab, urlData);
2230 }
2231 return currentTab;
2232 }
2233 }
2234
Michael Kolb8233fac2010-10-26 16:08:53 -07002235 @Override
2236 public Tab openIncognitoTab() {
2237 if (mTabControl.canCreateNewTab()) {
2238 Tab currentTab = mTabControl.getCurrentTab();
Michael Kolb8e7178d2011-01-26 19:13:36 -08002239 Tab tab = mTabControl.createNewTab(false, null,
John Reck4bfc0db2011-01-27 17:47:12 -08002240 null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07002241 addTab(tab);
2242 setActiveTab(tab);
John Reck4bfc0db2011-01-27 17:47:12 -08002243 loadUrlDataIn(tab, new UrlData("browser:incognito"));
Michael Kolb8233fac2010-10-26 16:08:53 -07002244 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002245 } else {
2246 mUi.showMaxTabsWarning();
2247 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002248 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002249 }
2250
2251 /**
2252 * @param index Index of the tab to change to, as defined by
2253 * mTabControl.getTabIndex(Tab t).
2254 * @return boolean True if we successfully switched to a different tab. If
2255 * the indexth tab is null, or if that tab is the same as
2256 * the current one, return false.
2257 */
2258 @Override
2259 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002260 // hide combo view if open
2261 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002262 Tab tab = mTabControl.getTab(index);
2263 Tab currentTab = mTabControl.getCurrentTab();
2264 if (tab == null || tab == currentTab) {
2265 return false;
2266 }
2267 setActiveTab(tab);
2268 return true;
2269 }
2270
2271 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002272 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002273 // hide combo view if open
2274 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002275 final Tab current = mTabControl.getCurrentTab();
2276 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002277 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002278 return;
2279 }
2280 final Tab parent = current.getParentTab();
2281 int indexToShow = -1;
2282 if (parent != null) {
2283 indexToShow = mTabControl.getTabIndex(parent);
2284 } else {
2285 final int currentIndex = mTabControl.getCurrentIndex();
2286 // Try to move to the tab to the right
2287 indexToShow = currentIndex + 1;
2288 if (indexToShow > mTabControl.getTabCount() - 1) {
2289 // Try to move to the tab to the left
2290 indexToShow = currentIndex - 1;
2291 }
2292 }
2293 if (switchToTab(indexToShow)) {
2294 // Close window
2295 closeTab(current);
2296 }
2297 }
2298
2299 /**
2300 * Close the tab, remove its associated title bar, and adjust mTabControl's
2301 * current tab to a valid value.
2302 */
2303 @Override
2304 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002305 // hide combo view if open
2306 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002307 int currentIndex = mTabControl.getCurrentIndex();
2308 int removeIndex = mTabControl.getTabIndex(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002309 Tab newtab = mTabControl.getTab(currentIndex);
2310 setActiveTab(newtab);
Michael Kolb2d59c322011-01-25 13:18:55 -08002311 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002312 }
2313
2314 /**************** TODO: Url loading clean up *******************************/
2315
2316 // Called when loading from context menu or LOAD_URL message
2317 protected void loadUrlFromContext(WebView view, String url) {
2318 // In case the user enters nothing.
2319 if (url != null && url.length() != 0 && view != null) {
2320 url = UrlUtils.smartUrlFilter(url);
2321 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2322 loadUrl(view, url);
2323 }
2324 }
2325 }
2326
2327 /**
2328 * Load the URL into the given WebView and update the title bar
2329 * to reflect the new load. Call this instead of WebView.loadUrl
2330 * directly.
2331 * @param view The WebView used to load url.
2332 * @param url The URL to load.
2333 */
2334 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002335 view.loadUrl(url);
2336 }
2337
2338 /**
2339 * Load UrlData into a Tab and update the title bar to reflect the new
2340 * load. Call this instead of UrlData.loadIn directly.
2341 * @param t The Tab used to load.
2342 * @param data The UrlData being loaded.
2343 */
2344 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002345 data.loadIn(t);
2346 }
2347
John Reck30c714c2010-12-16 17:30:34 -08002348 @Override
2349 public void onUserCanceledSsl(Tab tab) {
2350 WebView web = tab.getWebView();
2351 // TODO: Figure out the "right" behavior
2352 if (web.canGoBack()) {
2353 web.goBack();
2354 } else {
2355 web.loadUrl(mSettings.getHomePage());
2356 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002357 }
2358
2359 void goBackOnePageOrQuit() {
2360 Tab current = mTabControl.getCurrentTab();
2361 if (current == null) {
2362 /*
2363 * Instead of finishing the activity, simply push this to the back
2364 * of the stack and let ActivityManager to choose the foreground
2365 * activity. As BrowserActivity is singleTask, it will be always the
2366 * root of the task. So we can use either true or false for
2367 * moveTaskToBack().
2368 */
2369 mActivity.moveTaskToBack(true);
2370 return;
2371 }
2372 WebView w = current.getWebView();
2373 if (w.canGoBack()) {
2374 w.goBack();
2375 } else {
2376 // Check to see if we are closing a window that was created by
2377 // another window. If so, we switch back to that window.
2378 Tab parent = current.getParentTab();
2379 if (parent != null) {
2380 switchToTab(mTabControl.getTabIndex(parent));
2381 // Now we close the other tab
2382 closeTab(current);
2383 } else {
2384 if (current.closeOnExit()) {
Patrick Scottfc1518a2011-02-28 13:57:03 -05002385 // This will finish the activity if there is only one tab
2386 // open or it will switch to the next available tab if
2387 // available.
Michael Kolb96683f72011-02-15 14:24:35 -08002388 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002389 }
2390 /*
2391 * Instead of finishing the activity, simply push this to the back
2392 * of the stack and let ActivityManager to choose the foreground
2393 * activity. As BrowserActivity is singleTask, it will be always the
2394 * root of the task. So we can use either true or false for
2395 * moveTaskToBack().
2396 */
2397 mActivity.moveTaskToBack(true);
2398 }
2399 }
2400 }
2401
2402 /**
2403 * Feed the previously stored results strings to the BrowserProvider so that
2404 * the SearchDialog will show them instead of the standard searches.
2405 * @param result String to show on the editable line of the SearchDialog.
2406 */
2407 @Override
2408 public void showVoiceSearchResults(String result) {
2409 ContentProviderClient client = mActivity.getContentResolver()
2410 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2411 ContentProvider prov = client.getLocalContentProvider();
2412 BrowserProvider bp = (BrowserProvider) prov;
2413 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2414 client.release();
2415
2416 Bundle bundle = createGoogleSearchSourceBundle(
2417 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2418 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2419 startSearch(result, false, bundle, false);
2420 }
2421
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002422 @Override
2423 public void startSearch(String url) {
2424 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
2425 null, false);
2426 }
2427
Michael Kolb8233fac2010-10-26 16:08:53 -07002428 private void startSearch(String initialQuery, boolean selectInitialQuery,
2429 Bundle appSearchData, boolean globalSearch) {
2430 if (appSearchData == null) {
2431 appSearchData = createGoogleSearchSourceBundle(
2432 GOOGLE_SEARCH_SOURCE_TYPE);
2433 }
2434
2435 SearchEngine searchEngine = mSettings.getSearchEngine();
2436 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2437 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2438 }
2439 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2440 globalSearch);
2441 }
2442
2443 private Bundle createGoogleSearchSourceBundle(String source) {
2444 Bundle bundle = new Bundle();
2445 bundle.putString(Search.SOURCE, source);
2446 return bundle;
2447 }
2448
2449 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002450 * helper method for key handler
2451 * returns the current tab if it can't advance
2452 */
2453 private int getNextTabIndex() {
2454 return Math.min(mTabControl.getTabCount() - 1,
2455 mTabControl.getCurrentIndex() + 1);
2456 }
2457
2458 /**
2459 * helper method for key handler
2460 * returns the current tab if it can't advance
2461 */
2462 private int getPrevTabIndex() {
2463 return Math.max(0, mTabControl.getCurrentIndex() - 1);
2464 }
2465
2466 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002467 * handle key events in browser
2468 *
2469 * @param keyCode
2470 * @param event
2471 * @return true if handled, false to pass to super
2472 */
2473 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002474 boolean noModifiers = event.hasNoModifiers();
2475
Michael Kolb8233fac2010-10-26 16:08:53 -07002476 // Even if MENU is already held down, we need to call to super to open
2477 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002478 if (!noModifiers
2479 && ((KeyEvent.KEYCODE_MENU == keyCode)
2480 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2481 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002482 mMenuIsDown = true;
2483 return false;
2484 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002485
Cary Clark8ff8c662010-12-29 15:03:05 -05002486 WebView webView = getCurrentTopWebView();
2487 if (webView == null) return false;
2488
Cary Clark160bbb92011-01-10 11:17:07 -05002489 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2490 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002491
Michael Kolb8233fac2010-10-26 16:08:53 -07002492 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002493 case KeyEvent.KEYCODE_TAB:
2494 if (event.isCtrlPressed()) {
2495 if (event.isShiftPressed()) {
2496 // prev tab
2497 switchToTab(getPrevTabIndex());
2498 } else {
2499 // next tab
2500 switchToTab(getNextTabIndex());
2501 }
2502 return true;
2503 }
2504 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002505 case KeyEvent.KEYCODE_SPACE:
2506 // WebView/WebTextView handle the keys in the KeyDown. As
2507 // the Activity's shortcut keys are only handled when WebView
2508 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002509 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002510 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002511 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002512 pageDown();
2513 }
2514 return true;
2515 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002516 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002517 event.startTracking();
2518 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002519 case KeyEvent.KEYCODE_DPAD_LEFT:
2520 if (ctrl) {
2521 webView.goBack();
2522 return true;
2523 }
2524 break;
2525 case KeyEvent.KEYCODE_DPAD_RIGHT:
2526 if (ctrl) {
2527 webView.goForward();
2528 return true;
2529 }
2530 break;
2531 case KeyEvent.KEYCODE_A:
2532 if (ctrl) {
2533 webView.selectAll();
2534 return true;
2535 }
2536 break;
Michael Kolba4183062011-01-16 10:43:21 -08002537// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002538 case KeyEvent.KEYCODE_C:
2539 if (ctrl) {
2540 webView.copySelection();
2541 return true;
2542 }
2543 break;
Michael Kolba4183062011-01-16 10:43:21 -08002544// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002545// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002546// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002547// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002548// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002549// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002550// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002551// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002552// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002553// case KeyEvent.KEYCODE_M: // unused
2554// case KeyEvent.KEYCODE_N: // in Chrome: new window
2555// case KeyEvent.KEYCODE_O: // in Chrome: open file
2556// case KeyEvent.KEYCODE_P: // in Chrome: print page
2557// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002558// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002559// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2560 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002561 // we can't use the ctrl/shift flags, they check for
2562 // exclusive use of a modifier
2563 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002564 if (event.isShiftPressed()) {
2565 openIncognitoTab();
2566 } else {
2567 openTabToHomePage();
2568 }
2569 return true;
2570 }
2571 break;
2572// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2573// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb1a2eba42011-03-16 16:42:49 -07002574 case KeyEvent.KEYCODE_W: // in Chrome: close tab
2575 if (ctrl) {
2576 closeCurrentTab();
2577 return true;
2578 }
2579 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002580// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2581// case KeyEvent.KEYCODE_Y: // unused
2582// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002583 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002584 // it is a regular key and webview is not null
2585 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002586 }
2587
John Recke6bf4ab2011-02-24 15:48:05 -08002588 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2589 switch(keyCode) {
2590 case KeyEvent.KEYCODE_BACK:
2591 if (mUi.showsWeb()) {
2592 bookmarksOrHistoryPicker(true);
2593 return true;
2594 }
2595 break;
2596 }
2597 return false;
2598 }
2599
Michael Kolb8233fac2010-10-26 16:08:53 -07002600 boolean onKeyUp(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002601 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002602 switch(keyCode) {
2603 case KeyEvent.KEYCODE_MENU:
2604 mMenuIsDown = false;
2605 break;
2606 case KeyEvent.KEYCODE_BACK:
2607 if (event.isTracking() && !event.isCanceled()) {
2608 onBackKey();
2609 return true;
2610 }
2611 break;
2612 }
2613 return false;
2614 }
2615
2616 public boolean isMenuDown() {
2617 return mMenuIsDown;
2618 }
2619
Ben Murdoch8029a772010-11-16 11:58:21 +00002620 public void setupAutoFill(Message message) {
2621 // Open the settings activity at the AutoFill profile fragment so that
2622 // the user can create a new profile. When they return, we will dispatch
2623 // the message so that we can autofill the form using their new profile.
2624 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2625 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2626 AutoFillSettingsFragment.class.getName());
2627 mAutoFillSetupMessage = message;
2628 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2629 }
John Reckb3417f02011-01-14 11:01:05 -08002630
2631 @Override
2632 public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
2633 mOptionsMenuHandler = handler;
2634 }
2635
2636 @Override
2637 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
2638 if (mOptionsMenuHandler == handler) {
2639 mOptionsMenuHandler = null;
2640 }
2641 }
2642
Narayan Kamath5119edd2011-02-23 15:49:17 +00002643 @Override
2644 public void registerDropdownChangeListener(DropdownChangeListener d) {
2645 mUi.registerDropdownChangeListener(d);
2646 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002647}