blob: 2f47cad6f0c6b5d5b39d3870dff688d9139c5b4f [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;
John Reck847b5322011-04-14 17:02:18 -070050import android.os.Parcel;
Michael Kolb8233fac2010-10-26 16:08:53 -070051import android.os.PowerManager;
52import android.os.PowerManager.WakeLock;
Ben Murdoch8029a772010-11-16 11:58:21 +000053import android.preference.PreferenceActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -070054import android.provider.Browser;
55import android.provider.BrowserContract;
Michael Kolb8233fac2010-10-26 16:08:53 -070056import android.provider.BrowserContract.Images;
57import android.provider.ContactsContract;
58import android.provider.ContactsContract.Intents.Insert;
Michael Kolbcfa3af52010-12-14 10:36:11 -080059import android.speech.RecognizerIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070060import android.speech.RecognizerResultsIntent;
61import android.text.TextUtils;
62import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080063import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070064import android.view.ActionMode;
65import android.view.ContextMenu;
66import android.view.ContextMenu.ContextMenuInfo;
67import android.view.Gravity;
68import android.view.KeyEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070069import android.view.Menu;
70import android.view.MenuInflater;
71import android.view.MenuItem;
72import android.view.MenuItem.OnMenuItemClickListener;
73import android.view.View;
74import android.webkit.CookieManager;
75import android.webkit.CookieSyncManager;
76import android.webkit.HttpAuthHandler;
77import android.webkit.SslErrorHandler;
78import android.webkit.ValueCallback;
79import android.webkit.WebChromeClient;
80import android.webkit.WebIconDatabase;
81import android.webkit.WebSettings;
82import android.webkit.WebView;
Leon Scrogginsac993842011-02-02 12:54:07 -050083import android.widget.Toast;
Michael Kolb8233fac2010-10-26 16:08:53 -070084
85import java.io.ByteArrayOutputStream;
86import java.io.File;
John Reck847b5322011-04-14 17:02:18 -070087import java.io.FileOutputStream;
Michael Kolb8233fac2010-10-26 16:08:53 -070088import java.net.URLEncoder;
89import java.util.Calendar;
90import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -080091import java.util.List;
Michael Kolb8233fac2010-10-26 16:08:53 -070092
93/**
94 * Controller for browser
95 */
96public class Controller
97 implements WebViewController, UiController {
98
99 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800100 private static final String SEND_APP_ID_EXTRA =
101 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
102
Michael Kolb8233fac2010-10-26 16:08:53 -0700103
104 // public message ids
105 public final static int LOAD_URL = 1001;
106 public final static int STOP_LOAD = 1002;
107
108 // Message Ids
109 private static final int FOCUS_NODE_HREF = 102;
110 private static final int RELEASE_WAKELOCK = 107;
111
112 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
113
114 private static final int OPEN_BOOKMARKS = 201;
115
116 private static final int EMPTY_MENU = -1;
117
Michael Kolb8233fac2010-10-26 16:08:53 -0700118 // activity requestCode
119 final static int PREFERENCES_PAGE = 3;
120 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000121 final static int AUTOFILL_SETUP = 5;
122
Michael Kolb8233fac2010-10-26 16:08:53 -0700123 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
124
125 // As the ids are dynamically created, we can't guarantee that they will
126 // be in sequence, so this static array maps ids to a window number.
127 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
128 { R.id.window_one_menu_id, R.id.window_two_menu_id,
129 R.id.window_three_menu_id, R.id.window_four_menu_id,
130 R.id.window_five_menu_id, R.id.window_six_menu_id,
131 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
132
133 // "source" parameter for Google search through search key
134 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
135 // "source" parameter for Google search through simplily type
136 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
137
138 private Activity mActivity;
139 private UI mUi;
140 private TabControl mTabControl;
141 private BrowserSettings mSettings;
142 private WebViewFactory mFactory;
John Reckb3417f02011-01-14 11:01:05 -0800143 private OptionsMenuHandler mOptionsMenuHandler = null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700144
145 private WakeLock mWakeLock;
146
147 private UrlHandler mUrlHandler;
148 private UploadHandler mUploadHandler;
149 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700150 private PageDialogsHandler mPageDialogsHandler;
151 private NetworkStateHandler mNetworkHandler;
152
Ben Murdoch8029a772010-11-16 11:58:21 +0000153 private Message mAutoFillSetupMessage;
154
Michael Kolb8233fac2010-10-26 16:08:53 -0700155 private boolean mShouldShowErrorConsole;
156
157 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
158
159 // FIXME, temp address onPrepareMenu performance problem.
160 // When we move everything out of view, we should rewrite this.
161 private int mCurrentMenuState = 0;
162 private int mMenuState = R.id.MAIN_MENU;
163 private int mOldMenuState = EMPTY_MENU;
164 private Menu mCachedMenu;
165
Michael Kolb8233fac2010-10-26 16:08:53 -0700166 private boolean mMenuIsDown;
167
168 // For select and find, we keep track of the ActionMode so that
169 // finish() can be called as desired.
170 private ActionMode mActionMode;
171
172 /**
173 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
174 * of whether the configuration has changed. The first onMenuOpened call
175 * after a configuration change is simply a reopening of the same menu
176 * (i.e. mIconView did not change).
177 */
178 private boolean mConfigChanged;
179
180 /**
181 * Keeps track of whether the options menu is open. This is important in
182 * determining whether to show or hide the title bar overlay
183 */
184 private boolean mOptionsMenuOpen;
185
186 /**
187 * Whether or not the options menu is in its bigger, popup menu form. When
188 * true, we want the title bar overlay to be gone. When false, we do not.
189 * Only meaningful if mOptionsMenuOpen is true.
190 */
191 private boolean mExtendedMenuOpen;
192
193 private boolean mInLoad;
194
195 private boolean mActivityPaused = true;
196 private boolean mLoadStopped;
197
198 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500199 // Checks to see when the bookmarks database has changed, and updates the
200 // Tabs' notion of whether they represent bookmarked sites.
201 private ContentObserver mBookmarksObserver;
John Reck0ebd3ac2010-12-09 11:14:04 -0800202 private DataController mDataController;
John Reck847b5322011-04-14 17:02:18 -0700203 private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700204
205 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
206 @Override
207 public Void doInBackground(File... files) {
208 if (files != null) {
209 for (File f : files) {
210 if (!f.delete()) {
211 Log.e(LOGTAG, f.getPath() + " was not deleted");
212 }
213 }
214 }
215 return null;
216 }
217 }
218
219 public Controller(Activity browser) {
220 mActivity = browser;
221 mSettings = BrowserSettings.getInstance();
John Reck0ebd3ac2010-12-09 11:14:04 -0800222 mDataController = DataController.getInstance(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700223 mTabControl = new TabControl(this);
224 mSettings.setController(this);
John Reck847b5322011-04-14 17:02:18 -0700225 mCrashRecoveryHandler = new CrashRecoveryHandler(this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700226
227 mUrlHandler = new UrlHandler(this);
228 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700229 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
230
231 PowerManager pm = (PowerManager) mActivity
232 .getSystemService(Context.POWER_SERVICE);
233 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
234
235 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500236 mBookmarksObserver = new ContentObserver(mHandler) {
237 @Override
238 public void onChange(boolean selfChange) {
239 int size = mTabControl.getTabCount();
240 for (int i = 0; i < size; i++) {
241 mTabControl.getTab(i).updateBookmarkedStatus();
242 }
243 }
244
245 };
246 browser.getContentResolver().registerContentObserver(
247 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700248
249 mNetworkHandler = new NetworkStateHandler(mActivity, this);
250 // Start watching the default geolocation permissions
251 mSystemAllowGeolocationOrigins =
252 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
253 mSystemAllowGeolocationOrigins.start();
254
255 retainIconsOnStartup();
256 }
257
Patrick Scott7d50a932011-02-04 09:27:26 -0500258 void start(final Bundle icicle, final Intent intent) {
John Reck847b5322011-04-14 17:02:18 -0700259 if (icicle != null) {
260 mCrashRecoveryHandler.clearState();
261 doStart(icicle, intent);
262 } else {
263 mCrashRecoveryHandler.startRecovery(intent);
264 }
265 }
266
267 void doStart(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700268 // Unless the last browser usage was within 24 hours, destroy any
269 // remaining incognito tabs.
270
271 Calendar lastActiveDate = icicle != null ?
272 (Calendar) icicle.getSerializable("lastActiveDate") : null;
273 Calendar today = Calendar.getInstance();
274 Calendar yesterday = Calendar.getInstance();
275 yesterday.add(Calendar.DATE, -1);
276
Patrick Scott7d50a932011-02-04 09:27:26 -0500277 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700278 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800279 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700280
Patrick Scott7d50a932011-02-04 09:27:26 -0500281 // Find out if we will restore any state and remember the tab.
282 final int currentTab =
283 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000284
Patrick Scott7d50a932011-02-04 09:27:26 -0500285 if (currentTab == -1) {
286 // Not able to restore so we go ahead and clear session cookies. We
287 // must do this before trying to login the user as we don't want to
288 // clear any session cookies set during login.
289 CookieManager.getInstance().removeSessionCookie();
290 }
291
Patrick Scottd43e75a2011-03-14 14:47:23 -0400292 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500293 new Runnable() {
294 @Override public void run() {
John Reck847b5322011-04-14 17:02:18 -0700295 onPreloginFinished(icicle, intent, currentTab, restoreIncognitoTabs);
Patrick Scott7d50a932011-02-04 09:27:26 -0500296 }
297 });
298 }
299
John Reck847b5322011-04-14 17:02:18 -0700300 private void onPreloginFinished(Bundle icicle, Intent intent, int currentTab,
Patrick Scott7d50a932011-02-04 09:27:26 -0500301 boolean restoreIncognitoTabs) {
302 if (currentTab == -1) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700303 final Bundle extra = intent.getExtras();
304 // Create an initial tab.
305 // If the intent is ACTION_VIEW and data is not null, the Browser is
306 // invoked to view the content by another application. In this case,
307 // the tab will be close when exit.
308 UrlData urlData = mIntentHandler.getUrlDataFromIntent(intent);
309
310 String action = intent.getAction();
311 final Tab t = mTabControl.createNewTab(
312 (Intent.ACTION_VIEW.equals(action) &&
313 intent.getData() != null)
314 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
315 .equals(action),
316 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
317 urlData.mUrl, false);
318 addTab(t);
319 setActiveTab(t);
320 WebView webView = t.getWebView();
321 if (extra != null) {
322 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
323 if (scale > 0 && scale <= 1000) {
324 webView.setInitialScale(scale);
325 }
326 }
327
328 if (urlData.isEmpty()) {
329 loadUrl(webView, mSettings.getHomePage());
330 } else {
Michael Kolbcd424e92011-02-24 10:26:26 -0800331 // monkey protection against delayed start
332 if (t != null) {
333 loadUrlDataIn(t, urlData);
334 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700335 }
336 } else {
Patrick Scott7d50a932011-02-04 09:27:26 -0500337 mTabControl.restoreState(icicle, currentTab, restoreIncognitoTabs,
338 mUi.needsRestoreAllTabs());
Michael Kolb1bf23132010-11-19 12:55:12 -0800339 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700340 // TabControl.restoreState() will create a new tab even if
341 // restoring the state fails.
342 setActiveTab(mTabControl.getCurrentTab());
343 }
344 // clear up the thumbnail directory, which is no longer used;
345 // ideally this should only be run once after an upgrade from
346 // a previous version of the browser
347 new ClearThumbnails().execute(mTabControl.getThumbnailDir()
348 .listFiles());
349 // Read JavaScript flags if it exists.
350 String jsFlags = getSettings().getJsFlags();
351 if (jsFlags.trim().length() != 0) {
352 getCurrentWebView().setJsFlags(jsFlags);
353 }
John Reck439c9a52010-12-14 10:04:39 -0800354 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
355 bookmarksOrHistoryPicker(false);
356 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700357 }
358
359 void setWebViewFactory(WebViewFactory factory) {
360 mFactory = factory;
361 }
362
Michael Kolb1514bb72010-11-22 09:11:48 -0800363 @Override
364 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700365 return mFactory;
366 }
367
368 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800369 public void onSetWebView(Tab tab, WebView view) {
370 mUi.onSetWebView(tab, view);
371 }
372
373 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800374 public void createSubWindow(Tab tab) {
375 endActionMode();
376 WebView mainView = tab.getWebView();
377 WebView subView = mFactory.createWebView((mainView == null)
378 ? false
379 : mainView.isPrivateBrowsingEnabled());
380 mUi.createSubWindow(tab, subView);
381 }
382
383 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700384 public Activity getActivity() {
385 return mActivity;
386 }
387
388 void setUi(UI ui) {
389 mUi = ui;
390 }
391
392 BrowserSettings getSettings() {
393 return mSettings;
394 }
395
396 IntentHandler getIntentHandler() {
397 return mIntentHandler;
398 }
399
400 @Override
401 public UI getUi() {
402 return mUi;
403 }
404
405 int getMaxTabs() {
406 return mActivity.getResources().getInteger(R.integer.max_tabs);
407 }
408
409 @Override
410 public TabControl getTabControl() {
411 return mTabControl;
412 }
413
Michael Kolb1bf23132010-11-19 12:55:12 -0800414 @Override
415 public List<Tab> getTabs() {
416 return mTabControl.getTabs();
417 }
418
Michael Kolb8233fac2010-10-26 16:08:53 -0700419 // Open the icon database and retain all the icons for visited sites.
Ben Murdoch9446b932010-11-25 16:20:14 +0000420 // This is done on a background thread so as not to stall startup.
Michael Kolb8233fac2010-10-26 16:08:53 -0700421 private void retainIconsOnStartup() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000422 // WebIconDatabase needs to be retrieved on the UI thread so that if
423 // it has not been created successfully yet the Handler is started on the
424 // UI thread.
425 new RetainIconsOnStartupTask(WebIconDatabase.getInstance()).execute();
426 }
427
428 private class RetainIconsOnStartupTask extends AsyncTask<Void, Void, Void> {
429 private WebIconDatabase mDb;
430
431 public RetainIconsOnStartupTask(WebIconDatabase db) {
432 mDb = db;
433 }
434
John Recka00cbbd2010-12-16 12:38:19 -0800435 @Override
Ben Murdoch9446b932010-11-25 16:20:14 +0000436 protected Void doInBackground(Void... unused) {
437 mDb.open(mActivity.getDir("icons", 0).getPath());
438 Cursor c = null;
439 try {
440 c = Browser.getAllBookmarks(mActivity.getContentResolver());
441 if (c.moveToFirst()) {
442 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
443 do {
444 String url = c.getString(urlIndex);
445 mDb.retainIconForPageUrl(url);
446 } while (c.moveToNext());
447 }
448 } catch (IllegalStateException e) {
449 Log.e(LOGTAG, "retainIconsOnStartup", e);
450 } finally {
451 if (c != null) c.close();
Michael Kolb8233fac2010-10-26 16:08:53 -0700452 }
Ben Murdoch9446b932010-11-25 16:20:14 +0000453
454 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700455 }
456 }
457
458 private void startHandler() {
459 mHandler = new Handler() {
460
461 @Override
462 public void handleMessage(Message msg) {
463 switch (msg.what) {
464 case OPEN_BOOKMARKS:
465 bookmarksOrHistoryPicker(false);
466 break;
467 case FOCUS_NODE_HREF:
468 {
469 String url = (String) msg.getData().get("url");
470 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500471 String src = (String) msg.getData().get("src");
472 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700473 if (TextUtils.isEmpty(url)) {
474 break;
475 }
476 HashMap focusNodeMap = (HashMap) msg.obj;
477 WebView view = (WebView) focusNodeMap.get("webview");
478 // Only apply the action if the top window did not change.
479 if (getCurrentTopWebView() != view) {
480 break;
481 }
482 switch (msg.arg1) {
483 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -0700484 loadUrlFromContext(getCurrentTopWebView(), url);
485 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500486 case R.id.view_image_context_menu_id:
487 loadUrlFromContext(getCurrentTopWebView(), src);
488 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500489 case R.id.open_newtab_context_menu_id:
490 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -0800491 final Tab newTab = openTab(parent, url, false);
Leon Scroggins026f2542010-11-22 13:26:12 -0500492 if (newTab != null && newTab != parent) {
493 parent.addChildTab(newTab);
494 }
495 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700496 case R.id.copy_link_context_menu_id:
497 copy(url);
498 break;
499 case R.id.save_link_context_menu_id:
500 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500501 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000502 mActivity, url, null, null, null,
503 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700504 break;
505 }
506 break;
507 }
508
509 case LOAD_URL:
510 loadUrlFromContext(getCurrentTopWebView(), (String) msg.obj);
511 break;
512
513 case STOP_LOAD:
514 stopLoading();
515 break;
516
517 case RELEASE_WAKELOCK:
518 if (mWakeLock.isHeld()) {
519 mWakeLock.release();
520 // if we reach here, Browser should be still in the
521 // background loading after WAKELOCK_TIMEOUT (5-min).
522 // To avoid burning the battery, stop loading.
523 mTabControl.stopAllLoading();
524 }
525 break;
526
527 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800528 Tab tab = (Tab) msg.obj;
529 if (tab != null) {
530 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700531 }
532 break;
533 }
534 }
535 };
536
537 }
538
Michael Kolbba99c5d2010-11-29 14:57:41 -0800539 @Override
540 public void shareCurrentPage() {
541 shareCurrentPage(mTabControl.getCurrentTab());
542 }
543
544 private void shareCurrentPage(Tab tab) {
545 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800546 sharePage(mActivity, tab.getTitle(),
547 tab.getUrl(), tab.getFavicon(),
548 createScreenshot(tab.getWebView(),
549 getDesiredThumbnailWidth(mActivity),
550 getDesiredThumbnailHeight(mActivity)));
551 }
552 }
553
Michael Kolb8233fac2010-10-26 16:08:53 -0700554 /**
555 * Share a page, providing the title, url, favicon, and a screenshot. Uses
556 * an {@link Intent} to launch the Activity chooser.
557 * @param c Context used to launch a new Activity.
558 * @param title Title of the page. Stored in the Intent with
559 * {@link Intent#EXTRA_SUBJECT}
560 * @param url URL of the page. Stored in the Intent with
561 * {@link Intent#EXTRA_TEXT}
562 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
563 * with {@link Browser#EXTRA_SHARE_FAVICON}
564 * @param screenshot Bitmap of a screenshot of the page. Stored in the
565 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
566 */
567 static final void sharePage(Context c, String title, String url,
568 Bitmap favicon, Bitmap screenshot) {
569 Intent send = new Intent(Intent.ACTION_SEND);
570 send.setType("text/plain");
571 send.putExtra(Intent.EXTRA_TEXT, url);
572 send.putExtra(Intent.EXTRA_SUBJECT, title);
573 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
574 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
575 try {
576 c.startActivity(Intent.createChooser(send, c.getString(
577 R.string.choosertitle_sharevia)));
578 } catch(android.content.ActivityNotFoundException ex) {
579 // if no app handles it, do nothing
580 }
581 }
582
583 private void copy(CharSequence text) {
584 ClipboardManager cm = (ClipboardManager) mActivity
585 .getSystemService(Context.CLIPBOARD_SERVICE);
586 cm.setText(text);
587 }
588
589 // lifecycle
590
591 protected void onConfgurationChanged(Configuration config) {
592 mConfigChanged = true;
593 if (mPageDialogsHandler != null) {
594 mPageDialogsHandler.onConfigurationChanged(config);
595 }
596 mUi.onConfigurationChanged(config);
597 }
598
599 @Override
600 public void handleNewIntent(Intent intent) {
601 mIntentHandler.onNewIntent(intent);
602 }
603
604 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800605 if (mUi.isCustomViewShowing()) {
606 hideCustomView();
607 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700608 if (mActivityPaused) {
609 Log.e(LOGTAG, "BrowserActivity is already paused.");
610 return;
611 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700612 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800613 Tab tab = mTabControl.getCurrentTab();
614 if (tab != null) {
615 tab.pause();
616 if (!pauseWebViewTimers(tab)) {
617 mWakeLock.acquire();
618 mHandler.sendMessageDelayed(mHandler
619 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
620 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700621 }
622 mUi.onPause();
623 mNetworkHandler.onPause();
624
625 WebView.disablePlatformNotifications();
John Reck847b5322011-04-14 17:02:18 -0700626 mCrashRecoveryHandler.clearState();
Michael Kolb8233fac2010-10-26 16:08:53 -0700627 }
628
629 void onSaveInstanceState(Bundle outState) {
630 // the default implementation requires each view to have an id. As the
631 // browser handles the state itself and it doesn't use id for the views,
632 // don't call the default implementation. Otherwise it will trigger the
633 // warning like this, "couldn't save which view has focus because the
634 // focused view XXX has no id".
635
636 // Save all the tabs
637 mTabControl.saveState(outState);
638 // Save time so that we know how old incognito tabs (if any) are.
639 outState.putSerializable("lastActiveDate", Calendar.getInstance());
640 }
641
642 void onResume() {
643 if (!mActivityPaused) {
644 Log.e(LOGTAG, "BrowserActivity is already resumed.");
645 return;
646 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700647 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800648 Tab current = mTabControl.getCurrentTab();
649 if (current != null) {
650 current.resume();
651 resumeWebViewTimers(current);
652 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700653 if (mWakeLock.isHeld()) {
654 mHandler.removeMessages(RELEASE_WAKELOCK);
655 mWakeLock.release();
656 }
657 mUi.onResume();
658 mNetworkHandler.onResume();
659 WebView.enablePlatformNotifications();
660 }
661
Michael Kolb70976932010-11-30 11:34:01 -0800662 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800663 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800664 * @param tab guaranteed non-null
665 */
666 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700667 boolean inLoad = tab.inPageLoad();
668 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
669 CookieSyncManager.getInstance().startSync();
670 WebView w = tab.getWebView();
671 if (w != null) {
672 w.resumeTimers();
673 }
674 }
675 }
676
Michael Kolb70976932010-11-30 11:34:01 -0800677 /**
678 * Pause all WebView timers using the WebView of the given tab
679 * @param tab
680 * @return true if the timers are paused or tab is null
681 */
682 private boolean pauseWebViewTimers(Tab tab) {
683 if (tab == null) {
684 return true;
685 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700686 CookieSyncManager.getInstance().stopSync();
687 WebView w = getCurrentWebView();
688 if (w != null) {
689 w.pauseTimers();
690 }
691 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700692 }
Michael Kolb70976932010-11-30 11:34:01 -0800693 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700694 }
695
696 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800697 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700698 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
699 mUploadHandler = null;
700 }
701 if (mTabControl == null) return;
702 mUi.onDestroy();
703 // Remove the current tab and sub window
704 Tab t = mTabControl.getCurrentTab();
705 if (t != null) {
706 dismissSubWindow(t);
707 removeTab(t);
708 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500709 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700710 // Destroy all the tabs
711 mTabControl.destroy();
712 WebIconDatabase.getInstance().close();
713 // Stop watching the default geolocation permissions
714 mSystemAllowGeolocationOrigins.stop();
715 mSystemAllowGeolocationOrigins = null;
716 }
717
718 protected boolean isActivityPaused() {
719 return mActivityPaused;
720 }
721
722 protected void onLowMemory() {
723 mTabControl.freeMemory();
724 }
725
726 @Override
727 public boolean shouldShowErrorConsole() {
728 return mShouldShowErrorConsole;
729 }
730
731 protected void setShouldShowErrorConsole(boolean show) {
732 if (show == mShouldShowErrorConsole) {
733 // Nothing to do.
734 return;
735 }
736 mShouldShowErrorConsole = show;
737 Tab t = mTabControl.getCurrentTab();
738 if (t == null) {
739 // There is no current tab so we cannot toggle the error console
740 return;
741 }
742 mUi.setShouldShowErrorConsole(t, show);
743 }
744
745 @Override
746 public void stopLoading() {
747 mLoadStopped = true;
748 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700749 WebView w = getCurrentTopWebView();
750 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700751 mUi.onPageStopped(tab);
752 }
753
754 boolean didUserStopLoading() {
755 return mLoadStopped;
756 }
757
758 // WebViewController
759
760 @Override
John Reck324d4402011-01-11 16:56:42 -0800761 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700762
763 // We've started to load a new page. If there was a pending message
764 // to save a screenshot then we will now take the new page and save
765 // an incorrect screenshot. Therefore, remove any pending thumbnail
766 // messages from the queue.
767 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800768 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700769
770 // reset sync timer to avoid sync starts during loading a page
771 CookieSyncManager.getInstance().resetSync();
772
773 if (!mNetworkHandler.isNetworkUp()) {
774 view.setNetworkAvailable(false);
775 }
776
777 // when BrowserActivity just starts, onPageStarted may be called before
778 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
779 // to start the timer. As we won't switch tabs while an activity is in
780 // pause state, we can ensure calling resume and pause in pair.
781 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800782 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700783 }
784 mLoadStopped = false;
785 if (!mNetworkHandler.isNetworkUp()) {
786 mNetworkHandler.createAndShowNetworkDialog();
787 }
788 endActionMode();
789
John Reck30c714c2010-12-16 17:30:34 -0800790 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700791
John Reck324d4402011-01-11 16:56:42 -0800792 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700793 // update the bookmark database for favicon
794 maybeUpdateFavicon(tab, null, url, favicon);
795
796 Performance.tracePageStart(url);
797
798 // Performance probe
799 if (false) {
800 Performance.onPageStarted();
801 }
802
803 }
804
805 @Override
John Reck324d4402011-01-11 16:56:42 -0800806 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800807 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800808 if (!tab.isPrivateBrowsingEnabled()
809 && !TextUtils.isEmpty(tab.getUrl())) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700810 if (tab.inForeground() && !didUserStopLoading()
811 || !tab.inForeground()) {
812 // Only update the bookmark screenshot if the user did not
813 // cancel the load early.
814 mHandler.sendMessageDelayed(mHandler.obtainMessage(
John Reck34ef2672011-02-10 11:30:55 -0800815 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
Michael Kolb8233fac2010-10-26 16:08:53 -0700816 500);
817 }
818 }
819 // pause the WebView timer and release the wake lock if it is finished
820 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800821 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700822 if (mWakeLock.isHeld()) {
823 mHandler.removeMessages(RELEASE_WAKELOCK);
824 mWakeLock.release();
825 }
826 }
827 // Performance probe
828 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800829 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700830 }
831
832 Performance.tracePageFinished();
833 }
834
835 @Override
John Reck30c714c2010-12-16 17:30:34 -0800836 public void onProgressChanged(Tab tab) {
837 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700838
839 if (newProgress == 100) {
840 CookieSyncManager.getInstance().sync();
841 // onProgressChanged() may continue to be called after the main
842 // frame has finished loading, as any remaining sub frames continue
843 // to load. We'll only get called once though with newProgress as
844 // 100 when everything is loaded. (onPageFinished is called once
845 // when the main frame completes loading regardless of the state of
846 // any sub frames so calls to onProgressChanges may continue after
847 // onPageFinished has executed)
848 if (mInLoad) {
849 mInLoad = false;
850 updateInLoadMenuItems(mCachedMenu);
851 }
852 } else {
853 if (!mInLoad) {
854 // onPageFinished may have already been called but a subframe is
855 // still loading and updating the progress. Reset mInLoad and
856 // update the menu items.
857 mInLoad = true;
858 updateInLoadMenuItems(mCachedMenu);
859 }
860 }
John Reck30c714c2010-12-16 17:30:34 -0800861 mUi.onProgressChanged(tab);
862 }
863
864 @Override
865 public void onUpdatedLockIcon(Tab tab) {
866 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700867 }
868
869 @Override
870 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800871 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800872 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800873 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700874 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
875 return;
876 }
877 // Update the title in the history database if not in private browsing mode
878 if (!tab.isPrivateBrowsingEnabled()) {
John Reck0ebd3ac2010-12-09 11:14:04 -0800879 mDataController.updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700880 }
881 }
882
883 @Override
884 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800885 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700886 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
887 }
888
889 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800890 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
891 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700892 }
893
894 @Override
895 public boolean shouldOverrideKeyEvent(KeyEvent event) {
896 if (mMenuIsDown) {
897 // only check shortcut key when MENU is held
898 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
899 event);
900 } else {
901 return false;
902 }
903 }
904
905 @Override
906 public void onUnhandledKeyEvent(KeyEvent event) {
907 if (!isActivityPaused()) {
908 if (event.getAction() == KeyEvent.ACTION_DOWN) {
909 mActivity.onKeyDown(event.getKeyCode(), event);
910 } else {
911 mActivity.onKeyUp(event.getKeyCode(), event);
912 }
913 }
914 }
915
916 @Override
John Reck324d4402011-01-11 16:56:42 -0800917 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700918 // Don't save anything in private browsing mode
919 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800920 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700921
John Reck324d4402011-01-11 16:56:42 -0800922 if (TextUtils.isEmpty(url)
923 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700924 return;
925 }
John Reck0ebd3ac2010-12-09 11:14:04 -0800926 mDataController.updateVisitedHistory(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700927 WebIconDatabase.getInstance().retainIconForPageUrl(url);
John Reck847b5322011-04-14 17:02:18 -0700928 if (!mActivityPaused) {
929 // Since we clear the state in onPause, don't backup the current
930 // state if we are already paused
931 mCrashRecoveryHandler.backupState();
932 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700933 }
934
935 @Override
936 public void getVisitedHistory(final ValueCallback<String[]> callback) {
937 AsyncTask<Void, Void, String[]> task =
938 new AsyncTask<Void, Void, String[]>() {
939 @Override
940 public String[] doInBackground(Void... unused) {
941 return Browser.getVisitedHistory(mActivity.getContentResolver());
942 }
943 @Override
944 public void onPostExecute(String[] result) {
945 callback.onReceiveValue(result);
946 }
947 };
948 task.execute();
949 }
950
951 @Override
952 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
953 final HttpAuthHandler handler, final String host,
954 final String realm) {
955 String username = null;
956 String password = null;
957
958 boolean reuseHttpAuthUsernamePassword
959 = handler.useHttpAuthUsernamePassword();
960
961 if (reuseHttpAuthUsernamePassword && view != null) {
962 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
963 if (credentials != null && credentials.length == 2) {
964 username = credentials[0];
965 password = credentials[1];
966 }
967 }
968
969 if (username != null && password != null) {
970 handler.proceed(username, password);
971 } else {
972 if (tab.inForeground()) {
973 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
974 } else {
975 handler.cancel();
976 }
977 }
978 }
979
980 @Override
981 public void onDownloadStart(Tab tab, String url, String userAgent,
982 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000983 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -0500984 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000985 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
986 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700987 // This Tab was opened for the sole purpose of downloading a
988 // file. Remove it.
989 if (tab == mTabControl.getCurrentTab()) {
990 // In this case, the Tab is still on top.
991 goBackOnePageOrQuit();
992 } else {
993 // In this case, it is not.
994 closeTab(tab);
995 }
996 }
997 }
998
999 @Override
1000 public Bitmap getDefaultVideoPoster() {
1001 return mUi.getDefaultVideoPoster();
1002 }
1003
1004 @Override
1005 public View getVideoLoadingProgressView() {
1006 return mUi.getVideoLoadingProgressView();
1007 }
1008
1009 @Override
1010 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1011 SslError error) {
1012 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1013 }
1014
Patrick Scott92066772011-03-10 08:46:27 -05001015 @Override
1016 public void showAutoLogin(Tab tab) {
1017 assert tab.inForeground();
1018 // Update the title bar to show the auto-login request.
1019 mUi.showAutoLogin(tab);
1020 }
1021
1022 @Override
1023 public void hideAutoLogin(Tab tab) {
1024 assert tab.inForeground();
1025 mUi.hideAutoLogin(tab);
1026 }
1027
Michael Kolb8233fac2010-10-26 16:08:53 -07001028 // helper method
1029
1030 /*
1031 * Update the favorites icon if the private browsing isn't enabled and the
1032 * icon is valid.
1033 */
1034 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1035 final String url, Bitmap favicon) {
1036 if (favicon == null) {
1037 return;
1038 }
1039 if (!tab.isPrivateBrowsingEnabled()) {
1040 Bookmarks.updateFavicon(mActivity
1041 .getContentResolver(), originalUrl, url, favicon);
1042 }
1043 }
1044
Leon Scroggins4cd97792010-12-03 15:31:56 -05001045 @Override
1046 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001047 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001048 mUi.bookmarkedStatusHasChanged(tab);
1049 }
1050
Michael Kolb8233fac2010-10-26 16:08:53 -07001051 // end WebViewController
1052
1053 protected void pageUp() {
1054 getCurrentTopWebView().pageUp(false);
1055 }
1056
1057 protected void pageDown() {
1058 getCurrentTopWebView().pageDown(false);
1059 }
1060
1061 // callback from phone title bar
1062 public void editUrl() {
1063 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001064 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001065 }
1066
Michael Kolbcfa3af52010-12-14 10:36:11 -08001067 public void startVoiceSearch() {
1068 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1069 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1070 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1071 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1072 mActivity.getComponentName().flattenToString());
1073 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001074 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001075 mActivity.startActivity(intent);
1076 }
1077
Michael Kolb11d19782011-03-20 10:17:40 -07001078 @Override
1079 public void activateVoiceSearchMode(String title, List<String> results) {
1080 mUi.showVoiceTitleBar(title, results);
Michael Kolb8233fac2010-10-26 16:08:53 -07001081 }
1082
1083 public void revertVoiceSearchMode(Tab tab) {
1084 mUi.revertVoiceTitleBar(tab);
1085 }
1086
Michael Kolb736990c2011-03-20 10:01:20 -07001087 public boolean supportsVoiceSearch() {
1088 SearchEngine searchEngine = BrowserSettings.getInstance()
1089 .getSearchEngine();
1090 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1091 }
1092
Michael Kolb8233fac2010-10-26 16:08:53 -07001093 public void showCustomView(Tab tab, View view,
1094 WebChromeClient.CustomViewCallback callback) {
1095 if (tab.inForeground()) {
1096 if (mUi.isCustomViewShowing()) {
1097 callback.onCustomViewHidden();
1098 return;
1099 }
1100 mUi.showCustomView(view, callback);
1101 // Save the menu state and set it to empty while the custom
1102 // view is showing.
1103 mOldMenuState = mMenuState;
1104 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001105 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001106 }
1107 }
1108
1109 @Override
1110 public void hideCustomView() {
1111 if (mUi.isCustomViewShowing()) {
1112 mUi.onHideCustomView();
1113 // Reset the old menu state.
1114 mMenuState = mOldMenuState;
1115 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001116 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001117 }
1118 }
1119
1120 protected void onActivityResult(int requestCode, int resultCode,
1121 Intent intent) {
1122 if (getCurrentTopWebView() == null) return;
1123 switch (requestCode) {
1124 case PREFERENCES_PAGE:
1125 if (resultCode == Activity.RESULT_OK && intent != null) {
1126 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
1127 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
1128 mTabControl.removeParentChildRelationShips();
1129 }
1130 }
1131 break;
1132 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001133 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001134 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001135 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001136 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001137 case AUTOFILL_SETUP:
1138 // Determine whether a profile was actually set up or not
1139 // and if so, send the message back to the WebTextView to
1140 // fill the form with the new profile.
1141 if (getSettings().getAutoFillProfile() != null) {
1142 mAutoFillSetupMessage.sendToTarget();
1143 mAutoFillSetupMessage = null;
1144 }
1145 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001146 default:
1147 break;
1148 }
1149 getCurrentTopWebView().requestFocus();
1150 }
1151
1152 /**
1153 * Open the Go page.
1154 * @param startWithHistory If true, open starting on the history tab.
1155 * Otherwise, start with the bookmarks tab.
1156 */
1157 @Override
1158 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1159 if (mTabControl.getCurrentWebView() == null) {
1160 return;
1161 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001162 // clear action mode
1163 if (isInCustomActionMode()) {
1164 endActionMode();
1165 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001166 Bundle extras = new Bundle();
1167 // Disable opening in a new window if we have maxed out the windows
1168 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1169 !mTabControl.canCreateNewTab());
1170 mUi.showComboView(startWithHistory, extras);
1171 }
1172
1173 // combo view callbacks
1174
1175 /**
1176 * callback from ComboPage when clear history is requested
1177 */
1178 public void onRemoveParentChildRelationships() {
1179 mTabControl.removeParentChildRelationShips();
1180 }
1181
1182 /**
1183 * callback from ComboPage when bookmark/history selection
1184 */
1185 @Override
1186 public void onUrlSelected(String url, boolean newTab) {
1187 removeComboView();
1188 if (!TextUtils.isEmpty(url)) {
1189 if (newTab) {
Michael Kolb18eb3772010-12-10 14:29:51 -08001190 openTab(mTabControl.getCurrentTab(), url, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001191 } else {
1192 final Tab currentTab = mTabControl.getCurrentTab();
1193 dismissSubWindow(currentTab);
1194 loadUrl(getCurrentTopWebView(), url);
1195 }
1196 }
1197 }
1198
1199 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07001200 * dismiss the ComboPage
1201 */
1202 @Override
1203 public void removeComboView() {
1204 mUi.hideComboView();
1205 }
1206
1207 // active tabs page handling
1208
1209 protected void showActiveTabsPage() {
1210 mMenuState = EMPTY_MENU;
1211 mUi.showActiveTabsPage();
1212 }
1213
1214 /**
1215 * Remove the active tabs page.
1216 * @param needToAttach If true, the active tabs page did not attach a tab
1217 * to the content view, so we need to do that here.
1218 */
1219 @Override
1220 public void removeActiveTabsPage(boolean needToAttach) {
1221 mMenuState = R.id.MAIN_MENU;
1222 mUi.removeActiveTabsPage();
1223 if (needToAttach) {
1224 setActiveTab(mTabControl.getCurrentTab());
1225 }
1226 getCurrentTopWebView().requestFocus();
1227 }
1228
1229 // key handling
1230 protected void onBackKey() {
1231 if (!mUi.onBackKey()) {
1232 WebView subwindow = mTabControl.getCurrentSubWindow();
1233 if (subwindow != null) {
1234 if (subwindow.canGoBack()) {
1235 subwindow.goBack();
1236 } else {
1237 dismissSubWindow(mTabControl.getCurrentTab());
1238 }
1239 } else {
1240 goBackOnePageOrQuit();
1241 }
1242 }
1243 }
1244
1245 // menu handling and state
1246 // TODO: maybe put into separate handler
1247
1248 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckb3417f02011-01-14 11:01:05 -08001249 if (mOptionsMenuHandler != null) {
1250 return mOptionsMenuHandler.onCreateOptionsMenu(menu);
1251 }
1252
John Reckd73c5a22010-12-22 10:22:50 -08001253 if (mMenuState == EMPTY_MENU) {
1254 return false;
1255 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001256 MenuInflater inflater = mActivity.getMenuInflater();
1257 inflater.inflate(R.menu.browser, menu);
1258 updateInLoadMenuItems(menu);
1259 // hold on to the menu reference here; it is used by the page callbacks
1260 // to update the menu based on loading state
1261 mCachedMenu = menu;
1262 return true;
1263 }
1264
1265 protected void onCreateContextMenu(ContextMenu menu, View v,
1266 ContextMenuInfo menuInfo) {
1267 if (v instanceof TitleBarBase) {
1268 return;
1269 }
1270 if (!(v instanceof WebView)) {
1271 return;
1272 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001273 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001274 WebView.HitTestResult result = webview.getHitTestResult();
1275 if (result == null) {
1276 return;
1277 }
1278
1279 int type = result.getType();
1280 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1281 Log.w(LOGTAG,
1282 "We should not show context menu when nothing is touched");
1283 return;
1284 }
1285 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1286 // let TextView handles context menu
1287 return;
1288 }
1289
1290 // Note, http://b/issue?id=1106666 is requesting that
1291 // an inflated menu can be used again. This is not available
1292 // yet, so inflate each time (yuk!)
1293 MenuInflater inflater = mActivity.getMenuInflater();
1294 inflater.inflate(R.menu.browsercontext, menu);
1295
1296 // Show the correct menu group
1297 final String extra = result.getExtra();
1298 menu.setGroupVisible(R.id.PHONE_MENU,
1299 type == WebView.HitTestResult.PHONE_TYPE);
1300 menu.setGroupVisible(R.id.EMAIL_MENU,
1301 type == WebView.HitTestResult.EMAIL_TYPE);
1302 menu.setGroupVisible(R.id.GEO_MENU,
1303 type == WebView.HitTestResult.GEO_TYPE);
1304 menu.setGroupVisible(R.id.IMAGE_MENU,
1305 type == WebView.HitTestResult.IMAGE_TYPE
1306 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1307 menu.setGroupVisible(R.id.ANCHOR_MENU,
1308 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1309 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001310 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1311 || type == WebView.HitTestResult.PHONE_TYPE
1312 || type == WebView.HitTestResult.EMAIL_TYPE
1313 || type == WebView.HitTestResult.GEO_TYPE;
1314 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1315 if (hitText) {
1316 menu.findItem(R.id.select_text_menu_id)
1317 .setOnMenuItemClickListener(new SelectText(webview));
1318 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001319 // Setup custom handling depending on the type
1320 switch (type) {
1321 case WebView.HitTestResult.PHONE_TYPE:
1322 menu.setHeaderTitle(Uri.decode(extra));
1323 menu.findItem(R.id.dial_context_menu_id).setIntent(
1324 new Intent(Intent.ACTION_VIEW, Uri
1325 .parse(WebView.SCHEME_TEL + extra)));
1326 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1327 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1328 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1329 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1330 addIntent);
1331 menu.findItem(R.id.copy_phone_context_menu_id)
1332 .setOnMenuItemClickListener(
1333 new Copy(extra));
1334 break;
1335
1336 case WebView.HitTestResult.EMAIL_TYPE:
1337 menu.setHeaderTitle(extra);
1338 menu.findItem(R.id.email_context_menu_id).setIntent(
1339 new Intent(Intent.ACTION_VIEW, Uri
1340 .parse(WebView.SCHEME_MAILTO + extra)));
1341 menu.findItem(R.id.copy_mail_context_menu_id)
1342 .setOnMenuItemClickListener(
1343 new Copy(extra));
1344 break;
1345
1346 case WebView.HitTestResult.GEO_TYPE:
1347 menu.setHeaderTitle(extra);
1348 menu.findItem(R.id.map_context_menu_id).setIntent(
1349 new Intent(Intent.ACTION_VIEW, Uri
1350 .parse(WebView.SCHEME_GEO
1351 + URLEncoder.encode(extra))));
1352 menu.findItem(R.id.copy_geo_context_menu_id)
1353 .setOnMenuItemClickListener(
1354 new Copy(extra));
1355 break;
1356
1357 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1358 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001359 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001360 // decide whether to show the open link in new tab option
1361 boolean showNewTab = mTabControl.canCreateNewTab();
1362 MenuItem newTabItem
1363 = menu.findItem(R.id.open_newtab_context_menu_id);
Michael Kolb2dd65c82011-01-14 11:07:38 -08001364 newTabItem.setTitle(
1365 BrowserSettings.getInstance().openInBackground()
1366 ? R.string.contextmenu_openlink_newwindow_background
1367 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001368 newTabItem.setVisible(showNewTab);
1369 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001370 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1371 newTabItem.setOnMenuItemClickListener(
1372 new MenuItem.OnMenuItemClickListener() {
1373 @Override
1374 public boolean onMenuItemClick(MenuItem item) {
1375 final HashMap<String, WebView> hrefMap =
1376 new HashMap<String, WebView>();
1377 hrefMap.put("webview", webview);
1378 final Message msg = mHandler.obtainMessage(
1379 FOCUS_NODE_HREF,
1380 R.id.open_newtab_context_menu_id,
1381 0, hrefMap);
1382 webview.requestFocusNodeHref(msg);
1383 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001384 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001385 });
1386 } else {
1387 newTabItem.setOnMenuItemClickListener(
1388 new MenuItem.OnMenuItemClickListener() {
1389 @Override
1390 public boolean onMenuItemClick(MenuItem item) {
1391 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -08001392 final Tab newTab = openTab(parent,
1393 extra, false);
Leon Scroggins026f2542010-11-22 13:26:12 -05001394 if (newTab != parent) {
1395 parent.addChildTab(newTab);
1396 }
1397 return true;
1398 }
1399 });
1400 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001401 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001402 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1403 break;
1404 }
1405 // otherwise fall through to handle image part
1406 case WebView.HitTestResult.IMAGE_TYPE:
1407 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1408 menu.setHeaderTitle(extra);
1409 }
1410 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1411 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1412 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001413 setOnMenuItemClickListener(
1414 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001415 menu.findItem(R.id.set_wallpaper_context_menu_id).
1416 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1417 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001418 break;
1419
1420 default:
1421 Log.w(LOGTAG, "We should not get here.");
1422 break;
1423 }
1424 //update the ui
1425 mUi.onContextMenuCreated(menu);
1426 }
1427
1428 /**
1429 * As the menu can be open when loading state changes
1430 * we must manually update the state of the stop/reload menu
1431 * item
1432 */
1433 private void updateInLoadMenuItems(Menu menu) {
1434 if (menu == null) {
1435 return;
1436 }
1437 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1438 MenuItem src = mInLoad ?
1439 menu.findItem(R.id.stop_menu_id):
1440 menu.findItem(R.id.reload_menu_id);
1441 if (src != null) {
1442 dest.setIcon(src.getIcon());
1443 dest.setTitle(src.getTitle());
1444 }
1445 }
1446
John Reckb3417f02011-01-14 11:01:05 -08001447 boolean onPrepareOptionsMenu(Menu menu) {
1448 if (mOptionsMenuHandler != null) {
1449 return mOptionsMenuHandler.onPrepareOptionsMenu(menu);
1450 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001451 // Note: setVisible will decide whether an item is visible; while
1452 // setEnabled() will decide whether an item is enabled, which also means
1453 // whether the matching shortcut key will function.
1454 switch (mMenuState) {
1455 case EMPTY_MENU:
1456 if (mCurrentMenuState != mMenuState) {
1457 menu.setGroupVisible(R.id.MAIN_MENU, false);
1458 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1459 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1460 }
1461 break;
1462 default:
1463 if (mCurrentMenuState != mMenuState) {
1464 menu.setGroupVisible(R.id.MAIN_MENU, true);
1465 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1466 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1467 }
1468 final WebView w = getCurrentTopWebView();
1469 boolean canGoBack = false;
1470 boolean canGoForward = false;
1471 boolean isHome = false;
1472 if (w != null) {
1473 canGoBack = w.canGoBack();
1474 canGoForward = w.canGoForward();
1475 isHome = mSettings.getHomePage().equals(w.getUrl());
1476 }
1477 final MenuItem back = menu.findItem(R.id.back_menu_id);
1478 back.setEnabled(canGoBack);
1479
1480 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1481 home.setEnabled(!isHome);
1482
1483 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1484 forward.setEnabled(canGoForward);
1485
1486 // decide whether to show the share link option
1487 PackageManager pm = mActivity.getPackageManager();
1488 Intent send = new Intent(Intent.ACTION_SEND);
1489 send.setType("text/plain");
1490 ResolveInfo ri = pm.resolveActivity(send,
1491 PackageManager.MATCH_DEFAULT_ONLY);
1492 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1493
1494 boolean isNavDump = mSettings.isNavDump();
1495 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1496 nav.setVisible(isNavDump);
1497 nav.setEnabled(isNavDump);
1498
1499 boolean showDebugSettings = mSettings.showDebugSettings();
1500 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1501 counter.setVisible(showDebugSettings);
1502 counter.setEnabled(showDebugSettings);
1503
John Reckb3417f02011-01-14 11:01:05 -08001504 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1505 newtab.setEnabled(getTabControl().canCreateNewTab());
Michael Kolb8233fac2010-10-26 16:08:53 -07001506
Leon Scroggins81983762011-02-11 15:17:36 -05001507 MenuItem archive = menu.findItem(R.id.save_webarchive_menu_id);
John Reck51d8bad2011-02-28 15:47:47 -08001508 Tab tab = getTabControl().getCurrentTab();
1509 String url = tab != null ? tab.getUrl() : null;
1510 archive.setVisible(!TextUtils.isEmpty(url)
1511 && !url.endsWith(".webarchivexml"));
Michael Kolb8233fac2010-10-26 16:08:53 -07001512 break;
1513 }
1514 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001515 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001516 }
1517
1518 public boolean onOptionsItemSelected(MenuItem item) {
John Reckb3417f02011-01-14 11:01:05 -08001519 if (mOptionsMenuHandler != null &&
1520 mOptionsMenuHandler.onOptionsItemSelected(item)) {
1521 return true;
1522 }
1523
Michael Kolb8233fac2010-10-26 16:08:53 -07001524 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1525 // menu remains active, so ensure comboview is dismissed
1526 // if main menu option is selected
1527 removeComboView();
1528 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001529 if (null == getCurrentTopWebView()) {
1530 return false;
1531 }
1532 if (mMenuIsDown) {
1533 // The shortcut action consumes the MENU. Even if it is still down,
1534 // it won't trigger the next shortcut action. In the case of the
1535 // shortcut action triggering a new activity, like Bookmarks, we
1536 // won't get onKeyUp for MENU. So it is important to reset it here.
1537 mMenuIsDown = false;
1538 }
1539 switch (item.getItemId()) {
1540 // -- Main menu
1541 case R.id.new_tab_menu_id:
1542 openTabToHomePage();
1543 break;
1544
1545 case R.id.incognito_menu_id:
1546 openIncognitoTab();
1547 break;
1548
1549 case R.id.goto_menu_id:
1550 editUrl();
1551 break;
1552
1553 case R.id.bookmarks_menu_id:
1554 bookmarksOrHistoryPicker(false);
1555 break;
1556
1557 case R.id.active_tabs_menu_id:
1558 showActiveTabsPage();
1559 break;
1560
1561 case R.id.add_bookmark_menu_id:
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001562 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001563 break;
1564
1565 case R.id.stop_reload_menu_id:
1566 if (mInLoad) {
1567 stopLoading();
1568 } else {
1569 getCurrentTopWebView().reload();
1570 }
1571 break;
1572
1573 case R.id.back_menu_id:
1574 getCurrentTopWebView().goBack();
1575 break;
1576
1577 case R.id.forward_menu_id:
1578 getCurrentTopWebView().goForward();
1579 break;
1580
1581 case R.id.close_menu_id:
1582 // Close the subwindow if it exists.
1583 if (mTabControl.getCurrentSubWindow() != null) {
1584 dismissSubWindow(mTabControl.getCurrentTab());
1585 break;
1586 }
1587 closeCurrentTab();
1588 break;
1589
1590 case R.id.homepage_menu_id:
1591 Tab current = mTabControl.getCurrentTab();
1592 if (current != null) {
1593 dismissSubWindow(current);
1594 loadUrl(current.getWebView(), mSettings.getHomePage());
1595 }
1596 break;
1597
1598 case R.id.preferences_menu_id:
1599 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1600 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1601 getCurrentTopWebView().getUrl());
1602 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1603 break;
1604
1605 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001606 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001607 break;
1608
Leon Scrogginsac993842011-02-02 12:54:07 -05001609 case R.id.save_webarchive_menu_id:
1610 String state = Environment.getExternalStorageState();
1611 if (!Environment.MEDIA_MOUNTED.equals(state)) {
1612 Log.e(LOGTAG, "External storage not mounted");
1613 Toast.makeText(mActivity, R.string.webarchive_failed,
1614 Toast.LENGTH_SHORT).show();
1615 break;
1616 }
1617 final String directory = Environment.getExternalStoragePublicDirectory(
1618 Environment.DIRECTORY_DOWNLOADS) + File.separator;
1619 File dir = new File(directory);
1620 if (!dir.exists() && !dir.mkdirs()) {
1621 Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
1622 Toast.makeText(mActivity, R.string.webarchive_failed,
1623 Toast.LENGTH_SHORT).show();
1624 break;
1625 }
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001626 final WebView topWebView = getCurrentTopWebView();
Leon Scrogginsac993842011-02-02 12:54:07 -05001627 final String title = topWebView.getTitle();
John Reck51d8bad2011-02-28 15:47:47 -08001628 final String url = topWebView.getUrl();
Leon Scrogginsac993842011-02-02 12:54:07 -05001629 topWebView.saveWebArchive(directory, true,
1630 new ValueCallback<String>() {
1631 @Override
1632 public void onReceiveValue(final String value) {
1633 if (value != null) {
1634 File file = new File(value);
1635 final long length = file.length();
1636 if (file.exists() && length > 0) {
Leon Scroggins1cb96552011-02-11 14:22:57 -05001637 Toast.makeText(mActivity, R.string.webarchive_saved,
1638 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001639 final DownloadManager manager = (DownloadManager) mActivity
1640 .getSystemService(Context.DOWNLOAD_SERVICE);
1641 new Thread("Add WebArchive to download manager") {
1642 @Override
1643 public void run() {
Vasu Noria9e30a72011-03-07 11:37:34 -08001644 manager.addCompletedDownload(
1645 null == title ? value : title,
Leon Scrogginsac993842011-02-02 12:54:07 -05001646 value, true, "application/x-webarchive-xml",
1647 value, length, true);
1648 }
1649 }.start();
1650 return;
1651 }
1652 }
John Reck51d8bad2011-02-28 15:47:47 -08001653 DownloadHandler.onDownloadStartNoStream(mActivity,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001654 url, null, null, null, topWebView.isPrivateBrowsingEnabled());
Leon Scrogginsac993842011-02-02 12:54:07 -05001655 }
1656 });
1657 break;
1658
Michael Kolb8233fac2010-10-26 16:08:53 -07001659 case R.id.page_info_menu_id:
1660 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1661 false);
1662 break;
1663
1664 case R.id.classic_history_menu_id:
1665 bookmarksOrHistoryPicker(true);
1666 break;
1667
1668 case R.id.title_bar_share_page_url:
1669 case R.id.share_page_menu_id:
1670 Tab currentTab = mTabControl.getCurrentTab();
1671 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001672 return false;
1673 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001674 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001675 break;
1676
1677 case R.id.dump_nav_menu_id:
1678 getCurrentTopWebView().debugDump();
1679 break;
1680
1681 case R.id.dump_counters_menu_id:
1682 getCurrentTopWebView().dumpV8Counters();
1683 break;
1684
1685 case R.id.zoom_in_menu_id:
1686 getCurrentTopWebView().zoomIn();
1687 break;
1688
1689 case R.id.zoom_out_menu_id:
1690 getCurrentTopWebView().zoomOut();
1691 break;
1692
1693 case R.id.view_downloads_menu_id:
1694 viewDownloads();
1695 break;
1696
1697 case R.id.window_one_menu_id:
1698 case R.id.window_two_menu_id:
1699 case R.id.window_three_menu_id:
1700 case R.id.window_four_menu_id:
1701 case R.id.window_five_menu_id:
1702 case R.id.window_six_menu_id:
1703 case R.id.window_seven_menu_id:
1704 case R.id.window_eight_menu_id:
1705 {
1706 int menuid = item.getItemId();
1707 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1708 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1709 Tab desiredTab = mTabControl.getTab(id);
1710 if (desiredTab != null &&
1711 desiredTab != mTabControl.getCurrentTab()) {
1712 switchToTab(id);
1713 }
1714 break;
1715 }
1716 }
1717 }
1718 break;
1719
1720 default:
1721 return false;
1722 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001723 return true;
1724 }
1725
1726 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001727 // Let the History and Bookmark fragments handle menus they created.
1728 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1729 return false;
1730 }
1731
Michael Kolb8233fac2010-10-26 16:08:53 -07001732 int id = item.getItemId();
1733 boolean result = true;
1734 switch (id) {
1735 // For the context menu from the title bar
1736 case R.id.title_bar_copy_page_url:
1737 Tab currentTab = mTabControl.getCurrentTab();
1738 if (null == currentTab) {
1739 result = false;
1740 break;
1741 }
1742 WebView mainView = currentTab.getWebView();
1743 if (null == mainView) {
1744 result = false;
1745 break;
1746 }
1747 copy(mainView.getUrl());
1748 break;
1749 // -- Browser context menu
1750 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001751 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001752 case R.id.copy_link_context_menu_id:
1753 final WebView webView = getCurrentTopWebView();
1754 if (null == webView) {
1755 result = false;
1756 break;
1757 }
1758 final HashMap<String, WebView> hrefMap =
1759 new HashMap<String, WebView>();
1760 hrefMap.put("webview", webView);
1761 final Message msg = mHandler.obtainMessage(
1762 FOCUS_NODE_HREF, id, 0, hrefMap);
1763 webView.requestFocusNodeHref(msg);
1764 break;
1765
1766 default:
1767 // For other context menus
1768 result = onOptionsItemSelected(item);
1769 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001770 return result;
1771 }
1772
1773 /**
1774 * support programmatically opening the context menu
1775 */
1776 public void openContextMenu(View view) {
1777 mActivity.openContextMenu(view);
1778 }
1779
1780 /**
1781 * programmatically open the options menu
1782 */
1783 public void openOptionsMenu() {
1784 mActivity.openOptionsMenu();
1785 }
1786
1787 public boolean onMenuOpened(int featureId, Menu menu) {
1788 if (mOptionsMenuOpen) {
1789 if (mConfigChanged) {
1790 // We do not need to make any changes to the state of the
1791 // title bar, since the only thing that happened was a
1792 // change in orientation
1793 mConfigChanged = false;
1794 } else {
1795 if (!mExtendedMenuOpen) {
1796 mExtendedMenuOpen = true;
1797 mUi.onExtendedMenuOpened();
1798 } else {
1799 // Switching the menu back to icon view, so show the
1800 // title bar once again.
1801 mExtendedMenuOpen = false;
1802 mUi.onExtendedMenuClosed(mInLoad);
Michael Kolb8233fac2010-10-26 16:08:53 -07001803 }
1804 }
1805 } else {
1806 // The options menu is closed, so open it, and show the title
1807 mOptionsMenuOpen = true;
1808 mConfigChanged = false;
1809 mExtendedMenuOpen = false;
1810 mUi.onOptionsMenuOpened();
1811 }
1812 return true;
1813 }
1814
1815 public void onOptionsMenuClosed(Menu menu) {
1816 mOptionsMenuOpen = false;
1817 mUi.onOptionsMenuClosed(mInLoad);
1818 }
1819
1820 public void onContextMenuClosed(Menu menu) {
1821 mUi.onContextMenuClosed(menu, mInLoad);
1822 }
1823
1824 // Helper method for getting the top window.
1825 @Override
1826 public WebView getCurrentTopWebView() {
1827 return mTabControl.getCurrentTopWebView();
1828 }
1829
1830 @Override
1831 public WebView getCurrentWebView() {
1832 return mTabControl.getCurrentWebView();
1833 }
1834
1835 /*
1836 * This method is called as a result of the user selecting the options
1837 * menu to see the download window. It shows the download window on top of
1838 * the current window.
1839 */
1840 void viewDownloads() {
1841 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1842 mActivity.startActivity(intent);
1843 }
1844
1845 // action mode
1846
1847 void onActionModeStarted(ActionMode mode) {
1848 mUi.onActionModeStarted(mode);
1849 mActionMode = mode;
1850 }
1851
1852 /*
1853 * True if a custom ActionMode (i.e. find or select) is in use.
1854 */
1855 @Override
1856 public boolean isInCustomActionMode() {
1857 return mActionMode != null;
1858 }
1859
1860 /*
1861 * End the current ActionMode.
1862 */
1863 @Override
1864 public void endActionMode() {
1865 if (mActionMode != null) {
1866 mActionMode.finish();
1867 }
1868 }
1869
1870 /*
1871 * Called by find and select when they are finished. Replace title bars
1872 * as necessary.
1873 */
1874 public void onActionModeFinished(ActionMode mode) {
1875 if (!isInCustomActionMode()) return;
1876 mUi.onActionModeFinished(mInLoad);
1877 mActionMode = null;
1878 }
1879
1880 boolean isInLoad() {
1881 return mInLoad;
1882 }
1883
1884 // bookmark handling
1885
1886 /**
1887 * add the current page as a bookmark to the given folder id
1888 * @param folderId use -1 for the default folder
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001889 * @param canBeAnEdit If true, check to see whether the site is already
1890 * bookmarked, and if it is, edit that bookmark. If false, and
1891 * the site is already bookmarked, do not attempt to edit the
1892 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001893 */
1894 @Override
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001895 public void bookmarkCurrentPage(long folderId, boolean canBeAnEdit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001896 Intent i = new Intent(mActivity,
1897 AddBookmarkPage.class);
1898 WebView w = getCurrentTopWebView();
1899 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1900 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1901 String touchIconUrl = w.getTouchIconUrl();
1902 if (touchIconUrl != null) {
1903 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1904 WebSettings settings = w.getSettings();
1905 if (settings != null) {
1906 i.putExtra(AddBookmarkPage.USER_AGENT,
1907 settings.getUserAgentString());
1908 }
1909 }
1910 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1911 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1912 getDesiredThumbnailHeight(mActivity)));
1913 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1914 i.putExtra(BrowserContract.Bookmarks.PARENT,
1915 folderId);
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001916 if (canBeAnEdit) {
1917 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1918 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001919 // Put the dialog at the upper right of the screen, covering the
1920 // star on the title bar.
1921 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1922 mActivity.startActivity(i);
1923 }
1924
1925 // file chooser
1926 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1927 mUploadHandler = new UploadHandler(this);
1928 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1929 }
1930
1931 // thumbnails
1932
1933 /**
1934 * Return the desired width for thumbnail screenshots, which are stored in
1935 * the database, and used on the bookmarks screen.
1936 * @param context Context for finding out the density of the screen.
1937 * @return desired width for thumbnail screenshot.
1938 */
1939 static int getDesiredThumbnailWidth(Context context) {
1940 return context.getResources().getDimensionPixelOffset(
1941 R.dimen.bookmarkThumbnailWidth);
1942 }
1943
1944 /**
1945 * Return the desired height for thumbnail screenshots, which are stored in
1946 * the database, and used on the bookmarks screen.
1947 * @param context Context for finding out the density of the screen.
1948 * @return desired height for thumbnail screenshot.
1949 */
1950 static int getDesiredThumbnailHeight(Context context) {
1951 return context.getResources().getDimensionPixelOffset(
1952 R.dimen.bookmarkThumbnailHeight);
1953 }
1954
Michael Kolb1acef692011-03-08 14:12:06 -08001955 static Bitmap createScreenshot(Tab tab, int width, int height) {
1956 if ((tab != null) && (tab.getWebView() != null)) {
1957 return createScreenshot(tab.getWebView(), width, height);
1958 }
1959 return null;
1960 }
1961
Michael Kolb8233fac2010-10-26 16:08:53 -07001962 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001963 // We render to a bitmap 2x the desired size so that we can then
1964 // re-scale it with filtering since canvas.scale doesn't filter
1965 // This helps reduce aliasing at the cost of being slightly blurry
1966 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001967 Picture thumbnail = view.capturePicture();
1968 if (thumbnail == null) {
1969 return null;
1970 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001971 width *= filter_scale;
1972 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001973 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1974 Canvas canvas = new Canvas(bm);
1975 // May need to tweak these values to determine what is the
1976 // best scale factor
1977 int thumbnailWidth = thumbnail.getWidth();
1978 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001979 float scaleFactor = 1.0f;
Michael Kolbeb95db42011-03-03 10:38:40 -08001980 if (thumbnailWidth > 0 && thumbnailHeight > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001981 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001982 } else {
1983 return null;
1984 }
John Reckfe49ab42010-11-16 17:09:37 -08001985
Michael Kolbeb95db42011-03-03 10:38:40 -08001986 float scaleFactorY = (float) height / (float)thumbnailHeight;
1987 if (scaleFactorY > scaleFactor) {
1988 // The picture is narrower than the requested AR
1989 // Center the thumnail and crop the sides
1990 scaleFactor = scaleFactorY;
John Reckfe49ab42010-11-16 17:09:37 -08001991 float wx = (thumbnailWidth * scaleFactor) - width;
1992 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001993 }
1994
John Reckfe49ab42010-11-16 17:09:37 -08001995 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001996
1997 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001998 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
1999 height / filter_scale, true);
2000 bm.recycle();
2001 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07002002 }
2003
John Reck34ef2672011-02-10 11:30:55 -08002004 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002005 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07002006 // FIXME: Would like to make sure there is actually something to
2007 // draw, but the API for that (WebViewCore.pictureReady()) is not
2008 // currently accessible here.
2009
John Reck34ef2672011-02-10 11:30:55 -08002010 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08002011 if (view == null) {
2012 // Tab was destroyed
2013 return;
2014 }
John Reck34ef2672011-02-10 11:30:55 -08002015 final String url = tab.getUrl();
2016 final String originalUrl = view.getOriginalUrl();
2017
2018 if (TextUtils.isEmpty(url)) {
2019 return;
2020 }
2021
2022 // Only update thumbnails for web urls (http(s)://), not for
2023 // about:, javascript:, data:, etc...
2024 // Unless it is a bookmarked site, then always update
2025 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2026 return;
2027 }
2028
Michael Kolb8233fac2010-10-26 16:08:53 -07002029 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2030 getDesiredThumbnailHeight(mActivity));
2031 if (bm == null) {
2032 return;
2033 }
2034
2035 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002036 new AsyncTask<Void, Void, Void>() {
2037 @Override
2038 protected Void doInBackground(Void... unused) {
2039 Cursor cursor = null;
2040 try {
2041 // TODO: Clean this up
2042 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2043 if (cursor != null && cursor.moveToFirst()) {
2044 final ByteArrayOutputStream os =
2045 new ByteArrayOutputStream();
2046 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002047
John Reck34ef2672011-02-10 11:30:55 -08002048 ContentValues values = new ContentValues();
2049 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002050
John Reck34ef2672011-02-10 11:30:55 -08002051 do {
John Reck617fd832011-02-16 14:35:59 -08002052 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002053 cr.update(Images.CONTENT_URI, values, null, null);
2054 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002055 }
John Reck34ef2672011-02-10 11:30:55 -08002056 } catch (IllegalStateException e) {
2057 // Ignore
2058 } finally {
2059 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002060 }
John Reck34ef2672011-02-10 11:30:55 -08002061 return null;
2062 }
2063 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002064 }
2065
2066 private class Copy implements OnMenuItemClickListener {
2067 private CharSequence mText;
2068
2069 public boolean onMenuItemClick(MenuItem item) {
2070 copy(mText);
2071 return true;
2072 }
2073
2074 public Copy(CharSequence toCopy) {
2075 mText = toCopy;
2076 }
2077 }
2078
Leon Scroggins63c02662010-11-18 15:16:27 -05002079 private static class Download implements OnMenuItemClickListener {
2080 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002081 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002082 private boolean mPrivateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002083
2084 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002085 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002086 null, null, mPrivateBrowsing);
Michael Kolb8233fac2010-10-26 16:08:53 -07002087 return true;
2088 }
2089
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002090 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002091 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002092 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002093 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002094 }
2095 }
2096
Cary Clark8974d282010-11-22 10:46:05 -05002097 private static class SelectText implements OnMenuItemClickListener {
2098 private WebView mWebView;
2099
2100 public boolean onMenuItemClick(MenuItem item) {
2101 if (mWebView != null) {
2102 return mWebView.selectText();
2103 }
2104 return false;
2105 }
2106
2107 public SelectText(WebView webView) {
2108 mWebView = webView;
2109 }
2110
2111 }
2112
Michael Kolb8233fac2010-10-26 16:08:53 -07002113 /********************** TODO: UI stuff *****************************/
2114
2115 // these methods have been copied, they still need to be cleaned up
2116
2117 /****************** tabs ***************************************************/
2118
2119 // basic tab interactions:
2120
2121 // it is assumed that tabcontrol already knows about the tab
2122 protected void addTab(Tab tab) {
2123 mUi.addTab(tab);
2124 }
2125
2126 protected void removeTab(Tab tab) {
2127 mUi.removeTab(tab);
2128 mTabControl.removeTab(tab);
2129 }
2130
2131 protected void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002132 // monkey protection against delayed start
2133 if (tab != null) {
2134 mTabControl.setCurrentTab(tab);
2135 // the tab is guaranteed to have a webview after setCurrentTab
2136 mUi.setActiveTab(tab);
2137 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002138 }
2139
2140 protected void closeEmptyChildTab() {
2141 Tab current = mTabControl.getCurrentTab();
2142 if (current != null
2143 && current.getWebView().copyBackForwardList().getSize() == 0) {
2144 Tab parent = current.getParentTab();
2145 if (parent != null) {
2146 switchToTab(mTabControl.getTabIndex(parent));
2147 closeTab(current);
2148 }
2149 }
2150 }
2151
2152 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002153 // Dismiss the subwindow if applicable.
2154 dismissSubWindow(appTab);
2155 // Since we might kill the WebView, remove it from the
2156 // content view first.
2157 mUi.detachTab(appTab);
2158 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002159 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002160 // TODO: analyze why the remove and add are necessary
2161 mUi.attachTab(appTab);
2162 if (mTabControl.getCurrentTab() != appTab) {
2163 switchToTab(mTabControl.getTabIndex(appTab));
John Reck30c714c2010-12-16 17:30:34 -08002164 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002165 } else {
2166 // If the tab was the current tab, we have to attach
2167 // it to the view system again.
2168 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002169 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002170 }
2171 }
2172
2173 // Remove the sub window if it exists. Also called by TabControl when the
2174 // user clicks the 'X' to dismiss a sub window.
2175 public void dismissSubWindow(Tab tab) {
2176 removeSubWindow(tab);
2177 // dismiss the subwindow. This will destroy the WebView.
2178 tab.dismissSubWindow();
2179 getCurrentTopWebView().requestFocus();
2180 }
2181
2182 @Override
2183 public void removeSubWindow(Tab t) {
2184 if (t.getSubWebView() != null) {
2185 mUi.removeSubWindow(t.getSubViewContainer());
2186 }
2187 }
2188
2189 @Override
2190 public void attachSubWindow(Tab tab) {
2191 if (tab.getSubWebView() != null) {
2192 mUi.attachSubWindow(tab.getSubViewContainer());
2193 getCurrentTopWebView().requestFocus();
2194 }
2195 }
2196
Michael Kolb843510f2010-12-09 10:51:49 -08002197 @Override
2198 public Tab openTabToHomePage() {
2199 // check for max tabs
2200 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002201 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2202 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002203 } else {
2204 mUi.showMaxTabsWarning();
2205 return null;
2206 }
2207 }
2208
Michael Kolb18eb3772010-12-10 14:29:51 -08002209 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2210 if (mSettings.openInBackground() && !forceForeground) {
2211 Tab tab = mTabControl.createNewTab(false, null, null,
2212 (parent != null) && parent.isPrivateBrowsingEnabled());
2213 if (tab != null) {
2214 addTab(tab);
2215 WebView view = tab.getWebView();
2216 loadUrl(view, url);
2217 }
2218 return tab;
2219 } else {
2220 return openTabAndShow(parent, new UrlData(url), false, null);
2221 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002222 }
2223
Michael Kolb18eb3772010-12-10 14:29:51 -08002224
Michael Kolb8233fac2010-10-26 16:08:53 -07002225 // This method does a ton of stuff. It will attempt to create a new tab
2226 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2227 // url isn't null, it will load the given url.
Patrick Scottcd135082011-01-31 18:21:58 -05002228 public Tab openTabAndShow(Tab parent, final UrlData urlData,
2229 boolean closeOnExit, String appId) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002230 final Tab currentTab = mTabControl.getCurrentTab();
2231 if (mTabControl.canCreateNewTab()) {
2232 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Michael Kolb18eb3772010-12-10 14:29:51 -08002233 urlData.mUrl,
2234 (parent != null) && parent.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -07002235 WebView webview = tab.getWebView();
2236 // We must set the new tab as the current tab to reflect the old
2237 // animation behavior.
2238 addTab(tab);
2239 setActiveTab(tab);
Patrick Scottd43e75a2011-03-14 14:47:23 -04002240 if (!urlData.isEmpty()) {
2241 loadUrlDataIn(tab, urlData);
2242 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002243 return tab;
2244 } else {
2245 // Get rid of the subwindow if it exists
2246 dismissSubWindow(currentTab);
2247 if (!urlData.isEmpty()) {
2248 // Load the given url.
2249 loadUrlDataIn(currentTab, urlData);
2250 }
2251 return currentTab;
2252 }
2253 }
2254
Michael Kolb8233fac2010-10-26 16:08:53 -07002255 @Override
2256 public Tab openIncognitoTab() {
2257 if (mTabControl.canCreateNewTab()) {
2258 Tab currentTab = mTabControl.getCurrentTab();
Michael Kolb8e7178d2011-01-26 19:13:36 -08002259 Tab tab = mTabControl.createNewTab(false, null,
John Reck4bfc0db2011-01-27 17:47:12 -08002260 null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07002261 addTab(tab);
2262 setActiveTab(tab);
John Reck4bfc0db2011-01-27 17:47:12 -08002263 loadUrlDataIn(tab, new UrlData("browser:incognito"));
Michael Kolb8233fac2010-10-26 16:08:53 -07002264 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002265 } else {
2266 mUi.showMaxTabsWarning();
2267 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002268 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002269 }
2270
2271 /**
2272 * @param index Index of the tab to change to, as defined by
2273 * mTabControl.getTabIndex(Tab t).
2274 * @return boolean True if we successfully switched to a different tab. If
2275 * the indexth tab is null, or if that tab is the same as
2276 * the current one, return false.
2277 */
2278 @Override
2279 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002280 // hide combo view if open
2281 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002282 Tab tab = mTabControl.getTab(index);
2283 Tab currentTab = mTabControl.getCurrentTab();
2284 if (tab == null || tab == currentTab) {
2285 return false;
2286 }
2287 setActiveTab(tab);
2288 return true;
2289 }
2290
2291 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002292 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002293 // hide combo view if open
2294 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002295 final Tab current = mTabControl.getCurrentTab();
2296 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002297 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002298 return;
2299 }
2300 final Tab parent = current.getParentTab();
2301 int indexToShow = -1;
2302 if (parent != null) {
2303 indexToShow = mTabControl.getTabIndex(parent);
2304 } else {
2305 final int currentIndex = mTabControl.getCurrentIndex();
2306 // Try to move to the tab to the right
2307 indexToShow = currentIndex + 1;
2308 if (indexToShow > mTabControl.getTabCount() - 1) {
2309 // Try to move to the tab to the left
2310 indexToShow = currentIndex - 1;
2311 }
2312 }
2313 if (switchToTab(indexToShow)) {
2314 // Close window
2315 closeTab(current);
2316 }
2317 }
2318
2319 /**
2320 * Close the tab, remove its associated title bar, and adjust mTabControl's
2321 * current tab to a valid value.
2322 */
2323 @Override
2324 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002325 // hide combo view if open
2326 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002327 int currentIndex = mTabControl.getCurrentIndex();
2328 int removeIndex = mTabControl.getTabIndex(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002329 Tab newtab = mTabControl.getTab(currentIndex);
2330 setActiveTab(newtab);
Michael Kolb2d59c322011-01-25 13:18:55 -08002331 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002332 }
2333
2334 /**************** TODO: Url loading clean up *******************************/
2335
2336 // Called when loading from context menu or LOAD_URL message
2337 protected void loadUrlFromContext(WebView view, String url) {
2338 // In case the user enters nothing.
2339 if (url != null && url.length() != 0 && view != null) {
2340 url = UrlUtils.smartUrlFilter(url);
2341 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2342 loadUrl(view, url);
2343 }
2344 }
2345 }
2346
2347 /**
2348 * Load the URL into the given WebView and update the title bar
2349 * to reflect the new load. Call this instead of WebView.loadUrl
2350 * directly.
2351 * @param view The WebView used to load url.
2352 * @param url The URL to load.
2353 */
2354 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002355 view.loadUrl(url);
2356 }
2357
2358 /**
2359 * Load UrlData into a Tab and update the title bar to reflect the new
2360 * load. Call this instead of UrlData.loadIn directly.
2361 * @param t The Tab used to load.
2362 * @param data The UrlData being loaded.
2363 */
2364 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002365 data.loadIn(t);
2366 }
2367
John Reck30c714c2010-12-16 17:30:34 -08002368 @Override
2369 public void onUserCanceledSsl(Tab tab) {
2370 WebView web = tab.getWebView();
2371 // TODO: Figure out the "right" behavior
2372 if (web.canGoBack()) {
2373 web.goBack();
2374 } else {
2375 web.loadUrl(mSettings.getHomePage());
2376 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002377 }
2378
2379 void goBackOnePageOrQuit() {
2380 Tab current = mTabControl.getCurrentTab();
2381 if (current == null) {
2382 /*
2383 * Instead of finishing the activity, simply push this to the back
2384 * of the stack and let ActivityManager to choose the foreground
2385 * activity. As BrowserActivity is singleTask, it will be always the
2386 * root of the task. So we can use either true or false for
2387 * moveTaskToBack().
2388 */
2389 mActivity.moveTaskToBack(true);
2390 return;
2391 }
2392 WebView w = current.getWebView();
2393 if (w.canGoBack()) {
2394 w.goBack();
2395 } else {
2396 // Check to see if we are closing a window that was created by
2397 // another window. If so, we switch back to that window.
2398 Tab parent = current.getParentTab();
2399 if (parent != null) {
2400 switchToTab(mTabControl.getTabIndex(parent));
2401 // Now we close the other tab
2402 closeTab(current);
2403 } else {
2404 if (current.closeOnExit()) {
Patrick Scottfc1518a2011-02-28 13:57:03 -05002405 // This will finish the activity if there is only one tab
2406 // open or it will switch to the next available tab if
2407 // available.
Michael Kolb96683f72011-02-15 14:24:35 -08002408 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002409 }
2410 /*
2411 * Instead of finishing the activity, simply push this to the back
2412 * of the stack and let ActivityManager to choose the foreground
2413 * activity. As BrowserActivity is singleTask, it will be always the
2414 * root of the task. So we can use either true or false for
2415 * moveTaskToBack().
2416 */
2417 mActivity.moveTaskToBack(true);
2418 }
2419 }
2420 }
2421
2422 /**
2423 * Feed the previously stored results strings to the BrowserProvider so that
2424 * the SearchDialog will show them instead of the standard searches.
2425 * @param result String to show on the editable line of the SearchDialog.
2426 */
2427 @Override
2428 public void showVoiceSearchResults(String result) {
2429 ContentProviderClient client = mActivity.getContentResolver()
2430 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2431 ContentProvider prov = client.getLocalContentProvider();
2432 BrowserProvider bp = (BrowserProvider) prov;
2433 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2434 client.release();
2435
2436 Bundle bundle = createGoogleSearchSourceBundle(
2437 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2438 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2439 startSearch(result, false, bundle, false);
2440 }
2441
2442 private void startSearch(String initialQuery, boolean selectInitialQuery,
2443 Bundle appSearchData, boolean globalSearch) {
2444 if (appSearchData == null) {
2445 appSearchData = createGoogleSearchSourceBundle(
2446 GOOGLE_SEARCH_SOURCE_TYPE);
2447 }
2448
2449 SearchEngine searchEngine = mSettings.getSearchEngine();
2450 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2451 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2452 }
2453 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2454 globalSearch);
2455 }
2456
2457 private Bundle createGoogleSearchSourceBundle(String source) {
2458 Bundle bundle = new Bundle();
2459 bundle.putString(Search.SOURCE, source);
2460 return bundle;
2461 }
2462
2463 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002464 * helper method for key handler
2465 * returns the current tab if it can't advance
2466 */
2467 private int getNextTabIndex() {
2468 return Math.min(mTabControl.getTabCount() - 1,
2469 mTabControl.getCurrentIndex() + 1);
2470 }
2471
2472 /**
2473 * helper method for key handler
2474 * returns the current tab if it can't advance
2475 */
2476 private int getPrevTabIndex() {
2477 return Math.max(0, mTabControl.getCurrentIndex() - 1);
2478 }
2479
2480 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002481 * handle key events in browser
2482 *
2483 * @param keyCode
2484 * @param event
2485 * @return true if handled, false to pass to super
2486 */
2487 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002488 boolean noModifiers = event.hasNoModifiers();
2489
Michael Kolb8233fac2010-10-26 16:08:53 -07002490 // Even if MENU is already held down, we need to call to super to open
2491 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002492 if (!noModifiers
2493 && ((KeyEvent.KEYCODE_MENU == keyCode)
2494 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2495 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002496 mMenuIsDown = true;
2497 return false;
2498 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002499
Cary Clark8ff8c662010-12-29 15:03:05 -05002500 WebView webView = getCurrentTopWebView();
2501 if (webView == null) return false;
2502
Cary Clark160bbb92011-01-10 11:17:07 -05002503 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2504 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002505
Michael Kolb8233fac2010-10-26 16:08:53 -07002506 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002507 case KeyEvent.KEYCODE_TAB:
2508 if (event.isCtrlPressed()) {
2509 if (event.isShiftPressed()) {
2510 // prev tab
2511 switchToTab(getPrevTabIndex());
2512 } else {
2513 // next tab
2514 switchToTab(getNextTabIndex());
2515 }
2516 return true;
2517 }
2518 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002519 case KeyEvent.KEYCODE_SPACE:
2520 // WebView/WebTextView handle the keys in the KeyDown. As
2521 // the Activity's shortcut keys are only handled when WebView
2522 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002523 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002524 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002525 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002526 pageDown();
2527 }
2528 return true;
2529 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002530 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002531 event.startTracking();
2532 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002533 case KeyEvent.KEYCODE_DPAD_LEFT:
2534 if (ctrl) {
2535 webView.goBack();
2536 return true;
2537 }
2538 break;
2539 case KeyEvent.KEYCODE_DPAD_RIGHT:
2540 if (ctrl) {
2541 webView.goForward();
2542 return true;
2543 }
2544 break;
2545 case KeyEvent.KEYCODE_A:
2546 if (ctrl) {
2547 webView.selectAll();
2548 return true;
2549 }
2550 break;
Michael Kolba4183062011-01-16 10:43:21 -08002551// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002552 case KeyEvent.KEYCODE_C:
2553 if (ctrl) {
2554 webView.copySelection();
2555 return true;
2556 }
2557 break;
Michael Kolba4183062011-01-16 10:43:21 -08002558// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002559// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002560// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002561// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002562// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002563// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002564// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002565// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002566// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002567// case KeyEvent.KEYCODE_M: // unused
2568// case KeyEvent.KEYCODE_N: // in Chrome: new window
2569// case KeyEvent.KEYCODE_O: // in Chrome: open file
2570// case KeyEvent.KEYCODE_P: // in Chrome: print page
2571// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002572// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002573// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2574 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002575 // we can't use the ctrl/shift flags, they check for
2576 // exclusive use of a modifier
2577 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002578 if (event.isShiftPressed()) {
2579 openIncognitoTab();
2580 } else {
2581 openTabToHomePage();
2582 }
2583 return true;
2584 }
2585 break;
2586// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2587// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb1a2eba42011-03-16 16:42:49 -07002588 case KeyEvent.KEYCODE_W: // in Chrome: close tab
2589 if (ctrl) {
2590 closeCurrentTab();
2591 return true;
2592 }
2593 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002594// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2595// case KeyEvent.KEYCODE_Y: // unused
2596// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002597 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002598 // it is a regular key and webview is not null
2599 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002600 }
2601
John Recke6bf4ab2011-02-24 15:48:05 -08002602 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2603 switch(keyCode) {
2604 case KeyEvent.KEYCODE_BACK:
2605 if (mUi.showsWeb()) {
2606 bookmarksOrHistoryPicker(true);
2607 return true;
2608 }
2609 break;
2610 }
2611 return false;
2612 }
2613
Michael Kolb8233fac2010-10-26 16:08:53 -07002614 boolean onKeyUp(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002615 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002616 switch(keyCode) {
2617 case KeyEvent.KEYCODE_MENU:
2618 mMenuIsDown = false;
2619 break;
2620 case KeyEvent.KEYCODE_BACK:
2621 if (event.isTracking() && !event.isCanceled()) {
2622 onBackKey();
2623 return true;
2624 }
2625 break;
2626 }
2627 return false;
2628 }
2629
2630 public boolean isMenuDown() {
2631 return mMenuIsDown;
2632 }
2633
Ben Murdoch8029a772010-11-16 11:58:21 +00002634 public void setupAutoFill(Message message) {
2635 // Open the settings activity at the AutoFill profile fragment so that
2636 // the user can create a new profile. When they return, we will dispatch
2637 // the message so that we can autofill the form using their new profile.
2638 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2639 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2640 AutoFillSettingsFragment.class.getName());
2641 mAutoFillSetupMessage = message;
2642 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2643 }
John Reckb3417f02011-01-14 11:01:05 -08002644
2645 @Override
2646 public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
2647 mOptionsMenuHandler = handler;
2648 }
2649
2650 @Override
2651 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
2652 if (mOptionsMenuHandler == handler) {
2653 mOptionsMenuHandler = null;
2654 }
2655 }
2656
Narayan Kamath5119edd2011-02-23 15:49:17 +00002657 @Override
2658 public void registerDropdownChangeListener(DropdownChangeListener d) {
2659 mUi.registerDropdownChangeListener(d);
2660 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002661}