blob: 5498d6d424d12c8d7f31816964c38c2058c5b256 [file] [log] [blame]
Michael Kolb8233fac2010-10-26 16:08:53 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
19import com.android.browser.IntentHandler.UrlData;
Narayan Kamath5119edd2011-02-23 15:49:17 +000020import com.android.browser.UI.DropdownChangeListener;
Michael Kolb8233fac2010-10-26 16:08:53 -070021import com.android.browser.search.SearchEngine;
22import com.android.common.Search;
23
24import android.app.Activity;
25import android.app.DownloadManager;
26import android.app.SearchManager;
27import android.content.ClipboardManager;
28import android.content.ContentProvider;
29import android.content.ContentProviderClient;
30import android.content.ContentResolver;
31import android.content.ContentValues;
32import android.content.Context;
33import android.content.Intent;
34import android.content.pm.PackageManager;
35import android.content.pm.ResolveInfo;
36import android.content.res.Configuration;
Leon Scroggins1961ed22010-12-07 15:22:21 -050037import android.database.ContentObserver;
Michael Kolb8233fac2010-10-26 16:08:53 -070038import android.database.Cursor;
39import android.database.sqlite.SQLiteDatabase;
Michael Kolb8233fac2010-10-26 16:08:53 -070040import android.graphics.Bitmap;
41import android.graphics.Canvas;
42import android.graphics.Picture;
43import android.net.Uri;
44import android.net.http.SslError;
45import android.os.AsyncTask;
46import android.os.Bundle;
Leon Scrogginsac993842011-02-02 12:54:07 -050047import android.os.Environment;
Michael Kolb8233fac2010-10-26 16:08:53 -070048import android.os.Handler;
49import android.os.Message;
50import android.os.PowerManager;
51import android.os.PowerManager.WakeLock;
Ben Murdoch8029a772010-11-16 11:58:21 +000052import android.preference.PreferenceActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -070053import android.provider.Browser;
54import android.provider.BrowserContract;
Michael Kolb8233fac2010-10-26 16:08:53 -070055import android.provider.BrowserContract.Images;
56import android.provider.ContactsContract;
57import android.provider.ContactsContract.Intents.Insert;
Michael Kolbcfa3af52010-12-14 10:36:11 -080058import android.speech.RecognizerIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070059import android.speech.RecognizerResultsIntent;
60import android.text.TextUtils;
61import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080062import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070063import android.view.ActionMode;
64import android.view.ContextMenu;
65import android.view.ContextMenu.ContextMenuInfo;
66import android.view.Gravity;
67import android.view.KeyEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070068import android.view.Menu;
69import android.view.MenuInflater;
70import android.view.MenuItem;
71import android.view.MenuItem.OnMenuItemClickListener;
72import android.view.View;
73import android.webkit.CookieManager;
74import android.webkit.CookieSyncManager;
75import android.webkit.HttpAuthHandler;
76import android.webkit.SslErrorHandler;
77import android.webkit.ValueCallback;
78import android.webkit.WebChromeClient;
79import android.webkit.WebIconDatabase;
80import android.webkit.WebSettings;
81import android.webkit.WebView;
Leon Scrogginsac993842011-02-02 12:54:07 -050082import android.widget.Toast;
Michael Kolb8233fac2010-10-26 16:08:53 -070083
84import java.io.ByteArrayOutputStream;
85import java.io.File;
86import java.net.URLEncoder;
87import java.util.Calendar;
88import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -080089import java.util.List;
Michael Kolb8233fac2010-10-26 16:08:53 -070090
91/**
92 * Controller for browser
93 */
94public class Controller
95 implements WebViewController, UiController {
96
97 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -080098 private static final String SEND_APP_ID_EXTRA =
99 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
100
Michael Kolb8233fac2010-10-26 16:08:53 -0700101
102 // public message ids
103 public final static int LOAD_URL = 1001;
104 public final static int STOP_LOAD = 1002;
105
106 // Message Ids
107 private static final int FOCUS_NODE_HREF = 102;
108 private static final int RELEASE_WAKELOCK = 107;
109
110 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
111
112 private static final int OPEN_BOOKMARKS = 201;
113
114 private static final int EMPTY_MENU = -1;
115
Michael Kolb8233fac2010-10-26 16:08:53 -0700116 // activity requestCode
117 final static int PREFERENCES_PAGE = 3;
118 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000119 final static int AUTOFILL_SETUP = 5;
120
Michael Kolb8233fac2010-10-26 16:08:53 -0700121 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
122
123 // As the ids are dynamically created, we can't guarantee that they will
124 // be in sequence, so this static array maps ids to a window number.
125 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
126 { R.id.window_one_menu_id, R.id.window_two_menu_id,
127 R.id.window_three_menu_id, R.id.window_four_menu_id,
128 R.id.window_five_menu_id, R.id.window_six_menu_id,
129 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
130
131 // "source" parameter for Google search through search key
132 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
133 // "source" parameter for Google search through simplily type
134 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
135
Guang Zhu9e78f512011-05-04 11:45:11 -0700136 // "no-crash-recovery" parameter in intetnt to suppress crash recovery
137 final static String NO_CRASH_RECOVERY = "no-crash-recovery";
138
Michael Kolb8233fac2010-10-26 16:08:53 -0700139 private Activity mActivity;
140 private UI mUi;
141 private TabControl mTabControl;
142 private BrowserSettings mSettings;
143 private WebViewFactory mFactory;
John Reckb3417f02011-01-14 11:01:05 -0800144 private OptionsMenuHandler mOptionsMenuHandler = null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700145
146 private WakeLock mWakeLock;
147
148 private UrlHandler mUrlHandler;
149 private UploadHandler mUploadHandler;
150 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700151 private PageDialogsHandler mPageDialogsHandler;
152 private NetworkStateHandler mNetworkHandler;
153
Ben Murdoch8029a772010-11-16 11:58:21 +0000154 private Message mAutoFillSetupMessage;
155
Michael Kolb8233fac2010-10-26 16:08:53 -0700156 private boolean mShouldShowErrorConsole;
157
158 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
159
160 // FIXME, temp address onPrepareMenu performance problem.
161 // When we move everything out of view, we should rewrite this.
162 private int mCurrentMenuState = 0;
163 private int mMenuState = R.id.MAIN_MENU;
164 private int mOldMenuState = EMPTY_MENU;
165 private Menu mCachedMenu;
166
Michael Kolb8233fac2010-10-26 16:08:53 -0700167 private boolean mMenuIsDown;
168
169 // For select and find, we keep track of the ActionMode so that
170 // finish() can be called as desired.
171 private ActionMode mActionMode;
172
173 /**
174 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
175 * of whether the configuration has changed. The first onMenuOpened call
176 * after a configuration change is simply a reopening of the same menu
177 * (i.e. mIconView did not change).
178 */
179 private boolean mConfigChanged;
180
181 /**
182 * Keeps track of whether the options menu is open. This is important in
183 * determining whether to show or hide the title bar overlay
184 */
185 private boolean mOptionsMenuOpen;
186
187 /**
188 * Whether or not the options menu is in its bigger, popup menu form. When
189 * true, we want the title bar overlay to be gone. When false, we do not.
190 * Only meaningful if mOptionsMenuOpen is true.
191 */
192 private boolean mExtendedMenuOpen;
193
194 private boolean mInLoad;
195
196 private boolean mActivityPaused = true;
197 private boolean mLoadStopped;
198
199 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500200 // Checks to see when the bookmarks database has changed, and updates the
201 // Tabs' notion of whether they represent bookmarked sites.
202 private ContentObserver mBookmarksObserver;
John Reck0ebd3ac2010-12-09 11:14:04 -0800203 private DataController mDataController;
John Reck847b5322011-04-14 17:02:18 -0700204 private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700205
206 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
207 @Override
208 public Void doInBackground(File... files) {
209 if (files != null) {
210 for (File f : files) {
211 if (!f.delete()) {
212 Log.e(LOGTAG, f.getPath() + " was not deleted");
213 }
214 }
215 }
216 return null;
217 }
218 }
219
220 public Controller(Activity browser) {
221 mActivity = browser;
222 mSettings = BrowserSettings.getInstance();
John Reck0ebd3ac2010-12-09 11:14:04 -0800223 mDataController = DataController.getInstance(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700224 mTabControl = new TabControl(this);
225 mSettings.setController(this);
John Reck847b5322011-04-14 17:02:18 -0700226 mCrashRecoveryHandler = new CrashRecoveryHandler(this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700227
228 mUrlHandler = new UrlHandler(this);
229 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700230 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
231
232 PowerManager pm = (PowerManager) mActivity
233 .getSystemService(Context.POWER_SERVICE);
234 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
235
236 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500237 mBookmarksObserver = new ContentObserver(mHandler) {
238 @Override
239 public void onChange(boolean selfChange) {
240 int size = mTabControl.getTabCount();
241 for (int i = 0; i < size; i++) {
242 mTabControl.getTab(i).updateBookmarkedStatus();
243 }
244 }
245
246 };
247 browser.getContentResolver().registerContentObserver(
248 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700249
250 mNetworkHandler = new NetworkStateHandler(mActivity, this);
251 // Start watching the default geolocation permissions
252 mSystemAllowGeolocationOrigins =
253 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
254 mSystemAllowGeolocationOrigins.start();
255
256 retainIconsOnStartup();
257 }
258
Patrick Scott7d50a932011-02-04 09:27:26 -0500259 void start(final Bundle icicle, final Intent intent) {
Guang Zhu9e78f512011-05-04 11:45:11 -0700260 boolean noCrashRecovery = intent.getBooleanExtra(NO_CRASH_RECOVERY, false);
261 if (icicle != null || noCrashRecovery) {
John Reck847b5322011-04-14 17:02:18 -0700262 mCrashRecoveryHandler.clearState();
263 doStart(icicle, intent);
264 } else {
265 mCrashRecoveryHandler.startRecovery(intent);
266 }
267 }
268
269 void doStart(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700270 // Unless the last browser usage was within 24 hours, destroy any
271 // remaining incognito tabs.
272
273 Calendar lastActiveDate = icicle != null ?
274 (Calendar) icicle.getSerializable("lastActiveDate") : null;
275 Calendar today = Calendar.getInstance();
276 Calendar yesterday = Calendar.getInstance();
277 yesterday.add(Calendar.DATE, -1);
278
Patrick Scott7d50a932011-02-04 09:27:26 -0500279 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700280 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800281 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700282
Patrick Scott7d50a932011-02-04 09:27:26 -0500283 // Find out if we will restore any state and remember the tab.
284 final int currentTab =
285 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000286
Patrick Scott7d50a932011-02-04 09:27:26 -0500287 if (currentTab == -1) {
288 // Not able to restore so we go ahead and clear session cookies. We
289 // must do this before trying to login the user as we don't want to
290 // clear any session cookies set during login.
291 CookieManager.getInstance().removeSessionCookie();
292 }
293
Patrick Scottd43e75a2011-03-14 14:47:23 -0400294 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500295 new Runnable() {
296 @Override public void run() {
John Reck847b5322011-04-14 17:02:18 -0700297 onPreloginFinished(icicle, intent, currentTab, restoreIncognitoTabs);
Patrick Scott7d50a932011-02-04 09:27:26 -0500298 }
299 });
300 }
301
John Reck847b5322011-04-14 17:02:18 -0700302 private void onPreloginFinished(Bundle icicle, Intent intent, int currentTab,
Patrick Scott7d50a932011-02-04 09:27:26 -0500303 boolean restoreIncognitoTabs) {
304 if (currentTab == -1) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700305 final Bundle extra = intent.getExtras();
306 // Create an initial tab.
307 // If the intent is ACTION_VIEW and data is not null, the Browser is
308 // invoked to view the content by another application. In this case,
309 // the tab will be close when exit.
310 UrlData urlData = mIntentHandler.getUrlDataFromIntent(intent);
311
312 String action = intent.getAction();
313 final Tab t = mTabControl.createNewTab(
314 (Intent.ACTION_VIEW.equals(action) &&
315 intent.getData() != null)
316 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
317 .equals(action),
318 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
319 urlData.mUrl, false);
320 addTab(t);
321 setActiveTab(t);
322 WebView webView = t.getWebView();
323 if (extra != null) {
324 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
325 if (scale > 0 && scale <= 1000) {
326 webView.setInitialScale(scale);
327 }
328 }
329
330 if (urlData.isEmpty()) {
331 loadUrl(webView, mSettings.getHomePage());
332 } else {
Michael Kolbcd424e92011-02-24 10:26:26 -0800333 // monkey protection against delayed start
334 if (t != null) {
335 loadUrlDataIn(t, urlData);
336 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700337 }
338 } else {
Patrick Scott7d50a932011-02-04 09:27:26 -0500339 mTabControl.restoreState(icicle, currentTab, restoreIncognitoTabs,
340 mUi.needsRestoreAllTabs());
Michael Kolb1bf23132010-11-19 12:55:12 -0800341 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700342 // TabControl.restoreState() will create a new tab even if
343 // restoring the state fails.
344 setActiveTab(mTabControl.getCurrentTab());
345 }
346 // clear up the thumbnail directory, which is no longer used;
347 // ideally this should only be run once after an upgrade from
348 // a previous version of the browser
349 new ClearThumbnails().execute(mTabControl.getThumbnailDir()
350 .listFiles());
351 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700352 String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb8233fac2010-10-26 16:08:53 -0700353 if (jsFlags.trim().length() != 0) {
354 getCurrentWebView().setJsFlags(jsFlags);
355 }
John Reck439c9a52010-12-14 10:04:39 -0800356 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
357 bookmarksOrHistoryPicker(false);
358 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700359 }
360
361 void setWebViewFactory(WebViewFactory factory) {
362 mFactory = factory;
363 }
364
Michael Kolb1514bb72010-11-22 09:11:48 -0800365 @Override
366 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700367 return mFactory;
368 }
369
370 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800371 public void onSetWebView(Tab tab, WebView view) {
372 mUi.onSetWebView(tab, view);
373 }
374
375 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800376 public void createSubWindow(Tab tab) {
377 endActionMode();
378 WebView mainView = tab.getWebView();
379 WebView subView = mFactory.createWebView((mainView == null)
380 ? false
381 : mainView.isPrivateBrowsingEnabled());
382 mUi.createSubWindow(tab, subView);
383 }
384
385 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700386 public Activity getActivity() {
387 return mActivity;
388 }
389
390 void setUi(UI ui) {
391 mUi = ui;
392 }
393
394 BrowserSettings getSettings() {
395 return mSettings;
396 }
397
398 IntentHandler getIntentHandler() {
399 return mIntentHandler;
400 }
401
402 @Override
403 public UI getUi() {
404 return mUi;
405 }
406
407 int getMaxTabs() {
408 return mActivity.getResources().getInteger(R.integer.max_tabs);
409 }
410
411 @Override
412 public TabControl getTabControl() {
413 return mTabControl;
414 }
415
Michael Kolb1bf23132010-11-19 12:55:12 -0800416 @Override
417 public List<Tab> getTabs() {
418 return mTabControl.getTabs();
419 }
420
Michael Kolb8233fac2010-10-26 16:08:53 -0700421 // Open the icon database and retain all the icons for visited sites.
Ben Murdoch9446b932010-11-25 16:20:14 +0000422 // This is done on a background thread so as not to stall startup.
Michael Kolb8233fac2010-10-26 16:08:53 -0700423 private void retainIconsOnStartup() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000424 // WebIconDatabase needs to be retrieved on the UI thread so that if
425 // it has not been created successfully yet the Handler is started on the
426 // UI thread.
427 new RetainIconsOnStartupTask(WebIconDatabase.getInstance()).execute();
428 }
429
430 private class RetainIconsOnStartupTask extends AsyncTask<Void, Void, Void> {
431 private WebIconDatabase mDb;
432
433 public RetainIconsOnStartupTask(WebIconDatabase db) {
434 mDb = db;
435 }
436
John Recka00cbbd2010-12-16 12:38:19 -0800437 @Override
Ben Murdoch9446b932010-11-25 16:20:14 +0000438 protected Void doInBackground(Void... unused) {
439 mDb.open(mActivity.getDir("icons", 0).getPath());
440 Cursor c = null;
441 try {
442 c = Browser.getAllBookmarks(mActivity.getContentResolver());
443 if (c.moveToFirst()) {
444 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
445 do {
446 String url = c.getString(urlIndex);
447 mDb.retainIconForPageUrl(url);
448 } while (c.moveToNext());
449 }
450 } catch (IllegalStateException e) {
451 Log.e(LOGTAG, "retainIconsOnStartup", e);
452 } finally {
453 if (c != null) c.close();
Michael Kolb8233fac2010-10-26 16:08:53 -0700454 }
Ben Murdoch9446b932010-11-25 16:20:14 +0000455
456 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700457 }
458 }
459
460 private void startHandler() {
461 mHandler = new Handler() {
462
463 @Override
464 public void handleMessage(Message msg) {
465 switch (msg.what) {
466 case OPEN_BOOKMARKS:
467 bookmarksOrHistoryPicker(false);
468 break;
469 case FOCUS_NODE_HREF:
470 {
471 String url = (String) msg.getData().get("url");
472 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500473 String src = (String) msg.getData().get("src");
474 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700475 if (TextUtils.isEmpty(url)) {
476 break;
477 }
478 HashMap focusNodeMap = (HashMap) msg.obj;
479 WebView view = (WebView) focusNodeMap.get("webview");
480 // Only apply the action if the top window did not change.
481 if (getCurrentTopWebView() != view) {
482 break;
483 }
484 switch (msg.arg1) {
485 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -0700486 loadUrlFromContext(getCurrentTopWebView(), url);
487 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500488 case R.id.view_image_context_menu_id:
489 loadUrlFromContext(getCurrentTopWebView(), src);
490 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500491 case R.id.open_newtab_context_menu_id:
492 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -0800493 final Tab newTab = openTab(parent, url, false);
Leon Scroggins026f2542010-11-22 13:26:12 -0500494 if (newTab != null && newTab != parent) {
495 parent.addChildTab(newTab);
496 }
497 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700498 case R.id.copy_link_context_menu_id:
499 copy(url);
500 break;
501 case R.id.save_link_context_menu_id:
502 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500503 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000504 mActivity, url, null, null, null,
505 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700506 break;
507 }
508 break;
509 }
510
511 case LOAD_URL:
512 loadUrlFromContext(getCurrentTopWebView(), (String) msg.obj);
513 break;
514
515 case STOP_LOAD:
516 stopLoading();
517 break;
518
519 case RELEASE_WAKELOCK:
520 if (mWakeLock.isHeld()) {
521 mWakeLock.release();
522 // if we reach here, Browser should be still in the
523 // background loading after WAKELOCK_TIMEOUT (5-min).
524 // To avoid burning the battery, stop loading.
525 mTabControl.stopAllLoading();
526 }
527 break;
528
529 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800530 Tab tab = (Tab) msg.obj;
531 if (tab != null) {
532 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700533 }
534 break;
535 }
536 }
537 };
538
539 }
540
Michael Kolbba99c5d2010-11-29 14:57:41 -0800541 @Override
542 public void shareCurrentPage() {
543 shareCurrentPage(mTabControl.getCurrentTab());
544 }
545
546 private void shareCurrentPage(Tab tab) {
547 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800548 sharePage(mActivity, tab.getTitle(),
549 tab.getUrl(), tab.getFavicon(),
550 createScreenshot(tab.getWebView(),
551 getDesiredThumbnailWidth(mActivity),
552 getDesiredThumbnailHeight(mActivity)));
553 }
554 }
555
Michael Kolb8233fac2010-10-26 16:08:53 -0700556 /**
557 * Share a page, providing the title, url, favicon, and a screenshot. Uses
558 * an {@link Intent} to launch the Activity chooser.
559 * @param c Context used to launch a new Activity.
560 * @param title Title of the page. Stored in the Intent with
561 * {@link Intent#EXTRA_SUBJECT}
562 * @param url URL of the page. Stored in the Intent with
563 * {@link Intent#EXTRA_TEXT}
564 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
565 * with {@link Browser#EXTRA_SHARE_FAVICON}
566 * @param screenshot Bitmap of a screenshot of the page. Stored in the
567 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
568 */
569 static final void sharePage(Context c, String title, String url,
570 Bitmap favicon, Bitmap screenshot) {
571 Intent send = new Intent(Intent.ACTION_SEND);
572 send.setType("text/plain");
573 send.putExtra(Intent.EXTRA_TEXT, url);
574 send.putExtra(Intent.EXTRA_SUBJECT, title);
575 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
576 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
577 try {
578 c.startActivity(Intent.createChooser(send, c.getString(
579 R.string.choosertitle_sharevia)));
580 } catch(android.content.ActivityNotFoundException ex) {
581 // if no app handles it, do nothing
582 }
583 }
584
585 private void copy(CharSequence text) {
586 ClipboardManager cm = (ClipboardManager) mActivity
587 .getSystemService(Context.CLIPBOARD_SERVICE);
588 cm.setText(text);
589 }
590
591 // lifecycle
592
593 protected void onConfgurationChanged(Configuration config) {
594 mConfigChanged = true;
595 if (mPageDialogsHandler != null) {
596 mPageDialogsHandler.onConfigurationChanged(config);
597 }
598 mUi.onConfigurationChanged(config);
599 }
600
601 @Override
602 public void handleNewIntent(Intent intent) {
603 mIntentHandler.onNewIntent(intent);
604 }
605
606 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800607 if (mUi.isCustomViewShowing()) {
608 hideCustomView();
609 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700610 if (mActivityPaused) {
611 Log.e(LOGTAG, "BrowserActivity is already paused.");
612 return;
613 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700614 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800615 Tab tab = mTabControl.getCurrentTab();
616 if (tab != null) {
617 tab.pause();
618 if (!pauseWebViewTimers(tab)) {
619 mWakeLock.acquire();
620 mHandler.sendMessageDelayed(mHandler
621 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
622 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700623 }
624 mUi.onPause();
625 mNetworkHandler.onPause();
626
627 WebView.disablePlatformNotifications();
John Reck847b5322011-04-14 17:02:18 -0700628 mCrashRecoveryHandler.clearState();
Michael Kolb8233fac2010-10-26 16:08:53 -0700629 }
630
631 void onSaveInstanceState(Bundle outState) {
632 // the default implementation requires each view to have an id. As the
633 // browser handles the state itself and it doesn't use id for the views,
634 // don't call the default implementation. Otherwise it will trigger the
635 // warning like this, "couldn't save which view has focus because the
636 // focused view XXX has no id".
637
638 // Save all the tabs
639 mTabControl.saveState(outState);
640 // Save time so that we know how old incognito tabs (if any) are.
641 outState.putSerializable("lastActiveDate", Calendar.getInstance());
642 }
643
644 void onResume() {
645 if (!mActivityPaused) {
646 Log.e(LOGTAG, "BrowserActivity is already resumed.");
647 return;
648 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700649 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800650 Tab current = mTabControl.getCurrentTab();
651 if (current != null) {
652 current.resume();
653 resumeWebViewTimers(current);
654 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700655 if (mWakeLock.isHeld()) {
656 mHandler.removeMessages(RELEASE_WAKELOCK);
657 mWakeLock.release();
658 }
659 mUi.onResume();
660 mNetworkHandler.onResume();
661 WebView.enablePlatformNotifications();
662 }
663
Michael Kolb70976932010-11-30 11:34:01 -0800664 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800665 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800666 * @param tab guaranteed non-null
667 */
668 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700669 boolean inLoad = tab.inPageLoad();
670 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
671 CookieSyncManager.getInstance().startSync();
672 WebView w = tab.getWebView();
673 if (w != null) {
674 w.resumeTimers();
675 }
676 }
677 }
678
Michael Kolb70976932010-11-30 11:34:01 -0800679 /**
680 * Pause all WebView timers using the WebView of the given tab
681 * @param tab
682 * @return true if the timers are paused or tab is null
683 */
684 private boolean pauseWebViewTimers(Tab tab) {
685 if (tab == null) {
686 return true;
687 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700688 CookieSyncManager.getInstance().stopSync();
689 WebView w = getCurrentWebView();
690 if (w != null) {
691 w.pauseTimers();
692 }
693 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700694 }
Michael Kolb70976932010-11-30 11:34:01 -0800695 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700696 }
697
698 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800699 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700700 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
701 mUploadHandler = null;
702 }
703 if (mTabControl == null) return;
704 mUi.onDestroy();
705 // Remove the current tab and sub window
706 Tab t = mTabControl.getCurrentTab();
707 if (t != null) {
708 dismissSubWindow(t);
709 removeTab(t);
710 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500711 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700712 // Destroy all the tabs
713 mTabControl.destroy();
714 WebIconDatabase.getInstance().close();
715 // Stop watching the default geolocation permissions
716 mSystemAllowGeolocationOrigins.stop();
717 mSystemAllowGeolocationOrigins = null;
718 }
719
720 protected boolean isActivityPaused() {
721 return mActivityPaused;
722 }
723
724 protected void onLowMemory() {
725 mTabControl.freeMemory();
726 }
727
728 @Override
729 public boolean shouldShowErrorConsole() {
730 return mShouldShowErrorConsole;
731 }
732
733 protected void setShouldShowErrorConsole(boolean show) {
734 if (show == mShouldShowErrorConsole) {
735 // Nothing to do.
736 return;
737 }
738 mShouldShowErrorConsole = show;
739 Tab t = mTabControl.getCurrentTab();
740 if (t == null) {
741 // There is no current tab so we cannot toggle the error console
742 return;
743 }
744 mUi.setShouldShowErrorConsole(t, show);
745 }
746
747 @Override
748 public void stopLoading() {
749 mLoadStopped = true;
750 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700751 WebView w = getCurrentTopWebView();
752 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700753 mUi.onPageStopped(tab);
754 }
755
756 boolean didUserStopLoading() {
757 return mLoadStopped;
758 }
759
760 // WebViewController
761
762 @Override
John Reck324d4402011-01-11 16:56:42 -0800763 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700764
765 // We've started to load a new page. If there was a pending message
766 // to save a screenshot then we will now take the new page and save
767 // an incorrect screenshot. Therefore, remove any pending thumbnail
768 // messages from the queue.
769 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800770 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700771
772 // reset sync timer to avoid sync starts during loading a page
773 CookieSyncManager.getInstance().resetSync();
774
775 if (!mNetworkHandler.isNetworkUp()) {
776 view.setNetworkAvailable(false);
777 }
778
779 // when BrowserActivity just starts, onPageStarted may be called before
780 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
781 // to start the timer. As we won't switch tabs while an activity is in
782 // pause state, we can ensure calling resume and pause in pair.
783 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800784 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700785 }
786 mLoadStopped = false;
787 if (!mNetworkHandler.isNetworkUp()) {
788 mNetworkHandler.createAndShowNetworkDialog();
789 }
790 endActionMode();
791
John Reck30c714c2010-12-16 17:30:34 -0800792 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700793
John Reck324d4402011-01-11 16:56:42 -0800794 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700795 // update the bookmark database for favicon
796 maybeUpdateFavicon(tab, null, url, favicon);
797
798 Performance.tracePageStart(url);
799
800 // Performance probe
801 if (false) {
802 Performance.onPageStarted();
803 }
804
805 }
806
807 @Override
John Reck324d4402011-01-11 16:56:42 -0800808 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800809 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800810 if (!tab.isPrivateBrowsingEnabled()
811 && !TextUtils.isEmpty(tab.getUrl())) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700812 if (tab.inForeground() && !didUserStopLoading()
813 || !tab.inForeground()) {
814 // Only update the bookmark screenshot if the user did not
815 // cancel the load early.
816 mHandler.sendMessageDelayed(mHandler.obtainMessage(
John Reck34ef2672011-02-10 11:30:55 -0800817 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
Michael Kolb8233fac2010-10-26 16:08:53 -0700818 500);
819 }
820 }
821 // pause the WebView timer and release the wake lock if it is finished
822 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800823 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700824 if (mWakeLock.isHeld()) {
825 mHandler.removeMessages(RELEASE_WAKELOCK);
826 mWakeLock.release();
827 }
828 }
829 // Performance probe
830 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800831 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700832 }
833
834 Performance.tracePageFinished();
835 }
836
837 @Override
John Reck30c714c2010-12-16 17:30:34 -0800838 public void onProgressChanged(Tab tab) {
839 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700840
841 if (newProgress == 100) {
842 CookieSyncManager.getInstance().sync();
843 // onProgressChanged() may continue to be called after the main
844 // frame has finished loading, as any remaining sub frames continue
845 // to load. We'll only get called once though with newProgress as
846 // 100 when everything is loaded. (onPageFinished is called once
847 // when the main frame completes loading regardless of the state of
848 // any sub frames so calls to onProgressChanges may continue after
849 // onPageFinished has executed)
850 if (mInLoad) {
851 mInLoad = false;
852 updateInLoadMenuItems(mCachedMenu);
853 }
854 } else {
855 if (!mInLoad) {
856 // onPageFinished may have already been called but a subframe is
857 // still loading and updating the progress. Reset mInLoad and
858 // update the menu items.
859 mInLoad = true;
860 updateInLoadMenuItems(mCachedMenu);
861 }
862 }
John Reck30c714c2010-12-16 17:30:34 -0800863 mUi.onProgressChanged(tab);
864 }
865
866 @Override
867 public void onUpdatedLockIcon(Tab tab) {
868 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700869 }
870
871 @Override
872 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800873 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800874 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800875 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700876 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
877 return;
878 }
879 // Update the title in the history database if not in private browsing mode
880 if (!tab.isPrivateBrowsingEnabled()) {
John Reck0ebd3ac2010-12-09 11:14:04 -0800881 mDataController.updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700882 }
883 }
884
885 @Override
886 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800887 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700888 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
889 }
890
891 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800892 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
893 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700894 }
895
896 @Override
897 public boolean shouldOverrideKeyEvent(KeyEvent event) {
898 if (mMenuIsDown) {
899 // only check shortcut key when MENU is held
900 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
901 event);
902 } else {
903 return false;
904 }
905 }
906
907 @Override
908 public void onUnhandledKeyEvent(KeyEvent event) {
909 if (!isActivityPaused()) {
910 if (event.getAction() == KeyEvent.ACTION_DOWN) {
911 mActivity.onKeyDown(event.getKeyCode(), event);
912 } else {
913 mActivity.onKeyUp(event.getKeyCode(), event);
914 }
915 }
916 }
917
918 @Override
John Reck324d4402011-01-11 16:56:42 -0800919 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700920 // Don't save anything in private browsing mode
921 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800922 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700923
John Reck324d4402011-01-11 16:56:42 -0800924 if (TextUtils.isEmpty(url)
925 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700926 return;
927 }
John Reck0ebd3ac2010-12-09 11:14:04 -0800928 mDataController.updateVisitedHistory(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700929 WebIconDatabase.getInstance().retainIconForPageUrl(url);
John Reck847b5322011-04-14 17:02:18 -0700930 if (!mActivityPaused) {
931 // Since we clear the state in onPause, don't backup the current
932 // state if we are already paused
933 mCrashRecoveryHandler.backupState();
934 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700935 }
936
937 @Override
938 public void getVisitedHistory(final ValueCallback<String[]> callback) {
939 AsyncTask<Void, Void, String[]> task =
940 new AsyncTask<Void, Void, String[]>() {
941 @Override
942 public String[] doInBackground(Void... unused) {
943 return Browser.getVisitedHistory(mActivity.getContentResolver());
944 }
945 @Override
946 public void onPostExecute(String[] result) {
947 callback.onReceiveValue(result);
948 }
949 };
950 task.execute();
951 }
952
953 @Override
954 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
955 final HttpAuthHandler handler, final String host,
956 final String realm) {
957 String username = null;
958 String password = null;
959
960 boolean reuseHttpAuthUsernamePassword
961 = handler.useHttpAuthUsernamePassword();
962
963 if (reuseHttpAuthUsernamePassword && view != null) {
964 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
965 if (credentials != null && credentials.length == 2) {
966 username = credentials[0];
967 password = credentials[1];
968 }
969 }
970
971 if (username != null && password != null) {
972 handler.proceed(username, password);
973 } else {
974 if (tab.inForeground()) {
975 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
976 } else {
977 handler.cancel();
978 }
979 }
980 }
981
982 @Override
983 public void onDownloadStart(Tab tab, String url, String userAgent,
984 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000985 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -0500986 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000987 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
988 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700989 // This Tab was opened for the sole purpose of downloading a
990 // file. Remove it.
991 if (tab == mTabControl.getCurrentTab()) {
992 // In this case, the Tab is still on top.
993 goBackOnePageOrQuit();
994 } else {
995 // In this case, it is not.
996 closeTab(tab);
997 }
998 }
999 }
1000
1001 @Override
1002 public Bitmap getDefaultVideoPoster() {
1003 return mUi.getDefaultVideoPoster();
1004 }
1005
1006 @Override
1007 public View getVideoLoadingProgressView() {
1008 return mUi.getVideoLoadingProgressView();
1009 }
1010
1011 @Override
1012 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1013 SslError error) {
1014 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1015 }
1016
Patrick Scott92066772011-03-10 08:46:27 -05001017 @Override
1018 public void showAutoLogin(Tab tab) {
1019 assert tab.inForeground();
1020 // Update the title bar to show the auto-login request.
1021 mUi.showAutoLogin(tab);
1022 }
1023
1024 @Override
1025 public void hideAutoLogin(Tab tab) {
1026 assert tab.inForeground();
1027 mUi.hideAutoLogin(tab);
1028 }
1029
Michael Kolb8233fac2010-10-26 16:08:53 -07001030 // helper method
1031
1032 /*
1033 * Update the favorites icon if the private browsing isn't enabled and the
1034 * icon is valid.
1035 */
1036 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1037 final String url, Bitmap favicon) {
1038 if (favicon == null) {
1039 return;
1040 }
1041 if (!tab.isPrivateBrowsingEnabled()) {
1042 Bookmarks.updateFavicon(mActivity
1043 .getContentResolver(), originalUrl, url, favicon);
1044 }
1045 }
1046
Leon Scroggins4cd97792010-12-03 15:31:56 -05001047 @Override
1048 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001049 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001050 mUi.bookmarkedStatusHasChanged(tab);
1051 }
1052
Michael Kolb8233fac2010-10-26 16:08:53 -07001053 // end WebViewController
1054
1055 protected void pageUp() {
1056 getCurrentTopWebView().pageUp(false);
1057 }
1058
1059 protected void pageDown() {
1060 getCurrentTopWebView().pageDown(false);
1061 }
1062
1063 // callback from phone title bar
1064 public void editUrl() {
1065 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001066 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001067 }
1068
Michael Kolbcfa3af52010-12-14 10:36:11 -08001069 public void startVoiceSearch() {
1070 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1071 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1072 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1073 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1074 mActivity.getComponentName().flattenToString());
1075 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001076 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001077 mActivity.startActivity(intent);
1078 }
1079
Michael Kolb11d19782011-03-20 10:17:40 -07001080 @Override
1081 public void activateVoiceSearchMode(String title, List<String> results) {
1082 mUi.showVoiceTitleBar(title, results);
Michael Kolb8233fac2010-10-26 16:08:53 -07001083 }
1084
1085 public void revertVoiceSearchMode(Tab tab) {
1086 mUi.revertVoiceTitleBar(tab);
1087 }
1088
Michael Kolb736990c2011-03-20 10:01:20 -07001089 public boolean supportsVoiceSearch() {
John Reck35e9dd62011-04-25 09:01:54 -07001090 SearchEngine searchEngine = getSettings().getSearchEngine();
Michael Kolb736990c2011-03-20 10:01:20 -07001091 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1092 }
1093
Michael Kolb8233fac2010-10-26 16:08:53 -07001094 public void showCustomView(Tab tab, View view,
1095 WebChromeClient.CustomViewCallback callback) {
1096 if (tab.inForeground()) {
1097 if (mUi.isCustomViewShowing()) {
1098 callback.onCustomViewHidden();
1099 return;
1100 }
1101 mUi.showCustomView(view, callback);
1102 // Save the menu state and set it to empty while the custom
1103 // view is showing.
1104 mOldMenuState = mMenuState;
1105 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001106 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001107 }
1108 }
1109
1110 @Override
1111 public void hideCustomView() {
1112 if (mUi.isCustomViewShowing()) {
1113 mUi.onHideCustomView();
1114 // Reset the old menu state.
1115 mMenuState = mOldMenuState;
1116 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001117 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001118 }
1119 }
1120
1121 protected void onActivityResult(int requestCode, int resultCode,
1122 Intent intent) {
1123 if (getCurrentTopWebView() == null) return;
1124 switch (requestCode) {
1125 case PREFERENCES_PAGE:
1126 if (resultCode == Activity.RESULT_OK && intent != null) {
1127 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001128 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001129 mTabControl.removeParentChildRelationShips();
1130 }
1131 }
1132 break;
1133 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001134 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001135 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001136 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001137 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001138 case AUTOFILL_SETUP:
1139 // Determine whether a profile was actually set up or not
1140 // and if so, send the message back to the WebTextView to
1141 // fill the form with the new profile.
1142 if (getSettings().getAutoFillProfile() != null) {
1143 mAutoFillSetupMessage.sendToTarget();
1144 mAutoFillSetupMessage = null;
1145 }
1146 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001147 default:
1148 break;
1149 }
1150 getCurrentTopWebView().requestFocus();
1151 }
1152
1153 /**
1154 * Open the Go page.
1155 * @param startWithHistory If true, open starting on the history tab.
1156 * Otherwise, start with the bookmarks tab.
1157 */
1158 @Override
1159 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1160 if (mTabControl.getCurrentWebView() == null) {
1161 return;
1162 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001163 // clear action mode
1164 if (isInCustomActionMode()) {
1165 endActionMode();
1166 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001167 Bundle extras = new Bundle();
1168 // Disable opening in a new window if we have maxed out the windows
1169 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1170 !mTabControl.canCreateNewTab());
1171 mUi.showComboView(startWithHistory, extras);
1172 }
1173
1174 // combo view callbacks
1175
1176 /**
1177 * callback from ComboPage when clear history is requested
1178 */
1179 public void onRemoveParentChildRelationships() {
1180 mTabControl.removeParentChildRelationShips();
1181 }
1182
1183 /**
1184 * callback from ComboPage when bookmark/history selection
1185 */
1186 @Override
1187 public void onUrlSelected(String url, boolean newTab) {
1188 removeComboView();
1189 if (!TextUtils.isEmpty(url)) {
1190 if (newTab) {
Michael Kolb18eb3772010-12-10 14:29:51 -08001191 openTab(mTabControl.getCurrentTab(), url, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001192 } else {
1193 final Tab currentTab = mTabControl.getCurrentTab();
1194 dismissSubWindow(currentTab);
1195 loadUrl(getCurrentTopWebView(), url);
1196 }
1197 }
1198 }
1199
1200 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07001201 * dismiss the ComboPage
1202 */
1203 @Override
1204 public void removeComboView() {
1205 mUi.hideComboView();
1206 }
1207
1208 // active tabs page handling
1209
1210 protected void showActiveTabsPage() {
1211 mMenuState = EMPTY_MENU;
1212 mUi.showActiveTabsPage();
1213 }
1214
1215 /**
1216 * Remove the active tabs page.
1217 * @param needToAttach If true, the active tabs page did not attach a tab
1218 * to the content view, so we need to do that here.
1219 */
1220 @Override
1221 public void removeActiveTabsPage(boolean needToAttach) {
1222 mMenuState = R.id.MAIN_MENU;
1223 mUi.removeActiveTabsPage();
1224 if (needToAttach) {
1225 setActiveTab(mTabControl.getCurrentTab());
1226 }
1227 getCurrentTopWebView().requestFocus();
1228 }
1229
1230 // key handling
1231 protected void onBackKey() {
1232 if (!mUi.onBackKey()) {
1233 WebView subwindow = mTabControl.getCurrentSubWindow();
1234 if (subwindow != null) {
1235 if (subwindow.canGoBack()) {
1236 subwindow.goBack();
1237 } else {
1238 dismissSubWindow(mTabControl.getCurrentTab());
1239 }
1240 } else {
1241 goBackOnePageOrQuit();
1242 }
1243 }
1244 }
1245
1246 // menu handling and state
1247 // TODO: maybe put into separate handler
1248
1249 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckb3417f02011-01-14 11:01:05 -08001250 if (mOptionsMenuHandler != null) {
1251 return mOptionsMenuHandler.onCreateOptionsMenu(menu);
1252 }
1253
John Reckd73c5a22010-12-22 10:22:50 -08001254 if (mMenuState == EMPTY_MENU) {
1255 return false;
1256 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001257 MenuInflater inflater = mActivity.getMenuInflater();
1258 inflater.inflate(R.menu.browser, menu);
1259 updateInLoadMenuItems(menu);
1260 // hold on to the menu reference here; it is used by the page callbacks
1261 // to update the menu based on loading state
1262 mCachedMenu = menu;
1263 return true;
1264 }
1265
1266 protected void onCreateContextMenu(ContextMenu menu, View v,
1267 ContextMenuInfo menuInfo) {
1268 if (v instanceof TitleBarBase) {
1269 return;
1270 }
1271 if (!(v instanceof WebView)) {
1272 return;
1273 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001274 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001275 WebView.HitTestResult result = webview.getHitTestResult();
1276 if (result == null) {
1277 return;
1278 }
1279
1280 int type = result.getType();
1281 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1282 Log.w(LOGTAG,
1283 "We should not show context menu when nothing is touched");
1284 return;
1285 }
1286 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1287 // let TextView handles context menu
1288 return;
1289 }
1290
1291 // Note, http://b/issue?id=1106666 is requesting that
1292 // an inflated menu can be used again. This is not available
1293 // yet, so inflate each time (yuk!)
1294 MenuInflater inflater = mActivity.getMenuInflater();
1295 inflater.inflate(R.menu.browsercontext, menu);
1296
1297 // Show the correct menu group
1298 final String extra = result.getExtra();
1299 menu.setGroupVisible(R.id.PHONE_MENU,
1300 type == WebView.HitTestResult.PHONE_TYPE);
1301 menu.setGroupVisible(R.id.EMAIL_MENU,
1302 type == WebView.HitTestResult.EMAIL_TYPE);
1303 menu.setGroupVisible(R.id.GEO_MENU,
1304 type == WebView.HitTestResult.GEO_TYPE);
1305 menu.setGroupVisible(R.id.IMAGE_MENU,
1306 type == WebView.HitTestResult.IMAGE_TYPE
1307 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1308 menu.setGroupVisible(R.id.ANCHOR_MENU,
1309 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1310 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001311 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1312 || type == WebView.HitTestResult.PHONE_TYPE
1313 || type == WebView.HitTestResult.EMAIL_TYPE
1314 || type == WebView.HitTestResult.GEO_TYPE;
1315 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1316 if (hitText) {
1317 menu.findItem(R.id.select_text_menu_id)
1318 .setOnMenuItemClickListener(new SelectText(webview));
1319 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001320 // Setup custom handling depending on the type
1321 switch (type) {
1322 case WebView.HitTestResult.PHONE_TYPE:
1323 menu.setHeaderTitle(Uri.decode(extra));
1324 menu.findItem(R.id.dial_context_menu_id).setIntent(
1325 new Intent(Intent.ACTION_VIEW, Uri
1326 .parse(WebView.SCHEME_TEL + extra)));
1327 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1328 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1329 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1330 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1331 addIntent);
1332 menu.findItem(R.id.copy_phone_context_menu_id)
1333 .setOnMenuItemClickListener(
1334 new Copy(extra));
1335 break;
1336
1337 case WebView.HitTestResult.EMAIL_TYPE:
1338 menu.setHeaderTitle(extra);
1339 menu.findItem(R.id.email_context_menu_id).setIntent(
1340 new Intent(Intent.ACTION_VIEW, Uri
1341 .parse(WebView.SCHEME_MAILTO + extra)));
1342 menu.findItem(R.id.copy_mail_context_menu_id)
1343 .setOnMenuItemClickListener(
1344 new Copy(extra));
1345 break;
1346
1347 case WebView.HitTestResult.GEO_TYPE:
1348 menu.setHeaderTitle(extra);
1349 menu.findItem(R.id.map_context_menu_id).setIntent(
1350 new Intent(Intent.ACTION_VIEW, Uri
1351 .parse(WebView.SCHEME_GEO
1352 + URLEncoder.encode(extra))));
1353 menu.findItem(R.id.copy_geo_context_menu_id)
1354 .setOnMenuItemClickListener(
1355 new Copy(extra));
1356 break;
1357
1358 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1359 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001360 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001361 // decide whether to show the open link in new tab option
1362 boolean showNewTab = mTabControl.canCreateNewTab();
1363 MenuItem newTabItem
1364 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001365 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001366 ? 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
John Reck35e9dd62011-04-25 09:01:54 -07001494 boolean isNavDump = mSettings.enableNavDump();
Michael Kolb8233fac2010-10-26 16:08:53 -07001495 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1496 nav.setVisible(isNavDump);
1497 nav.setEnabled(isNavDump);
1498
John Reck35e9dd62011-04-25 09:01:54 -07001499 boolean showDebugSettings = mSettings.isDebugEnabled();
Michael Kolb8233fac2010-10-26 16:08:53 -07001500 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
Michael Kolbf2055602011-04-09 17:20:03 -07002131 @Override
2132 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002133 // monkey protection against delayed start
2134 if (tab != null) {
2135 mTabControl.setCurrentTab(tab);
2136 // the tab is guaranteed to have a webview after setCurrentTab
2137 mUi.setActiveTab(tab);
2138 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002139 }
2140
2141 protected void closeEmptyChildTab() {
2142 Tab current = mTabControl.getCurrentTab();
2143 if (current != null
2144 && current.getWebView().copyBackForwardList().getSize() == 0) {
2145 Tab parent = current.getParentTab();
2146 if (parent != null) {
2147 switchToTab(mTabControl.getTabIndex(parent));
2148 closeTab(current);
2149 }
2150 }
2151 }
2152
2153 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002154 // Dismiss the subwindow if applicable.
2155 dismissSubWindow(appTab);
2156 // Since we might kill the WebView, remove it from the
2157 // content view first.
2158 mUi.detachTab(appTab);
2159 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002160 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002161 // TODO: analyze why the remove and add are necessary
2162 mUi.attachTab(appTab);
2163 if (mTabControl.getCurrentTab() != appTab) {
2164 switchToTab(mTabControl.getTabIndex(appTab));
John Reck30c714c2010-12-16 17:30:34 -08002165 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002166 } else {
2167 // If the tab was the current tab, we have to attach
2168 // it to the view system again.
2169 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002170 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002171 }
2172 }
2173
2174 // Remove the sub window if it exists. Also called by TabControl when the
2175 // user clicks the 'X' to dismiss a sub window.
2176 public void dismissSubWindow(Tab tab) {
2177 removeSubWindow(tab);
2178 // dismiss the subwindow. This will destroy the WebView.
2179 tab.dismissSubWindow();
2180 getCurrentTopWebView().requestFocus();
2181 }
2182
2183 @Override
2184 public void removeSubWindow(Tab t) {
2185 if (t.getSubWebView() != null) {
2186 mUi.removeSubWindow(t.getSubViewContainer());
2187 }
2188 }
2189
2190 @Override
2191 public void attachSubWindow(Tab tab) {
2192 if (tab.getSubWebView() != null) {
2193 mUi.attachSubWindow(tab.getSubViewContainer());
2194 getCurrentTopWebView().requestFocus();
2195 }
2196 }
2197
Michael Kolb843510f2010-12-09 10:51:49 -08002198 @Override
2199 public Tab openTabToHomePage() {
2200 // check for max tabs
2201 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002202 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2203 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002204 } else {
2205 mUi.showMaxTabsWarning();
2206 return null;
2207 }
2208 }
2209
Michael Kolb18eb3772010-12-10 14:29:51 -08002210 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2211 if (mSettings.openInBackground() && !forceForeground) {
2212 Tab tab = mTabControl.createNewTab(false, null, null,
2213 (parent != null) && parent.isPrivateBrowsingEnabled());
2214 if (tab != null) {
2215 addTab(tab);
2216 WebView view = tab.getWebView();
2217 loadUrl(view, url);
2218 }
2219 return tab;
2220 } else {
2221 return openTabAndShow(parent, new UrlData(url), false, null);
2222 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002223 }
2224
Michael Kolb18eb3772010-12-10 14:29:51 -08002225
Michael Kolb8233fac2010-10-26 16:08:53 -07002226 // This method does a ton of stuff. It will attempt to create a new tab
2227 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2228 // url isn't null, it will load the given url.
Patrick Scottcd135082011-01-31 18:21:58 -05002229 public Tab openTabAndShow(Tab parent, final UrlData urlData,
2230 boolean closeOnExit, String appId) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002231 final Tab currentTab = mTabControl.getCurrentTab();
2232 if (mTabControl.canCreateNewTab()) {
2233 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Michael Kolb18eb3772010-12-10 14:29:51 -08002234 urlData.mUrl,
2235 (parent != null) && parent.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -07002236 WebView webview = tab.getWebView();
2237 // We must set the new tab as the current tab to reflect the old
2238 // animation behavior.
2239 addTab(tab);
2240 setActiveTab(tab);
Patrick Scottd43e75a2011-03-14 14:47:23 -04002241 if (!urlData.isEmpty()) {
2242 loadUrlDataIn(tab, urlData);
2243 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002244 return tab;
2245 } else {
2246 // Get rid of the subwindow if it exists
2247 dismissSubWindow(currentTab);
2248 if (!urlData.isEmpty()) {
2249 // Load the given url.
2250 loadUrlDataIn(currentTab, urlData);
2251 }
2252 return currentTab;
2253 }
2254 }
2255
Michael Kolb8233fac2010-10-26 16:08:53 -07002256 @Override
2257 public Tab openIncognitoTab() {
2258 if (mTabControl.canCreateNewTab()) {
2259 Tab currentTab = mTabControl.getCurrentTab();
Michael Kolb8e7178d2011-01-26 19:13:36 -08002260 Tab tab = mTabControl.createNewTab(false, null,
John Reck4bfc0db2011-01-27 17:47:12 -08002261 null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07002262 addTab(tab);
2263 setActiveTab(tab);
John Reck4bfc0db2011-01-27 17:47:12 -08002264 loadUrlDataIn(tab, new UrlData("browser:incognito"));
Michael Kolb8233fac2010-10-26 16:08:53 -07002265 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002266 } else {
2267 mUi.showMaxTabsWarning();
2268 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002269 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002270 }
2271
2272 /**
2273 * @param index Index of the tab to change to, as defined by
2274 * mTabControl.getTabIndex(Tab t).
2275 * @return boolean True if we successfully switched to a different tab. If
2276 * the indexth tab is null, or if that tab is the same as
2277 * the current one, return false.
2278 */
2279 @Override
2280 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002281 // hide combo view if open
2282 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002283 Tab tab = mTabControl.getTab(index);
2284 Tab currentTab = mTabControl.getCurrentTab();
2285 if (tab == null || tab == currentTab) {
2286 return false;
2287 }
2288 setActiveTab(tab);
2289 return true;
2290 }
2291
2292 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002293 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002294 // hide combo view if open
2295 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002296 final Tab current = mTabControl.getCurrentTab();
2297 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002298 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002299 return;
2300 }
2301 final Tab parent = current.getParentTab();
2302 int indexToShow = -1;
2303 if (parent != null) {
2304 indexToShow = mTabControl.getTabIndex(parent);
2305 } else {
2306 final int currentIndex = mTabControl.getCurrentIndex();
2307 // Try to move to the tab to the right
2308 indexToShow = currentIndex + 1;
2309 if (indexToShow > mTabControl.getTabCount() - 1) {
2310 // Try to move to the tab to the left
2311 indexToShow = currentIndex - 1;
2312 }
2313 }
2314 if (switchToTab(indexToShow)) {
2315 // Close window
2316 closeTab(current);
2317 }
2318 }
2319
2320 /**
2321 * Close the tab, remove its associated title bar, and adjust mTabControl's
2322 * current tab to a valid value.
2323 */
2324 @Override
2325 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002326 // hide combo view if open
2327 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002328 int currentIndex = mTabControl.getCurrentIndex();
2329 int removeIndex = mTabControl.getTabIndex(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002330 Tab newtab = mTabControl.getTab(currentIndex);
2331 setActiveTab(newtab);
Michael Kolb2d59c322011-01-25 13:18:55 -08002332 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002333 }
2334
2335 /**************** TODO: Url loading clean up *******************************/
2336
2337 // Called when loading from context menu or LOAD_URL message
2338 protected void loadUrlFromContext(WebView view, String url) {
2339 // In case the user enters nothing.
2340 if (url != null && url.length() != 0 && view != null) {
2341 url = UrlUtils.smartUrlFilter(url);
2342 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2343 loadUrl(view, url);
2344 }
2345 }
2346 }
2347
2348 /**
2349 * Load the URL into the given WebView and update the title bar
2350 * to reflect the new load. Call this instead of WebView.loadUrl
2351 * directly.
2352 * @param view The WebView used to load url.
2353 * @param url The URL to load.
2354 */
2355 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002356 view.loadUrl(url);
2357 }
2358
2359 /**
2360 * Load UrlData into a Tab and update the title bar to reflect the new
2361 * load. Call this instead of UrlData.loadIn directly.
2362 * @param t The Tab used to load.
2363 * @param data The UrlData being loaded.
2364 */
2365 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002366 data.loadIn(t);
2367 }
2368
John Reck30c714c2010-12-16 17:30:34 -08002369 @Override
2370 public void onUserCanceledSsl(Tab tab) {
2371 WebView web = tab.getWebView();
2372 // TODO: Figure out the "right" behavior
2373 if (web.canGoBack()) {
2374 web.goBack();
2375 } else {
2376 web.loadUrl(mSettings.getHomePage());
2377 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002378 }
2379
2380 void goBackOnePageOrQuit() {
2381 Tab current = mTabControl.getCurrentTab();
2382 if (current == null) {
2383 /*
2384 * Instead of finishing the activity, simply push this to the back
2385 * of the stack and let ActivityManager to choose the foreground
2386 * activity. As BrowserActivity is singleTask, it will be always the
2387 * root of the task. So we can use either true or false for
2388 * moveTaskToBack().
2389 */
2390 mActivity.moveTaskToBack(true);
2391 return;
2392 }
2393 WebView w = current.getWebView();
2394 if (w.canGoBack()) {
2395 w.goBack();
2396 } else {
2397 // Check to see if we are closing a window that was created by
2398 // another window. If so, we switch back to that window.
2399 Tab parent = current.getParentTab();
2400 if (parent != null) {
2401 switchToTab(mTabControl.getTabIndex(parent));
2402 // Now we close the other tab
2403 closeTab(current);
2404 } else {
2405 if (current.closeOnExit()) {
Patrick Scottfc1518a2011-02-28 13:57:03 -05002406 // This will finish the activity if there is only one tab
2407 // open or it will switch to the next available tab if
2408 // available.
Michael Kolb96683f72011-02-15 14:24:35 -08002409 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002410 }
2411 /*
2412 * Instead of finishing the activity, simply push this to the back
2413 * of the stack and let ActivityManager to choose the foreground
2414 * activity. As BrowserActivity is singleTask, it will be always the
2415 * root of the task. So we can use either true or false for
2416 * moveTaskToBack().
2417 */
2418 mActivity.moveTaskToBack(true);
2419 }
2420 }
2421 }
2422
2423 /**
2424 * Feed the previously stored results strings to the BrowserProvider so that
2425 * the SearchDialog will show them instead of the standard searches.
2426 * @param result String to show on the editable line of the SearchDialog.
2427 */
2428 @Override
2429 public void showVoiceSearchResults(String result) {
2430 ContentProviderClient client = mActivity.getContentResolver()
2431 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2432 ContentProvider prov = client.getLocalContentProvider();
2433 BrowserProvider bp = (BrowserProvider) prov;
2434 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2435 client.release();
2436
2437 Bundle bundle = createGoogleSearchSourceBundle(
2438 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2439 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2440 startSearch(result, false, bundle, false);
2441 }
2442
2443 private void startSearch(String initialQuery, boolean selectInitialQuery,
2444 Bundle appSearchData, boolean globalSearch) {
2445 if (appSearchData == null) {
2446 appSearchData = createGoogleSearchSourceBundle(
2447 GOOGLE_SEARCH_SOURCE_TYPE);
2448 }
2449
2450 SearchEngine searchEngine = mSettings.getSearchEngine();
2451 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2452 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2453 }
2454 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2455 globalSearch);
2456 }
2457
2458 private Bundle createGoogleSearchSourceBundle(String source) {
2459 Bundle bundle = new Bundle();
2460 bundle.putString(Search.SOURCE, source);
2461 return bundle;
2462 }
2463
2464 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002465 * helper method for key handler
2466 * returns the current tab if it can't advance
2467 */
2468 private int getNextTabIndex() {
2469 return Math.min(mTabControl.getTabCount() - 1,
2470 mTabControl.getCurrentIndex() + 1);
2471 }
2472
2473 /**
2474 * helper method for key handler
2475 * returns the current tab if it can't advance
2476 */
2477 private int getPrevTabIndex() {
2478 return Math.max(0, mTabControl.getCurrentIndex() - 1);
2479 }
2480
2481 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002482 * handle key events in browser
2483 *
2484 * @param keyCode
2485 * @param event
2486 * @return true if handled, false to pass to super
2487 */
2488 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002489 boolean noModifiers = event.hasNoModifiers();
2490
Michael Kolb8233fac2010-10-26 16:08:53 -07002491 // Even if MENU is already held down, we need to call to super to open
2492 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002493 if (!noModifiers
2494 && ((KeyEvent.KEYCODE_MENU == keyCode)
2495 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2496 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002497 mMenuIsDown = true;
2498 return false;
2499 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002500
Cary Clark8ff8c662010-12-29 15:03:05 -05002501 WebView webView = getCurrentTopWebView();
2502 if (webView == null) return false;
2503
Cary Clark160bbb92011-01-10 11:17:07 -05002504 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2505 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002506
Michael Kolb8233fac2010-10-26 16:08:53 -07002507 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002508 case KeyEvent.KEYCODE_TAB:
2509 if (event.isCtrlPressed()) {
2510 if (event.isShiftPressed()) {
2511 // prev tab
2512 switchToTab(getPrevTabIndex());
2513 } else {
2514 // next tab
2515 switchToTab(getNextTabIndex());
2516 }
2517 return true;
2518 }
2519 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002520 case KeyEvent.KEYCODE_SPACE:
2521 // WebView/WebTextView handle the keys in the KeyDown. As
2522 // the Activity's shortcut keys are only handled when WebView
2523 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002524 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002525 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002526 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002527 pageDown();
2528 }
2529 return true;
2530 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002531 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002532 event.startTracking();
2533 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002534 case KeyEvent.KEYCODE_DPAD_LEFT:
2535 if (ctrl) {
2536 webView.goBack();
2537 return true;
2538 }
2539 break;
2540 case KeyEvent.KEYCODE_DPAD_RIGHT:
2541 if (ctrl) {
2542 webView.goForward();
2543 return true;
2544 }
2545 break;
2546 case KeyEvent.KEYCODE_A:
2547 if (ctrl) {
2548 webView.selectAll();
2549 return true;
2550 }
2551 break;
Michael Kolba4183062011-01-16 10:43:21 -08002552// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002553 case KeyEvent.KEYCODE_C:
2554 if (ctrl) {
2555 webView.copySelection();
2556 return true;
2557 }
2558 break;
Michael Kolba4183062011-01-16 10:43:21 -08002559// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002560// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002561// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002562// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002563// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002564// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002565// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002566// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002567// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002568// case KeyEvent.KEYCODE_M: // unused
2569// case KeyEvent.KEYCODE_N: // in Chrome: new window
2570// case KeyEvent.KEYCODE_O: // in Chrome: open file
2571// case KeyEvent.KEYCODE_P: // in Chrome: print page
2572// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002573// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002574// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2575 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002576 // we can't use the ctrl/shift flags, they check for
2577 // exclusive use of a modifier
2578 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002579 if (event.isShiftPressed()) {
2580 openIncognitoTab();
2581 } else {
2582 openTabToHomePage();
2583 }
2584 return true;
2585 }
2586 break;
2587// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2588// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb1a2eba42011-03-16 16:42:49 -07002589 case KeyEvent.KEYCODE_W: // in Chrome: close tab
2590 if (ctrl) {
2591 closeCurrentTab();
2592 return true;
2593 }
2594 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002595// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2596// case KeyEvent.KEYCODE_Y: // unused
2597// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002598 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002599 // it is a regular key and webview is not null
2600 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002601 }
2602
John Recke6bf4ab2011-02-24 15:48:05 -08002603 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2604 switch(keyCode) {
2605 case KeyEvent.KEYCODE_BACK:
2606 if (mUi.showsWeb()) {
2607 bookmarksOrHistoryPicker(true);
2608 return true;
2609 }
2610 break;
2611 }
2612 return false;
2613 }
2614
Michael Kolb8233fac2010-10-26 16:08:53 -07002615 boolean onKeyUp(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002616 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002617 switch(keyCode) {
2618 case KeyEvent.KEYCODE_MENU:
2619 mMenuIsDown = false;
2620 break;
2621 case KeyEvent.KEYCODE_BACK:
2622 if (event.isTracking() && !event.isCanceled()) {
2623 onBackKey();
2624 return true;
2625 }
2626 break;
2627 }
2628 return false;
2629 }
2630
2631 public boolean isMenuDown() {
2632 return mMenuIsDown;
2633 }
2634
Ben Murdoch8029a772010-11-16 11:58:21 +00002635 public void setupAutoFill(Message message) {
2636 // Open the settings activity at the AutoFill profile fragment so that
2637 // the user can create a new profile. When they return, we will dispatch
2638 // the message so that we can autofill the form using their new profile.
2639 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2640 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2641 AutoFillSettingsFragment.class.getName());
2642 mAutoFillSetupMessage = message;
2643 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2644 }
John Reckb3417f02011-01-14 11:01:05 -08002645
2646 @Override
2647 public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
2648 mOptionsMenuHandler = handler;
2649 }
2650
2651 @Override
2652 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
2653 if (mOptionsMenuHandler == handler) {
2654 mOptionsMenuHandler = null;
2655 }
2656 }
2657
Narayan Kamath5119edd2011-02-23 15:49:17 +00002658 @Override
2659 public void registerDropdownChangeListener(DropdownChangeListener d) {
2660 mUi.registerDropdownChangeListener(d);
2661 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002662}