blob: d1e1b0abd4ece049a7c48ba2ab733490d7986622 [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";
Michael Kolba4261fd2011-05-05 11:27:37 -0700100 private static final String INCOGNITO_URI = "browser:incognito";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800101
Michael Kolb8233fac2010-10-26 16:08:53 -0700102
103 // public message ids
104 public final static int LOAD_URL = 1001;
105 public final static int STOP_LOAD = 1002;
106
107 // Message Ids
108 private static final int FOCUS_NODE_HREF = 102;
109 private static final int RELEASE_WAKELOCK = 107;
110
111 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
112
113 private static final int OPEN_BOOKMARKS = 201;
114
115 private static final int EMPTY_MENU = -1;
116
Michael Kolb8233fac2010-10-26 16:08:53 -0700117 // activity requestCode
118 final static int PREFERENCES_PAGE = 3;
119 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000120 final static int AUTOFILL_SETUP = 5;
121
Michael Kolb8233fac2010-10-26 16:08:53 -0700122 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
123
124 // As the ids are dynamically created, we can't guarantee that they will
125 // be in sequence, so this static array maps ids to a window number.
126 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
127 { R.id.window_one_menu_id, R.id.window_two_menu_id,
128 R.id.window_three_menu_id, R.id.window_four_menu_id,
129 R.id.window_five_menu_id, R.id.window_six_menu_id,
130 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
131
132 // "source" parameter for Google search through search key
133 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
134 // "source" parameter for Google search through simplily type
135 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
136
Guang Zhu9e78f512011-05-04 11:45:11 -0700137 // "no-crash-recovery" parameter in intetnt to suppress crash recovery
138 final static String NO_CRASH_RECOVERY = "no-crash-recovery";
139
Michael Kolb8233fac2010-10-26 16:08:53 -0700140 private Activity mActivity;
141 private UI mUi;
142 private TabControl mTabControl;
143 private BrowserSettings mSettings;
144 private WebViewFactory mFactory;
John Reckb3417f02011-01-14 11:01:05 -0800145 private OptionsMenuHandler mOptionsMenuHandler = null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700146
147 private WakeLock mWakeLock;
148
149 private UrlHandler mUrlHandler;
150 private UploadHandler mUploadHandler;
151 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700152 private PageDialogsHandler mPageDialogsHandler;
153 private NetworkStateHandler mNetworkHandler;
154
Ben Murdoch8029a772010-11-16 11:58:21 +0000155 private Message mAutoFillSetupMessage;
156
Michael Kolb8233fac2010-10-26 16:08:53 -0700157 private boolean mShouldShowErrorConsole;
158
159 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
160
161 // FIXME, temp address onPrepareMenu performance problem.
162 // When we move everything out of view, we should rewrite this.
163 private int mCurrentMenuState = 0;
164 private int mMenuState = R.id.MAIN_MENU;
165 private int mOldMenuState = EMPTY_MENU;
166 private Menu mCachedMenu;
167
Michael Kolb8233fac2010-10-26 16:08:53 -0700168 private boolean mMenuIsDown;
169
170 // For select and find, we keep track of the ActionMode so that
171 // finish() can be called as desired.
172 private ActionMode mActionMode;
173
174 /**
175 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
176 * of whether the configuration has changed. The first onMenuOpened call
177 * after a configuration change is simply a reopening of the same menu
178 * (i.e. mIconView did not change).
179 */
180 private boolean mConfigChanged;
181
182 /**
183 * Keeps track of whether the options menu is open. This is important in
184 * determining whether to show or hide the title bar overlay
185 */
186 private boolean mOptionsMenuOpen;
187
188 /**
189 * Whether or not the options menu is in its bigger, popup menu form. When
190 * true, we want the title bar overlay to be gone. When false, we do not.
191 * Only meaningful if mOptionsMenuOpen is true.
192 */
193 private boolean mExtendedMenuOpen;
194
195 private boolean mInLoad;
196
197 private boolean mActivityPaused = true;
198 private boolean mLoadStopped;
199
200 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500201 // Checks to see when the bookmarks database has changed, and updates the
202 // Tabs' notion of whether they represent bookmarked sites.
203 private ContentObserver mBookmarksObserver;
John Reck0ebd3ac2010-12-09 11:14:04 -0800204 private DataController mDataController;
John Reck847b5322011-04-14 17:02:18 -0700205 private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700206
207 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
208 @Override
209 public Void doInBackground(File... files) {
210 if (files != null) {
211 for (File f : files) {
212 if (!f.delete()) {
213 Log.e(LOGTAG, f.getPath() + " was not deleted");
214 }
215 }
216 }
217 return null;
218 }
219 }
220
221 public Controller(Activity browser) {
222 mActivity = browser;
223 mSettings = BrowserSettings.getInstance();
John Reck0ebd3ac2010-12-09 11:14:04 -0800224 mDataController = DataController.getInstance(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700225 mTabControl = new TabControl(this);
226 mSettings.setController(this);
John Reck847b5322011-04-14 17:02:18 -0700227 mCrashRecoveryHandler = new CrashRecoveryHandler(this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700228
229 mUrlHandler = new UrlHandler(this);
230 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700231 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
232
233 PowerManager pm = (PowerManager) mActivity
234 .getSystemService(Context.POWER_SERVICE);
235 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
236
237 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500238 mBookmarksObserver = new ContentObserver(mHandler) {
239 @Override
240 public void onChange(boolean selfChange) {
241 int size = mTabControl.getTabCount();
242 for (int i = 0; i < size; i++) {
243 mTabControl.getTab(i).updateBookmarkedStatus();
244 }
245 }
246
247 };
248 browser.getContentResolver().registerContentObserver(
249 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700250
251 mNetworkHandler = new NetworkStateHandler(mActivity, this);
252 // Start watching the default geolocation permissions
253 mSystemAllowGeolocationOrigins =
254 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
255 mSystemAllowGeolocationOrigins.start();
256
257 retainIconsOnStartup();
258 }
259
Patrick Scott7d50a932011-02-04 09:27:26 -0500260 void start(final Bundle icicle, final Intent intent) {
Guang Zhu9e78f512011-05-04 11:45:11 -0700261 boolean noCrashRecovery = intent.getBooleanExtra(NO_CRASH_RECOVERY, false);
262 if (icicle != null || noCrashRecovery) {
John Reck847b5322011-04-14 17:02:18 -0700263 mCrashRecoveryHandler.clearState();
264 doStart(icicle, intent);
265 } else {
266 mCrashRecoveryHandler.startRecovery(intent);
267 }
268 }
269
270 void doStart(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700271 // Unless the last browser usage was within 24 hours, destroy any
272 // remaining incognito tabs.
273
274 Calendar lastActiveDate = icicle != null ?
275 (Calendar) icicle.getSerializable("lastActiveDate") : null;
276 Calendar today = Calendar.getInstance();
277 Calendar yesterday = Calendar.getInstance();
278 yesterday.add(Calendar.DATE, -1);
279
Patrick Scott7d50a932011-02-04 09:27:26 -0500280 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700281 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800282 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700283
Patrick Scott7d50a932011-02-04 09:27:26 -0500284 // Find out if we will restore any state and remember the tab.
285 final int currentTab =
286 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000287
Patrick Scott7d50a932011-02-04 09:27:26 -0500288 if (currentTab == -1) {
289 // Not able to restore so we go ahead and clear session cookies. We
290 // must do this before trying to login the user as we don't want to
291 // clear any session cookies set during login.
292 CookieManager.getInstance().removeSessionCookie();
293 }
294
Patrick Scottd43e75a2011-03-14 14:47:23 -0400295 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500296 new Runnable() {
297 @Override public void run() {
John Reck847b5322011-04-14 17:02:18 -0700298 onPreloginFinished(icicle, intent, currentTab, restoreIncognitoTabs);
Patrick Scott7d50a932011-02-04 09:27:26 -0500299 }
300 });
301 }
302
John Reck847b5322011-04-14 17:02:18 -0700303 private void onPreloginFinished(Bundle icicle, Intent intent, int currentTab,
Patrick Scott7d50a932011-02-04 09:27:26 -0500304 boolean restoreIncognitoTabs) {
305 if (currentTab == -1) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700306 final Bundle extra = intent.getExtras();
307 // Create an initial tab.
308 // If the intent is ACTION_VIEW and data is not null, the Browser is
309 // invoked to view the content by another application. In this case,
310 // the tab will be close when exit.
311 UrlData urlData = mIntentHandler.getUrlDataFromIntent(intent);
312
313 String action = intent.getAction();
314 final Tab t = mTabControl.createNewTab(
315 (Intent.ACTION_VIEW.equals(action) &&
316 intent.getData() != null)
317 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
318 .equals(action),
319 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
320 urlData.mUrl, false);
321 addTab(t);
322 setActiveTab(t);
323 WebView webView = t.getWebView();
324 if (extra != null) {
325 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
326 if (scale > 0 && scale <= 1000) {
327 webView.setInitialScale(scale);
328 }
329 }
330
331 if (urlData.isEmpty()) {
332 loadUrl(webView, mSettings.getHomePage());
333 } else {
Michael Kolbcd424e92011-02-24 10:26:26 -0800334 // monkey protection against delayed start
335 if (t != null) {
336 loadUrlDataIn(t, urlData);
337 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700338 }
339 } else {
Patrick Scott7d50a932011-02-04 09:27:26 -0500340 mTabControl.restoreState(icicle, currentTab, restoreIncognitoTabs,
341 mUi.needsRestoreAllTabs());
Michael Kolb1bf23132010-11-19 12:55:12 -0800342 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700343 // TabControl.restoreState() will create a new tab even if
344 // restoring the state fails.
345 setActiveTab(mTabControl.getCurrentTab());
346 }
347 // clear up the thumbnail directory, which is no longer used;
348 // ideally this should only be run once after an upgrade from
349 // a previous version of the browser
350 new ClearThumbnails().execute(mTabControl.getThumbnailDir()
351 .listFiles());
352 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700353 String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb8233fac2010-10-26 16:08:53 -0700354 if (jsFlags.trim().length() != 0) {
355 getCurrentWebView().setJsFlags(jsFlags);
356 }
John Reck439c9a52010-12-14 10:04:39 -0800357 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
358 bookmarksOrHistoryPicker(false);
359 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700360 }
361
362 void setWebViewFactory(WebViewFactory factory) {
363 mFactory = factory;
364 }
365
Michael Kolb1514bb72010-11-22 09:11:48 -0800366 @Override
367 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700368 return mFactory;
369 }
370
371 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800372 public void onSetWebView(Tab tab, WebView view) {
373 mUi.onSetWebView(tab, view);
374 }
375
376 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800377 public void createSubWindow(Tab tab) {
378 endActionMode();
379 WebView mainView = tab.getWebView();
380 WebView subView = mFactory.createWebView((mainView == null)
381 ? false
382 : mainView.isPrivateBrowsingEnabled());
383 mUi.createSubWindow(tab, subView);
384 }
385
386 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700387 public Activity getActivity() {
388 return mActivity;
389 }
390
391 void setUi(UI ui) {
392 mUi = ui;
393 }
394
395 BrowserSettings getSettings() {
396 return mSettings;
397 }
398
399 IntentHandler getIntentHandler() {
400 return mIntentHandler;
401 }
402
403 @Override
404 public UI getUi() {
405 return mUi;
406 }
407
408 int getMaxTabs() {
409 return mActivity.getResources().getInteger(R.integer.max_tabs);
410 }
411
412 @Override
413 public TabControl getTabControl() {
414 return mTabControl;
415 }
416
Michael Kolb1bf23132010-11-19 12:55:12 -0800417 @Override
418 public List<Tab> getTabs() {
419 return mTabControl.getTabs();
420 }
421
Michael Kolb8233fac2010-10-26 16:08:53 -0700422 // Open the icon database and retain all the icons for visited sites.
Ben Murdoch9446b932010-11-25 16:20:14 +0000423 // This is done on a background thread so as not to stall startup.
Michael Kolb8233fac2010-10-26 16:08:53 -0700424 private void retainIconsOnStartup() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000425 // WebIconDatabase needs to be retrieved on the UI thread so that if
426 // it has not been created successfully yet the Handler is started on the
427 // UI thread.
428 new RetainIconsOnStartupTask(WebIconDatabase.getInstance()).execute();
429 }
430
431 private class RetainIconsOnStartupTask extends AsyncTask<Void, Void, Void> {
432 private WebIconDatabase mDb;
433
434 public RetainIconsOnStartupTask(WebIconDatabase db) {
435 mDb = db;
436 }
437
John Recka00cbbd2010-12-16 12:38:19 -0800438 @Override
Ben Murdoch9446b932010-11-25 16:20:14 +0000439 protected Void doInBackground(Void... unused) {
440 mDb.open(mActivity.getDir("icons", 0).getPath());
441 Cursor c = null;
442 try {
443 c = Browser.getAllBookmarks(mActivity.getContentResolver());
444 if (c.moveToFirst()) {
445 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
446 do {
447 String url = c.getString(urlIndex);
448 mDb.retainIconForPageUrl(url);
449 } while (c.moveToNext());
450 }
451 } catch (IllegalStateException e) {
452 Log.e(LOGTAG, "retainIconsOnStartup", e);
453 } finally {
454 if (c != null) c.close();
Michael Kolb8233fac2010-10-26 16:08:53 -0700455 }
Ben Murdoch9446b932010-11-25 16:20:14 +0000456
457 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700458 }
459 }
460
461 private void startHandler() {
462 mHandler = new Handler() {
463
464 @Override
465 public void handleMessage(Message msg) {
466 switch (msg.what) {
467 case OPEN_BOOKMARKS:
468 bookmarksOrHistoryPicker(false);
469 break;
470 case FOCUS_NODE_HREF:
471 {
472 String url = (String) msg.getData().get("url");
473 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500474 String src = (String) msg.getData().get("src");
475 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700476 if (TextUtils.isEmpty(url)) {
477 break;
478 }
479 HashMap focusNodeMap = (HashMap) msg.obj;
480 WebView view = (WebView) focusNodeMap.get("webview");
481 // Only apply the action if the top window did not change.
482 if (getCurrentTopWebView() != view) {
483 break;
484 }
485 switch (msg.arg1) {
486 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -0700487 loadUrlFromContext(getCurrentTopWebView(), url);
488 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500489 case R.id.view_image_context_menu_id:
490 loadUrlFromContext(getCurrentTopWebView(), src);
491 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500492 case R.id.open_newtab_context_menu_id:
493 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -0800494 final Tab newTab = openTab(parent, url, false);
Leon Scroggins026f2542010-11-22 13:26:12 -0500495 if (newTab != null && newTab != parent) {
496 parent.addChildTab(newTab);
497 }
498 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700499 case R.id.copy_link_context_menu_id:
500 copy(url);
501 break;
502 case R.id.save_link_context_menu_id:
503 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500504 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000505 mActivity, url, null, null, null,
506 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700507 break;
508 }
509 break;
510 }
511
512 case LOAD_URL:
513 loadUrlFromContext(getCurrentTopWebView(), (String) msg.obj);
514 break;
515
516 case STOP_LOAD:
517 stopLoading();
518 break;
519
520 case RELEASE_WAKELOCK:
521 if (mWakeLock.isHeld()) {
522 mWakeLock.release();
523 // if we reach here, Browser should be still in the
524 // background loading after WAKELOCK_TIMEOUT (5-min).
525 // To avoid burning the battery, stop loading.
526 mTabControl.stopAllLoading();
527 }
528 break;
529
530 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800531 Tab tab = (Tab) msg.obj;
532 if (tab != null) {
533 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700534 }
535 break;
536 }
537 }
538 };
539
540 }
541
Michael Kolbba99c5d2010-11-29 14:57:41 -0800542 @Override
543 public void shareCurrentPage() {
544 shareCurrentPage(mTabControl.getCurrentTab());
545 }
546
547 private void shareCurrentPage(Tab tab) {
548 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800549 sharePage(mActivity, tab.getTitle(),
550 tab.getUrl(), tab.getFavicon(),
551 createScreenshot(tab.getWebView(),
552 getDesiredThumbnailWidth(mActivity),
553 getDesiredThumbnailHeight(mActivity)));
554 }
555 }
556
Michael Kolb8233fac2010-10-26 16:08:53 -0700557 /**
558 * Share a page, providing the title, url, favicon, and a screenshot. Uses
559 * an {@link Intent} to launch the Activity chooser.
560 * @param c Context used to launch a new Activity.
561 * @param title Title of the page. Stored in the Intent with
562 * {@link Intent#EXTRA_SUBJECT}
563 * @param url URL of the page. Stored in the Intent with
564 * {@link Intent#EXTRA_TEXT}
565 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
566 * with {@link Browser#EXTRA_SHARE_FAVICON}
567 * @param screenshot Bitmap of a screenshot of the page. Stored in the
568 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
569 */
570 static final void sharePage(Context c, String title, String url,
571 Bitmap favicon, Bitmap screenshot) {
572 Intent send = new Intent(Intent.ACTION_SEND);
573 send.setType("text/plain");
574 send.putExtra(Intent.EXTRA_TEXT, url);
575 send.putExtra(Intent.EXTRA_SUBJECT, title);
576 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
577 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
578 try {
579 c.startActivity(Intent.createChooser(send, c.getString(
580 R.string.choosertitle_sharevia)));
581 } catch(android.content.ActivityNotFoundException ex) {
582 // if no app handles it, do nothing
583 }
584 }
585
586 private void copy(CharSequence text) {
587 ClipboardManager cm = (ClipboardManager) mActivity
588 .getSystemService(Context.CLIPBOARD_SERVICE);
589 cm.setText(text);
590 }
591
592 // lifecycle
593
594 protected void onConfgurationChanged(Configuration config) {
595 mConfigChanged = true;
596 if (mPageDialogsHandler != null) {
597 mPageDialogsHandler.onConfigurationChanged(config);
598 }
599 mUi.onConfigurationChanged(config);
600 }
601
602 @Override
603 public void handleNewIntent(Intent intent) {
604 mIntentHandler.onNewIntent(intent);
605 }
606
607 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800608 if (mUi.isCustomViewShowing()) {
609 hideCustomView();
610 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700611 if (mActivityPaused) {
612 Log.e(LOGTAG, "BrowserActivity is already paused.");
613 return;
614 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700615 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800616 Tab tab = mTabControl.getCurrentTab();
617 if (tab != null) {
618 tab.pause();
619 if (!pauseWebViewTimers(tab)) {
620 mWakeLock.acquire();
621 mHandler.sendMessageDelayed(mHandler
622 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
623 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700624 }
625 mUi.onPause();
626 mNetworkHandler.onPause();
627
628 WebView.disablePlatformNotifications();
John Reck847b5322011-04-14 17:02:18 -0700629 mCrashRecoveryHandler.clearState();
Michael Kolb8233fac2010-10-26 16:08:53 -0700630 }
631
632 void onSaveInstanceState(Bundle outState) {
633 // the default implementation requires each view to have an id. As the
634 // browser handles the state itself and it doesn't use id for the views,
635 // don't call the default implementation. Otherwise it will trigger the
636 // warning like this, "couldn't save which view has focus because the
637 // focused view XXX has no id".
638
639 // Save all the tabs
640 mTabControl.saveState(outState);
641 // Save time so that we know how old incognito tabs (if any) are.
642 outState.putSerializable("lastActiveDate", Calendar.getInstance());
643 }
644
645 void onResume() {
646 if (!mActivityPaused) {
647 Log.e(LOGTAG, "BrowserActivity is already resumed.");
648 return;
649 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700650 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800651 Tab current = mTabControl.getCurrentTab();
652 if (current != null) {
653 current.resume();
654 resumeWebViewTimers(current);
655 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700656 if (mWakeLock.isHeld()) {
657 mHandler.removeMessages(RELEASE_WAKELOCK);
658 mWakeLock.release();
659 }
660 mUi.onResume();
661 mNetworkHandler.onResume();
662 WebView.enablePlatformNotifications();
663 }
664
Michael Kolb70976932010-11-30 11:34:01 -0800665 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800666 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800667 * @param tab guaranteed non-null
668 */
669 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700670 boolean inLoad = tab.inPageLoad();
671 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
672 CookieSyncManager.getInstance().startSync();
673 WebView w = tab.getWebView();
674 if (w != null) {
675 w.resumeTimers();
676 }
677 }
678 }
679
Michael Kolb70976932010-11-30 11:34:01 -0800680 /**
681 * Pause all WebView timers using the WebView of the given tab
682 * @param tab
683 * @return true if the timers are paused or tab is null
684 */
685 private boolean pauseWebViewTimers(Tab tab) {
686 if (tab == null) {
687 return true;
688 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700689 CookieSyncManager.getInstance().stopSync();
690 WebView w = getCurrentWebView();
691 if (w != null) {
692 w.pauseTimers();
693 }
694 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700695 }
Michael Kolb70976932010-11-30 11:34:01 -0800696 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700697 }
698
699 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800700 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700701 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
702 mUploadHandler = null;
703 }
704 if (mTabControl == null) return;
705 mUi.onDestroy();
706 // Remove the current tab and sub window
707 Tab t = mTabControl.getCurrentTab();
708 if (t != null) {
709 dismissSubWindow(t);
710 removeTab(t);
711 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500712 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700713 // Destroy all the tabs
714 mTabControl.destroy();
715 WebIconDatabase.getInstance().close();
716 // Stop watching the default geolocation permissions
717 mSystemAllowGeolocationOrigins.stop();
718 mSystemAllowGeolocationOrigins = null;
719 }
720
721 protected boolean isActivityPaused() {
722 return mActivityPaused;
723 }
724
725 protected void onLowMemory() {
726 mTabControl.freeMemory();
727 }
728
729 @Override
730 public boolean shouldShowErrorConsole() {
731 return mShouldShowErrorConsole;
732 }
733
734 protected void setShouldShowErrorConsole(boolean show) {
735 if (show == mShouldShowErrorConsole) {
736 // Nothing to do.
737 return;
738 }
739 mShouldShowErrorConsole = show;
740 Tab t = mTabControl.getCurrentTab();
741 if (t == null) {
742 // There is no current tab so we cannot toggle the error console
743 return;
744 }
745 mUi.setShouldShowErrorConsole(t, show);
746 }
747
748 @Override
749 public void stopLoading() {
750 mLoadStopped = true;
751 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700752 WebView w = getCurrentTopWebView();
753 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700754 mUi.onPageStopped(tab);
755 }
756
757 boolean didUserStopLoading() {
758 return mLoadStopped;
759 }
760
761 // WebViewController
762
763 @Override
John Reck324d4402011-01-11 16:56:42 -0800764 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700765
766 // We've started to load a new page. If there was a pending message
767 // to save a screenshot then we will now take the new page and save
768 // an incorrect screenshot. Therefore, remove any pending thumbnail
769 // messages from the queue.
770 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800771 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700772
773 // reset sync timer to avoid sync starts during loading a page
774 CookieSyncManager.getInstance().resetSync();
775
776 if (!mNetworkHandler.isNetworkUp()) {
777 view.setNetworkAvailable(false);
778 }
779
780 // when BrowserActivity just starts, onPageStarted may be called before
781 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
782 // to start the timer. As we won't switch tabs while an activity is in
783 // pause state, we can ensure calling resume and pause in pair.
784 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800785 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700786 }
787 mLoadStopped = false;
788 if (!mNetworkHandler.isNetworkUp()) {
789 mNetworkHandler.createAndShowNetworkDialog();
790 }
791 endActionMode();
792
John Reck30c714c2010-12-16 17:30:34 -0800793 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700794
John Reck324d4402011-01-11 16:56:42 -0800795 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700796 // update the bookmark database for favicon
797 maybeUpdateFavicon(tab, null, url, favicon);
798
799 Performance.tracePageStart(url);
800
801 // Performance probe
802 if (false) {
803 Performance.onPageStarted();
804 }
805
806 }
807
808 @Override
John Reck324d4402011-01-11 16:56:42 -0800809 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800810 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800811 if (!tab.isPrivateBrowsingEnabled()
812 && !TextUtils.isEmpty(tab.getUrl())) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700813 if (tab.inForeground() && !didUserStopLoading()
814 || !tab.inForeground()) {
815 // Only update the bookmark screenshot if the user did not
816 // cancel the load early.
817 mHandler.sendMessageDelayed(mHandler.obtainMessage(
John Reck34ef2672011-02-10 11:30:55 -0800818 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
Michael Kolb8233fac2010-10-26 16:08:53 -0700819 500);
820 }
821 }
822 // pause the WebView timer and release the wake lock if it is finished
823 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800824 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700825 if (mWakeLock.isHeld()) {
826 mHandler.removeMessages(RELEASE_WAKELOCK);
827 mWakeLock.release();
828 }
829 }
830 // Performance probe
831 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800832 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700833 }
834
835 Performance.tracePageFinished();
836 }
837
838 @Override
John Reck30c714c2010-12-16 17:30:34 -0800839 public void onProgressChanged(Tab tab) {
840 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700841
842 if (newProgress == 100) {
843 CookieSyncManager.getInstance().sync();
844 // onProgressChanged() may continue to be called after the main
845 // frame has finished loading, as any remaining sub frames continue
846 // to load. We'll only get called once though with newProgress as
847 // 100 when everything is loaded. (onPageFinished is called once
848 // when the main frame completes loading regardless of the state of
849 // any sub frames so calls to onProgressChanges may continue after
850 // onPageFinished has executed)
851 if (mInLoad) {
852 mInLoad = false;
853 updateInLoadMenuItems(mCachedMenu);
854 }
855 } else {
856 if (!mInLoad) {
857 // onPageFinished may have already been called but a subframe is
858 // still loading and updating the progress. Reset mInLoad and
859 // update the menu items.
860 mInLoad = true;
861 updateInLoadMenuItems(mCachedMenu);
862 }
863 }
John Reck30c714c2010-12-16 17:30:34 -0800864 mUi.onProgressChanged(tab);
865 }
866
867 @Override
868 public void onUpdatedLockIcon(Tab tab) {
869 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700870 }
871
872 @Override
873 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800874 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800875 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800876 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700877 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
878 return;
879 }
880 // Update the title in the history database if not in private browsing mode
881 if (!tab.isPrivateBrowsingEnabled()) {
John Reck0ebd3ac2010-12-09 11:14:04 -0800882 mDataController.updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700883 }
884 }
885
886 @Override
887 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800888 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700889 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
890 }
891
892 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800893 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
894 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700895 }
896
897 @Override
898 public boolean shouldOverrideKeyEvent(KeyEvent event) {
899 if (mMenuIsDown) {
900 // only check shortcut key when MENU is held
901 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
902 event);
903 } else {
904 return false;
905 }
906 }
907
908 @Override
909 public void onUnhandledKeyEvent(KeyEvent event) {
910 if (!isActivityPaused()) {
911 if (event.getAction() == KeyEvent.ACTION_DOWN) {
912 mActivity.onKeyDown(event.getKeyCode(), event);
913 } else {
914 mActivity.onKeyUp(event.getKeyCode(), event);
915 }
916 }
917 }
918
919 @Override
John Reck324d4402011-01-11 16:56:42 -0800920 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700921 // Don't save anything in private browsing mode
922 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800923 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700924
John Reck324d4402011-01-11 16:56:42 -0800925 if (TextUtils.isEmpty(url)
926 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700927 return;
928 }
John Reck0ebd3ac2010-12-09 11:14:04 -0800929 mDataController.updateVisitedHistory(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700930 WebIconDatabase.getInstance().retainIconForPageUrl(url);
John Reck847b5322011-04-14 17:02:18 -0700931 if (!mActivityPaused) {
932 // Since we clear the state in onPause, don't backup the current
933 // state if we are already paused
934 mCrashRecoveryHandler.backupState();
935 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700936 }
937
938 @Override
939 public void getVisitedHistory(final ValueCallback<String[]> callback) {
940 AsyncTask<Void, Void, String[]> task =
941 new AsyncTask<Void, Void, String[]>() {
942 @Override
943 public String[] doInBackground(Void... unused) {
944 return Browser.getVisitedHistory(mActivity.getContentResolver());
945 }
946 @Override
947 public void onPostExecute(String[] result) {
948 callback.onReceiveValue(result);
949 }
950 };
951 task.execute();
952 }
953
954 @Override
955 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
956 final HttpAuthHandler handler, final String host,
957 final String realm) {
958 String username = null;
959 String password = null;
960
961 boolean reuseHttpAuthUsernamePassword
962 = handler.useHttpAuthUsernamePassword();
963
964 if (reuseHttpAuthUsernamePassword && view != null) {
965 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
966 if (credentials != null && credentials.length == 2) {
967 username = credentials[0];
968 password = credentials[1];
969 }
970 }
971
972 if (username != null && password != null) {
973 handler.proceed(username, password);
974 } else {
975 if (tab.inForeground()) {
976 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
977 } else {
978 handler.cancel();
979 }
980 }
981 }
982
983 @Override
984 public void onDownloadStart(Tab tab, String url, String userAgent,
985 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000986 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -0500987 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000988 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
989 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700990 // This Tab was opened for the sole purpose of downloading a
991 // file. Remove it.
992 if (tab == mTabControl.getCurrentTab()) {
993 // In this case, the Tab is still on top.
994 goBackOnePageOrQuit();
995 } else {
996 // In this case, it is not.
997 closeTab(tab);
998 }
999 }
1000 }
1001
1002 @Override
1003 public Bitmap getDefaultVideoPoster() {
1004 return mUi.getDefaultVideoPoster();
1005 }
1006
1007 @Override
1008 public View getVideoLoadingProgressView() {
1009 return mUi.getVideoLoadingProgressView();
1010 }
1011
1012 @Override
1013 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1014 SslError error) {
1015 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1016 }
1017
Patrick Scott92066772011-03-10 08:46:27 -05001018 @Override
1019 public void showAutoLogin(Tab tab) {
1020 assert tab.inForeground();
1021 // Update the title bar to show the auto-login request.
1022 mUi.showAutoLogin(tab);
1023 }
1024
1025 @Override
1026 public void hideAutoLogin(Tab tab) {
1027 assert tab.inForeground();
1028 mUi.hideAutoLogin(tab);
1029 }
1030
Michael Kolb8233fac2010-10-26 16:08:53 -07001031 // helper method
1032
1033 /*
1034 * Update the favorites icon if the private browsing isn't enabled and the
1035 * icon is valid.
1036 */
1037 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1038 final String url, Bitmap favicon) {
1039 if (favicon == null) {
1040 return;
1041 }
1042 if (!tab.isPrivateBrowsingEnabled()) {
1043 Bookmarks.updateFavicon(mActivity
1044 .getContentResolver(), originalUrl, url, favicon);
1045 }
1046 }
1047
Leon Scroggins4cd97792010-12-03 15:31:56 -05001048 @Override
1049 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001050 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001051 mUi.bookmarkedStatusHasChanged(tab);
1052 }
1053
Michael Kolb8233fac2010-10-26 16:08:53 -07001054 // end WebViewController
1055
1056 protected void pageUp() {
1057 getCurrentTopWebView().pageUp(false);
1058 }
1059
1060 protected void pageDown() {
1061 getCurrentTopWebView().pageDown(false);
1062 }
1063
1064 // callback from phone title bar
1065 public void editUrl() {
1066 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001067 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001068 }
1069
Michael Kolbcfa3af52010-12-14 10:36:11 -08001070 public void startVoiceSearch() {
1071 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1072 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1073 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1074 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1075 mActivity.getComponentName().flattenToString());
1076 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001077 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001078 mActivity.startActivity(intent);
1079 }
1080
Michael Kolb11d19782011-03-20 10:17:40 -07001081 @Override
1082 public void activateVoiceSearchMode(String title, List<String> results) {
1083 mUi.showVoiceTitleBar(title, results);
Michael Kolb8233fac2010-10-26 16:08:53 -07001084 }
1085
1086 public void revertVoiceSearchMode(Tab tab) {
1087 mUi.revertVoiceTitleBar(tab);
1088 }
1089
Michael Kolb736990c2011-03-20 10:01:20 -07001090 public boolean supportsVoiceSearch() {
John Reck35e9dd62011-04-25 09:01:54 -07001091 SearchEngine searchEngine = getSettings().getSearchEngine();
Michael Kolb736990c2011-03-20 10:01:20 -07001092 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1093 }
1094
Michael Kolb8233fac2010-10-26 16:08:53 -07001095 public void showCustomView(Tab tab, View view,
1096 WebChromeClient.CustomViewCallback callback) {
1097 if (tab.inForeground()) {
1098 if (mUi.isCustomViewShowing()) {
1099 callback.onCustomViewHidden();
1100 return;
1101 }
1102 mUi.showCustomView(view, callback);
1103 // Save the menu state and set it to empty while the custom
1104 // view is showing.
1105 mOldMenuState = mMenuState;
1106 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001107 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001108 }
1109 }
1110
1111 @Override
1112 public void hideCustomView() {
1113 if (mUi.isCustomViewShowing()) {
1114 mUi.onHideCustomView();
1115 // Reset the old menu state.
1116 mMenuState = mOldMenuState;
1117 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001118 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001119 }
1120 }
1121
1122 protected void onActivityResult(int requestCode, int resultCode,
1123 Intent intent) {
1124 if (getCurrentTopWebView() == null) return;
1125 switch (requestCode) {
1126 case PREFERENCES_PAGE:
1127 if (resultCode == Activity.RESULT_OK && intent != null) {
1128 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001129 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001130 mTabControl.removeParentChildRelationShips();
1131 }
1132 }
1133 break;
1134 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001135 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001136 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001137 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001138 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001139 case AUTOFILL_SETUP:
1140 // Determine whether a profile was actually set up or not
1141 // and if so, send the message back to the WebTextView to
1142 // fill the form with the new profile.
1143 if (getSettings().getAutoFillProfile() != null) {
1144 mAutoFillSetupMessage.sendToTarget();
1145 mAutoFillSetupMessage = null;
1146 }
1147 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001148 default:
1149 break;
1150 }
1151 getCurrentTopWebView().requestFocus();
1152 }
1153
1154 /**
1155 * Open the Go page.
1156 * @param startWithHistory If true, open starting on the history tab.
1157 * Otherwise, start with the bookmarks tab.
1158 */
1159 @Override
1160 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1161 if (mTabControl.getCurrentWebView() == null) {
1162 return;
1163 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001164 // clear action mode
1165 if (isInCustomActionMode()) {
1166 endActionMode();
1167 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001168 Bundle extras = new Bundle();
1169 // Disable opening in a new window if we have maxed out the windows
1170 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1171 !mTabControl.canCreateNewTab());
1172 mUi.showComboView(startWithHistory, extras);
1173 }
1174
1175 // combo view callbacks
1176
1177 /**
1178 * callback from ComboPage when clear history is requested
1179 */
1180 public void onRemoveParentChildRelationships() {
1181 mTabControl.removeParentChildRelationShips();
1182 }
1183
1184 /**
1185 * callback from ComboPage when bookmark/history selection
1186 */
1187 @Override
1188 public void onUrlSelected(String url, boolean newTab) {
1189 removeComboView();
1190 if (!TextUtils.isEmpty(url)) {
1191 if (newTab) {
Michael Kolb18eb3772010-12-10 14:29:51 -08001192 openTab(mTabControl.getCurrentTab(), url, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001193 } else {
1194 final Tab currentTab = mTabControl.getCurrentTab();
1195 dismissSubWindow(currentTab);
1196 loadUrl(getCurrentTopWebView(), url);
1197 }
1198 }
1199 }
1200
1201 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07001202 * dismiss the ComboPage
1203 */
1204 @Override
1205 public void removeComboView() {
1206 mUi.hideComboView();
1207 }
1208
1209 // active tabs page handling
1210
1211 protected void showActiveTabsPage() {
1212 mMenuState = EMPTY_MENU;
1213 mUi.showActiveTabsPage();
1214 }
1215
1216 /**
1217 * Remove the active tabs page.
1218 * @param needToAttach If true, the active tabs page did not attach a tab
1219 * to the content view, so we need to do that here.
1220 */
1221 @Override
1222 public void removeActiveTabsPage(boolean needToAttach) {
1223 mMenuState = R.id.MAIN_MENU;
1224 mUi.removeActiveTabsPage();
1225 if (needToAttach) {
1226 setActiveTab(mTabControl.getCurrentTab());
1227 }
1228 getCurrentTopWebView().requestFocus();
1229 }
1230
1231 // key handling
1232 protected void onBackKey() {
1233 if (!mUi.onBackKey()) {
1234 WebView subwindow = mTabControl.getCurrentSubWindow();
1235 if (subwindow != null) {
1236 if (subwindow.canGoBack()) {
1237 subwindow.goBack();
1238 } else {
1239 dismissSubWindow(mTabControl.getCurrentTab());
1240 }
1241 } else {
1242 goBackOnePageOrQuit();
1243 }
1244 }
1245 }
1246
1247 // menu handling and state
1248 // TODO: maybe put into separate handler
1249
1250 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckb3417f02011-01-14 11:01:05 -08001251 if (mOptionsMenuHandler != null) {
1252 return mOptionsMenuHandler.onCreateOptionsMenu(menu);
1253 }
1254
John Reckd73c5a22010-12-22 10:22:50 -08001255 if (mMenuState == EMPTY_MENU) {
1256 return false;
1257 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001258 MenuInflater inflater = mActivity.getMenuInflater();
1259 inflater.inflate(R.menu.browser, menu);
1260 updateInLoadMenuItems(menu);
1261 // hold on to the menu reference here; it is used by the page callbacks
1262 // to update the menu based on loading state
1263 mCachedMenu = menu;
1264 return true;
1265 }
1266
1267 protected void onCreateContextMenu(ContextMenu menu, View v,
1268 ContextMenuInfo menuInfo) {
1269 if (v instanceof TitleBarBase) {
1270 return;
1271 }
1272 if (!(v instanceof WebView)) {
1273 return;
1274 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001275 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001276 WebView.HitTestResult result = webview.getHitTestResult();
1277 if (result == null) {
1278 return;
1279 }
1280
1281 int type = result.getType();
1282 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1283 Log.w(LOGTAG,
1284 "We should not show context menu when nothing is touched");
1285 return;
1286 }
1287 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1288 // let TextView handles context menu
1289 return;
1290 }
1291
1292 // Note, http://b/issue?id=1106666 is requesting that
1293 // an inflated menu can be used again. This is not available
1294 // yet, so inflate each time (yuk!)
1295 MenuInflater inflater = mActivity.getMenuInflater();
1296 inflater.inflate(R.menu.browsercontext, menu);
1297
1298 // Show the correct menu group
1299 final String extra = result.getExtra();
1300 menu.setGroupVisible(R.id.PHONE_MENU,
1301 type == WebView.HitTestResult.PHONE_TYPE);
1302 menu.setGroupVisible(R.id.EMAIL_MENU,
1303 type == WebView.HitTestResult.EMAIL_TYPE);
1304 menu.setGroupVisible(R.id.GEO_MENU,
1305 type == WebView.HitTestResult.GEO_TYPE);
1306 menu.setGroupVisible(R.id.IMAGE_MENU,
1307 type == WebView.HitTestResult.IMAGE_TYPE
1308 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1309 menu.setGroupVisible(R.id.ANCHOR_MENU,
1310 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1311 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001312 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1313 || type == WebView.HitTestResult.PHONE_TYPE
1314 || type == WebView.HitTestResult.EMAIL_TYPE
1315 || type == WebView.HitTestResult.GEO_TYPE;
1316 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1317 if (hitText) {
1318 menu.findItem(R.id.select_text_menu_id)
1319 .setOnMenuItemClickListener(new SelectText(webview));
1320 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001321 // Setup custom handling depending on the type
1322 switch (type) {
1323 case WebView.HitTestResult.PHONE_TYPE:
1324 menu.setHeaderTitle(Uri.decode(extra));
1325 menu.findItem(R.id.dial_context_menu_id).setIntent(
1326 new Intent(Intent.ACTION_VIEW, Uri
1327 .parse(WebView.SCHEME_TEL + extra)));
1328 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1329 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1330 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1331 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1332 addIntent);
1333 menu.findItem(R.id.copy_phone_context_menu_id)
1334 .setOnMenuItemClickListener(
1335 new Copy(extra));
1336 break;
1337
1338 case WebView.HitTestResult.EMAIL_TYPE:
1339 menu.setHeaderTitle(extra);
1340 menu.findItem(R.id.email_context_menu_id).setIntent(
1341 new Intent(Intent.ACTION_VIEW, Uri
1342 .parse(WebView.SCHEME_MAILTO + extra)));
1343 menu.findItem(R.id.copy_mail_context_menu_id)
1344 .setOnMenuItemClickListener(
1345 new Copy(extra));
1346 break;
1347
1348 case WebView.HitTestResult.GEO_TYPE:
1349 menu.setHeaderTitle(extra);
1350 menu.findItem(R.id.map_context_menu_id).setIntent(
1351 new Intent(Intent.ACTION_VIEW, Uri
1352 .parse(WebView.SCHEME_GEO
1353 + URLEncoder.encode(extra))));
1354 menu.findItem(R.id.copy_geo_context_menu_id)
1355 .setOnMenuItemClickListener(
1356 new Copy(extra));
1357 break;
1358
1359 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1360 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001361 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001362 // decide whether to show the open link in new tab option
1363 boolean showNewTab = mTabControl.canCreateNewTab();
1364 MenuItem newTabItem
1365 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001366 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001367 ? R.string.contextmenu_openlink_newwindow_background
1368 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001369 newTabItem.setVisible(showNewTab);
1370 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001371 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1372 newTabItem.setOnMenuItemClickListener(
1373 new MenuItem.OnMenuItemClickListener() {
1374 @Override
1375 public boolean onMenuItemClick(MenuItem item) {
1376 final HashMap<String, WebView> hrefMap =
1377 new HashMap<String, WebView>();
1378 hrefMap.put("webview", webview);
1379 final Message msg = mHandler.obtainMessage(
1380 FOCUS_NODE_HREF,
1381 R.id.open_newtab_context_menu_id,
1382 0, hrefMap);
1383 webview.requestFocusNodeHref(msg);
1384 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001385 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001386 });
1387 } else {
1388 newTabItem.setOnMenuItemClickListener(
1389 new MenuItem.OnMenuItemClickListener() {
1390 @Override
1391 public boolean onMenuItemClick(MenuItem item) {
1392 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -08001393 final Tab newTab = openTab(parent,
1394 extra, false);
Leon Scroggins026f2542010-11-22 13:26:12 -05001395 if (newTab != parent) {
1396 parent.addChildTab(newTab);
1397 }
1398 return true;
1399 }
1400 });
1401 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001402 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001403 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1404 break;
1405 }
1406 // otherwise fall through to handle image part
1407 case WebView.HitTestResult.IMAGE_TYPE:
1408 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1409 menu.setHeaderTitle(extra);
1410 }
1411 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1412 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1413 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001414 setOnMenuItemClickListener(
1415 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001416 menu.findItem(R.id.set_wallpaper_context_menu_id).
1417 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1418 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001419 break;
1420
1421 default:
1422 Log.w(LOGTAG, "We should not get here.");
1423 break;
1424 }
1425 //update the ui
1426 mUi.onContextMenuCreated(menu);
1427 }
1428
1429 /**
1430 * As the menu can be open when loading state changes
1431 * we must manually update the state of the stop/reload menu
1432 * item
1433 */
1434 private void updateInLoadMenuItems(Menu menu) {
1435 if (menu == null) {
1436 return;
1437 }
1438 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1439 MenuItem src = mInLoad ?
1440 menu.findItem(R.id.stop_menu_id):
1441 menu.findItem(R.id.reload_menu_id);
1442 if (src != null) {
1443 dest.setIcon(src.getIcon());
1444 dest.setTitle(src.getTitle());
1445 }
1446 }
1447
John Reckb3417f02011-01-14 11:01:05 -08001448 boolean onPrepareOptionsMenu(Menu menu) {
1449 if (mOptionsMenuHandler != null) {
1450 return mOptionsMenuHandler.onPrepareOptionsMenu(menu);
1451 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001452 // Note: setVisible will decide whether an item is visible; while
1453 // setEnabled() will decide whether an item is enabled, which also means
1454 // whether the matching shortcut key will function.
1455 switch (mMenuState) {
1456 case EMPTY_MENU:
1457 if (mCurrentMenuState != mMenuState) {
1458 menu.setGroupVisible(R.id.MAIN_MENU, false);
1459 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1460 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1461 }
1462 break;
1463 default:
1464 if (mCurrentMenuState != mMenuState) {
1465 menu.setGroupVisible(R.id.MAIN_MENU, true);
1466 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1467 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1468 }
1469 final WebView w = getCurrentTopWebView();
1470 boolean canGoBack = false;
1471 boolean canGoForward = false;
1472 boolean isHome = false;
1473 if (w != null) {
1474 canGoBack = w.canGoBack();
1475 canGoForward = w.canGoForward();
1476 isHome = mSettings.getHomePage().equals(w.getUrl());
1477 }
1478 final MenuItem back = menu.findItem(R.id.back_menu_id);
1479 back.setEnabled(canGoBack);
1480
1481 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1482 home.setEnabled(!isHome);
1483
1484 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1485 forward.setEnabled(canGoForward);
1486
1487 // decide whether to show the share link option
1488 PackageManager pm = mActivity.getPackageManager();
1489 Intent send = new Intent(Intent.ACTION_SEND);
1490 send.setType("text/plain");
1491 ResolveInfo ri = pm.resolveActivity(send,
1492 PackageManager.MATCH_DEFAULT_ONLY);
1493 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1494
John Reck35e9dd62011-04-25 09:01:54 -07001495 boolean isNavDump = mSettings.enableNavDump();
Michael Kolb8233fac2010-10-26 16:08:53 -07001496 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1497 nav.setVisible(isNavDump);
1498 nav.setEnabled(isNavDump);
1499
John Reck35e9dd62011-04-25 09:01:54 -07001500 boolean showDebugSettings = mSettings.isDebugEnabled();
Michael Kolb8233fac2010-10-26 16:08:53 -07001501 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1502 counter.setVisible(showDebugSettings);
1503 counter.setEnabled(showDebugSettings);
1504
John Reckb3417f02011-01-14 11:01:05 -08001505 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1506 newtab.setEnabled(getTabControl().canCreateNewTab());
Michael Kolb8233fac2010-10-26 16:08:53 -07001507
Leon Scroggins81983762011-02-11 15:17:36 -05001508 MenuItem archive = menu.findItem(R.id.save_webarchive_menu_id);
John Reck51d8bad2011-02-28 15:47:47 -08001509 Tab tab = getTabControl().getCurrentTab();
1510 String url = tab != null ? tab.getUrl() : null;
1511 archive.setVisible(!TextUtils.isEmpty(url)
1512 && !url.endsWith(".webarchivexml"));
Michael Kolb8233fac2010-10-26 16:08:53 -07001513 break;
1514 }
1515 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001516 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001517 }
1518
1519 public boolean onOptionsItemSelected(MenuItem item) {
John Reckb3417f02011-01-14 11:01:05 -08001520 if (mOptionsMenuHandler != null &&
1521 mOptionsMenuHandler.onOptionsItemSelected(item)) {
1522 return true;
1523 }
1524
Michael Kolb8233fac2010-10-26 16:08:53 -07001525 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1526 // menu remains active, so ensure comboview is dismissed
1527 // if main menu option is selected
1528 removeComboView();
1529 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001530 if (null == getCurrentTopWebView()) {
1531 return false;
1532 }
1533 if (mMenuIsDown) {
1534 // The shortcut action consumes the MENU. Even if it is still down,
1535 // it won't trigger the next shortcut action. In the case of the
1536 // shortcut action triggering a new activity, like Bookmarks, we
1537 // won't get onKeyUp for MENU. So it is important to reset it here.
1538 mMenuIsDown = false;
1539 }
1540 switch (item.getItemId()) {
1541 // -- Main menu
1542 case R.id.new_tab_menu_id:
1543 openTabToHomePage();
1544 break;
1545
1546 case R.id.incognito_menu_id:
1547 openIncognitoTab();
1548 break;
1549
1550 case R.id.goto_menu_id:
1551 editUrl();
1552 break;
1553
1554 case R.id.bookmarks_menu_id:
1555 bookmarksOrHistoryPicker(false);
1556 break;
1557
1558 case R.id.active_tabs_menu_id:
1559 showActiveTabsPage();
1560 break;
1561
1562 case R.id.add_bookmark_menu_id:
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001563 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001564 break;
1565
1566 case R.id.stop_reload_menu_id:
1567 if (mInLoad) {
1568 stopLoading();
1569 } else {
1570 getCurrentTopWebView().reload();
1571 }
1572 break;
1573
1574 case R.id.back_menu_id:
1575 getCurrentTopWebView().goBack();
1576 break;
1577
1578 case R.id.forward_menu_id:
1579 getCurrentTopWebView().goForward();
1580 break;
1581
1582 case R.id.close_menu_id:
1583 // Close the subwindow if it exists.
1584 if (mTabControl.getCurrentSubWindow() != null) {
1585 dismissSubWindow(mTabControl.getCurrentTab());
1586 break;
1587 }
1588 closeCurrentTab();
1589 break;
1590
1591 case R.id.homepage_menu_id:
1592 Tab current = mTabControl.getCurrentTab();
1593 if (current != null) {
1594 dismissSubWindow(current);
1595 loadUrl(current.getWebView(), mSettings.getHomePage());
1596 }
1597 break;
1598
1599 case R.id.preferences_menu_id:
1600 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1601 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1602 getCurrentTopWebView().getUrl());
1603 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1604 break;
1605
1606 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001607 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001608 break;
1609
Leon Scrogginsac993842011-02-02 12:54:07 -05001610 case R.id.save_webarchive_menu_id:
1611 String state = Environment.getExternalStorageState();
1612 if (!Environment.MEDIA_MOUNTED.equals(state)) {
1613 Log.e(LOGTAG, "External storage not mounted");
1614 Toast.makeText(mActivity, R.string.webarchive_failed,
1615 Toast.LENGTH_SHORT).show();
1616 break;
1617 }
1618 final String directory = Environment.getExternalStoragePublicDirectory(
1619 Environment.DIRECTORY_DOWNLOADS) + File.separator;
1620 File dir = new File(directory);
1621 if (!dir.exists() && !dir.mkdirs()) {
1622 Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
1623 Toast.makeText(mActivity, R.string.webarchive_failed,
1624 Toast.LENGTH_SHORT).show();
1625 break;
1626 }
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001627 final WebView topWebView = getCurrentTopWebView();
Leon Scrogginsac993842011-02-02 12:54:07 -05001628 final String title = topWebView.getTitle();
John Reck51d8bad2011-02-28 15:47:47 -08001629 final String url = topWebView.getUrl();
Leon Scrogginsac993842011-02-02 12:54:07 -05001630 topWebView.saveWebArchive(directory, true,
1631 new ValueCallback<String>() {
1632 @Override
1633 public void onReceiveValue(final String value) {
1634 if (value != null) {
1635 File file = new File(value);
1636 final long length = file.length();
1637 if (file.exists() && length > 0) {
Leon Scroggins1cb96552011-02-11 14:22:57 -05001638 Toast.makeText(mActivity, R.string.webarchive_saved,
1639 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001640 final DownloadManager manager = (DownloadManager) mActivity
1641 .getSystemService(Context.DOWNLOAD_SERVICE);
1642 new Thread("Add WebArchive to download manager") {
1643 @Override
1644 public void run() {
Vasu Noria9e30a72011-03-07 11:37:34 -08001645 manager.addCompletedDownload(
1646 null == title ? value : title,
Leon Scrogginsac993842011-02-02 12:54:07 -05001647 value, true, "application/x-webarchive-xml",
1648 value, length, true);
1649 }
1650 }.start();
1651 return;
1652 }
1653 }
John Reck51d8bad2011-02-28 15:47:47 -08001654 DownloadHandler.onDownloadStartNoStream(mActivity,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001655 url, null, null, null, topWebView.isPrivateBrowsingEnabled());
Leon Scrogginsac993842011-02-02 12:54:07 -05001656 }
1657 });
1658 break;
1659
Michael Kolb8233fac2010-10-26 16:08:53 -07001660 case R.id.page_info_menu_id:
1661 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1662 false);
1663 break;
1664
1665 case R.id.classic_history_menu_id:
1666 bookmarksOrHistoryPicker(true);
1667 break;
1668
1669 case R.id.title_bar_share_page_url:
1670 case R.id.share_page_menu_id:
1671 Tab currentTab = mTabControl.getCurrentTab();
1672 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001673 return false;
1674 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001675 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001676 break;
1677
1678 case R.id.dump_nav_menu_id:
1679 getCurrentTopWebView().debugDump();
1680 break;
1681
1682 case R.id.dump_counters_menu_id:
1683 getCurrentTopWebView().dumpV8Counters();
1684 break;
1685
1686 case R.id.zoom_in_menu_id:
1687 getCurrentTopWebView().zoomIn();
1688 break;
1689
1690 case R.id.zoom_out_menu_id:
1691 getCurrentTopWebView().zoomOut();
1692 break;
1693
1694 case R.id.view_downloads_menu_id:
1695 viewDownloads();
1696 break;
1697
1698 case R.id.window_one_menu_id:
1699 case R.id.window_two_menu_id:
1700 case R.id.window_three_menu_id:
1701 case R.id.window_four_menu_id:
1702 case R.id.window_five_menu_id:
1703 case R.id.window_six_menu_id:
1704 case R.id.window_seven_menu_id:
1705 case R.id.window_eight_menu_id:
1706 {
1707 int menuid = item.getItemId();
1708 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1709 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1710 Tab desiredTab = mTabControl.getTab(id);
1711 if (desiredTab != null &&
1712 desiredTab != mTabControl.getCurrentTab()) {
1713 switchToTab(id);
1714 }
1715 break;
1716 }
1717 }
1718 }
1719 break;
1720
1721 default:
1722 return false;
1723 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001724 return true;
1725 }
1726
1727 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001728 // Let the History and Bookmark fragments handle menus they created.
1729 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1730 return false;
1731 }
1732
Michael Kolb8233fac2010-10-26 16:08:53 -07001733 int id = item.getItemId();
1734 boolean result = true;
1735 switch (id) {
1736 // For the context menu from the title bar
1737 case R.id.title_bar_copy_page_url:
1738 Tab currentTab = mTabControl.getCurrentTab();
1739 if (null == currentTab) {
1740 result = false;
1741 break;
1742 }
1743 WebView mainView = currentTab.getWebView();
1744 if (null == mainView) {
1745 result = false;
1746 break;
1747 }
1748 copy(mainView.getUrl());
1749 break;
1750 // -- Browser context menu
1751 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001752 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001753 case R.id.copy_link_context_menu_id:
1754 final WebView webView = getCurrentTopWebView();
1755 if (null == webView) {
1756 result = false;
1757 break;
1758 }
1759 final HashMap<String, WebView> hrefMap =
1760 new HashMap<String, WebView>();
1761 hrefMap.put("webview", webView);
1762 final Message msg = mHandler.obtainMessage(
1763 FOCUS_NODE_HREF, id, 0, hrefMap);
1764 webView.requestFocusNodeHref(msg);
1765 break;
1766
1767 default:
1768 // For other context menus
1769 result = onOptionsItemSelected(item);
1770 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001771 return result;
1772 }
1773
1774 /**
1775 * support programmatically opening the context menu
1776 */
1777 public void openContextMenu(View view) {
1778 mActivity.openContextMenu(view);
1779 }
1780
1781 /**
1782 * programmatically open the options menu
1783 */
1784 public void openOptionsMenu() {
1785 mActivity.openOptionsMenu();
1786 }
1787
1788 public boolean onMenuOpened(int featureId, Menu menu) {
1789 if (mOptionsMenuOpen) {
1790 if (mConfigChanged) {
1791 // We do not need to make any changes to the state of the
1792 // title bar, since the only thing that happened was a
1793 // change in orientation
1794 mConfigChanged = false;
1795 } else {
1796 if (!mExtendedMenuOpen) {
1797 mExtendedMenuOpen = true;
1798 mUi.onExtendedMenuOpened();
1799 } else {
1800 // Switching the menu back to icon view, so show the
1801 // title bar once again.
1802 mExtendedMenuOpen = false;
1803 mUi.onExtendedMenuClosed(mInLoad);
Michael Kolb8233fac2010-10-26 16:08:53 -07001804 }
1805 }
1806 } else {
1807 // The options menu is closed, so open it, and show the title
1808 mOptionsMenuOpen = true;
1809 mConfigChanged = false;
1810 mExtendedMenuOpen = false;
1811 mUi.onOptionsMenuOpened();
1812 }
1813 return true;
1814 }
1815
1816 public void onOptionsMenuClosed(Menu menu) {
1817 mOptionsMenuOpen = false;
1818 mUi.onOptionsMenuClosed(mInLoad);
1819 }
1820
1821 public void onContextMenuClosed(Menu menu) {
1822 mUi.onContextMenuClosed(menu, mInLoad);
1823 }
1824
1825 // Helper method for getting the top window.
1826 @Override
1827 public WebView getCurrentTopWebView() {
1828 return mTabControl.getCurrentTopWebView();
1829 }
1830
1831 @Override
1832 public WebView getCurrentWebView() {
1833 return mTabControl.getCurrentWebView();
1834 }
1835
1836 /*
1837 * This method is called as a result of the user selecting the options
1838 * menu to see the download window. It shows the download window on top of
1839 * the current window.
1840 */
1841 void viewDownloads() {
1842 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1843 mActivity.startActivity(intent);
1844 }
1845
1846 // action mode
1847
1848 void onActionModeStarted(ActionMode mode) {
1849 mUi.onActionModeStarted(mode);
1850 mActionMode = mode;
1851 }
1852
1853 /*
1854 * True if a custom ActionMode (i.e. find or select) is in use.
1855 */
1856 @Override
1857 public boolean isInCustomActionMode() {
1858 return mActionMode != null;
1859 }
1860
1861 /*
1862 * End the current ActionMode.
1863 */
1864 @Override
1865 public void endActionMode() {
1866 if (mActionMode != null) {
1867 mActionMode.finish();
1868 }
1869 }
1870
1871 /*
1872 * Called by find and select when they are finished. Replace title bars
1873 * as necessary.
1874 */
1875 public void onActionModeFinished(ActionMode mode) {
1876 if (!isInCustomActionMode()) return;
1877 mUi.onActionModeFinished(mInLoad);
1878 mActionMode = null;
1879 }
1880
1881 boolean isInLoad() {
1882 return mInLoad;
1883 }
1884
1885 // bookmark handling
1886
1887 /**
1888 * add the current page as a bookmark to the given folder id
1889 * @param folderId use -1 for the default folder
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001890 * @param canBeAnEdit If true, check to see whether the site is already
1891 * bookmarked, and if it is, edit that bookmark. If false, and
1892 * the site is already bookmarked, do not attempt to edit the
1893 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001894 */
1895 @Override
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001896 public void bookmarkCurrentPage(long folderId, boolean canBeAnEdit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001897 Intent i = new Intent(mActivity,
1898 AddBookmarkPage.class);
1899 WebView w = getCurrentTopWebView();
1900 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1901 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1902 String touchIconUrl = w.getTouchIconUrl();
1903 if (touchIconUrl != null) {
1904 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1905 WebSettings settings = w.getSettings();
1906 if (settings != null) {
1907 i.putExtra(AddBookmarkPage.USER_AGENT,
1908 settings.getUserAgentString());
1909 }
1910 }
1911 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1912 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1913 getDesiredThumbnailHeight(mActivity)));
1914 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1915 i.putExtra(BrowserContract.Bookmarks.PARENT,
1916 folderId);
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001917 if (canBeAnEdit) {
1918 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1919 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001920 // Put the dialog at the upper right of the screen, covering the
1921 // star on the title bar.
1922 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1923 mActivity.startActivity(i);
1924 }
1925
1926 // file chooser
1927 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1928 mUploadHandler = new UploadHandler(this);
1929 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1930 }
1931
1932 // thumbnails
1933
1934 /**
1935 * Return the desired width for thumbnail screenshots, which are stored in
1936 * the database, and used on the bookmarks screen.
1937 * @param context Context for finding out the density of the screen.
1938 * @return desired width for thumbnail screenshot.
1939 */
1940 static int getDesiredThumbnailWidth(Context context) {
1941 return context.getResources().getDimensionPixelOffset(
1942 R.dimen.bookmarkThumbnailWidth);
1943 }
1944
1945 /**
1946 * Return the desired height for thumbnail screenshots, which are stored in
1947 * the database, and used on the bookmarks screen.
1948 * @param context Context for finding out the density of the screen.
1949 * @return desired height for thumbnail screenshot.
1950 */
1951 static int getDesiredThumbnailHeight(Context context) {
1952 return context.getResources().getDimensionPixelOffset(
1953 R.dimen.bookmarkThumbnailHeight);
1954 }
1955
Michael Kolb1acef692011-03-08 14:12:06 -08001956 static Bitmap createScreenshot(Tab tab, int width, int height) {
1957 if ((tab != null) && (tab.getWebView() != null)) {
1958 return createScreenshot(tab.getWebView(), width, height);
1959 }
1960 return null;
1961 }
1962
Michael Kolb8233fac2010-10-26 16:08:53 -07001963 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001964 // We render to a bitmap 2x the desired size so that we can then
1965 // re-scale it with filtering since canvas.scale doesn't filter
1966 // This helps reduce aliasing at the cost of being slightly blurry
1967 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001968 Picture thumbnail = view.capturePicture();
1969 if (thumbnail == null) {
1970 return null;
1971 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001972 width *= filter_scale;
1973 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001974 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1975 Canvas canvas = new Canvas(bm);
1976 // May need to tweak these values to determine what is the
1977 // best scale factor
1978 int thumbnailWidth = thumbnail.getWidth();
1979 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001980 float scaleFactor = 1.0f;
Michael Kolbeb95db42011-03-03 10:38:40 -08001981 if (thumbnailWidth > 0 && thumbnailHeight > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001982 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001983 } else {
1984 return null;
1985 }
John Reckfe49ab42010-11-16 17:09:37 -08001986
Michael Kolbeb95db42011-03-03 10:38:40 -08001987 float scaleFactorY = (float) height / (float)thumbnailHeight;
1988 if (scaleFactorY > scaleFactor) {
1989 // The picture is narrower than the requested AR
1990 // Center the thumnail and crop the sides
1991 scaleFactor = scaleFactorY;
John Reckfe49ab42010-11-16 17:09:37 -08001992 float wx = (thumbnailWidth * scaleFactor) - width;
1993 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001994 }
1995
John Reckfe49ab42010-11-16 17:09:37 -08001996 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001997
1998 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001999 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
2000 height / filter_scale, true);
2001 bm.recycle();
2002 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07002003 }
2004
John Reck34ef2672011-02-10 11:30:55 -08002005 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002006 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07002007 // FIXME: Would like to make sure there is actually something to
2008 // draw, but the API for that (WebViewCore.pictureReady()) is not
2009 // currently accessible here.
2010
John Reck34ef2672011-02-10 11:30:55 -08002011 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08002012 if (view == null) {
2013 // Tab was destroyed
2014 return;
2015 }
John Reck34ef2672011-02-10 11:30:55 -08002016 final String url = tab.getUrl();
2017 final String originalUrl = view.getOriginalUrl();
2018
2019 if (TextUtils.isEmpty(url)) {
2020 return;
2021 }
2022
2023 // Only update thumbnails for web urls (http(s)://), not for
2024 // about:, javascript:, data:, etc...
2025 // Unless it is a bookmarked site, then always update
2026 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2027 return;
2028 }
2029
Michael Kolb8233fac2010-10-26 16:08:53 -07002030 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2031 getDesiredThumbnailHeight(mActivity));
2032 if (bm == null) {
2033 return;
2034 }
2035
2036 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002037 new AsyncTask<Void, Void, Void>() {
2038 @Override
2039 protected Void doInBackground(Void... unused) {
2040 Cursor cursor = null;
2041 try {
2042 // TODO: Clean this up
2043 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2044 if (cursor != null && cursor.moveToFirst()) {
2045 final ByteArrayOutputStream os =
2046 new ByteArrayOutputStream();
2047 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002048
John Reck34ef2672011-02-10 11:30:55 -08002049 ContentValues values = new ContentValues();
2050 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002051
John Reck34ef2672011-02-10 11:30:55 -08002052 do {
John Reck617fd832011-02-16 14:35:59 -08002053 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002054 cr.update(Images.CONTENT_URI, values, null, null);
2055 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002056 }
John Reck34ef2672011-02-10 11:30:55 -08002057 } catch (IllegalStateException e) {
2058 // Ignore
2059 } finally {
2060 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002061 }
John Reck34ef2672011-02-10 11:30:55 -08002062 return null;
2063 }
2064 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002065 }
2066
2067 private class Copy implements OnMenuItemClickListener {
2068 private CharSequence mText;
2069
2070 public boolean onMenuItemClick(MenuItem item) {
2071 copy(mText);
2072 return true;
2073 }
2074
2075 public Copy(CharSequence toCopy) {
2076 mText = toCopy;
2077 }
2078 }
2079
Leon Scroggins63c02662010-11-18 15:16:27 -05002080 private static class Download implements OnMenuItemClickListener {
2081 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002082 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002083 private boolean mPrivateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002084
2085 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002086 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002087 null, null, mPrivateBrowsing);
Michael Kolb8233fac2010-10-26 16:08:53 -07002088 return true;
2089 }
2090
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002091 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002092 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002093 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002094 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002095 }
2096 }
2097
Cary Clark8974d282010-11-22 10:46:05 -05002098 private static class SelectText implements OnMenuItemClickListener {
2099 private WebView mWebView;
2100
2101 public boolean onMenuItemClick(MenuItem item) {
2102 if (mWebView != null) {
2103 return mWebView.selectText();
2104 }
2105 return false;
2106 }
2107
2108 public SelectText(WebView webView) {
2109 mWebView = webView;
2110 }
2111
2112 }
2113
Michael Kolb8233fac2010-10-26 16:08:53 -07002114 /********************** TODO: UI stuff *****************************/
2115
2116 // these methods have been copied, they still need to be cleaned up
2117
2118 /****************** tabs ***************************************************/
2119
2120 // basic tab interactions:
2121
2122 // it is assumed that tabcontrol already knows about the tab
2123 protected void addTab(Tab tab) {
2124 mUi.addTab(tab);
2125 }
2126
2127 protected void removeTab(Tab tab) {
2128 mUi.removeTab(tab);
2129 mTabControl.removeTab(tab);
2130 }
2131
Michael Kolbf2055602011-04-09 17:20:03 -07002132 @Override
2133 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002134 // monkey protection against delayed start
2135 if (tab != null) {
2136 mTabControl.setCurrentTab(tab);
2137 // the tab is guaranteed to have a webview after setCurrentTab
2138 mUi.setActiveTab(tab);
2139 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002140 }
2141
2142 protected void closeEmptyChildTab() {
2143 Tab current = mTabControl.getCurrentTab();
2144 if (current != null
2145 && current.getWebView().copyBackForwardList().getSize() == 0) {
2146 Tab parent = current.getParentTab();
2147 if (parent != null) {
2148 switchToTab(mTabControl.getTabIndex(parent));
2149 closeTab(current);
2150 }
2151 }
2152 }
2153
2154 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002155 // Dismiss the subwindow if applicable.
2156 dismissSubWindow(appTab);
2157 // Since we might kill the WebView, remove it from the
2158 // content view first.
2159 mUi.detachTab(appTab);
2160 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002161 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002162 // TODO: analyze why the remove and add are necessary
2163 mUi.attachTab(appTab);
2164 if (mTabControl.getCurrentTab() != appTab) {
2165 switchToTab(mTabControl.getTabIndex(appTab));
John Reck30c714c2010-12-16 17:30:34 -08002166 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002167 } else {
2168 // If the tab was the current tab, we have to attach
2169 // it to the view system again.
2170 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002171 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002172 }
2173 }
2174
2175 // Remove the sub window if it exists. Also called by TabControl when the
2176 // user clicks the 'X' to dismiss a sub window.
2177 public void dismissSubWindow(Tab tab) {
2178 removeSubWindow(tab);
2179 // dismiss the subwindow. This will destroy the WebView.
2180 tab.dismissSubWindow();
2181 getCurrentTopWebView().requestFocus();
2182 }
2183
2184 @Override
2185 public void removeSubWindow(Tab t) {
2186 if (t.getSubWebView() != null) {
2187 mUi.removeSubWindow(t.getSubViewContainer());
2188 }
2189 }
2190
2191 @Override
2192 public void attachSubWindow(Tab tab) {
2193 if (tab.getSubWebView() != null) {
2194 mUi.attachSubWindow(tab.getSubViewContainer());
2195 getCurrentTopWebView().requestFocus();
2196 }
2197 }
2198
Michael Kolb843510f2010-12-09 10:51:49 -08002199 @Override
2200 public Tab openTabToHomePage() {
2201 // check for max tabs
2202 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002203 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2204 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002205 } else {
2206 mUi.showMaxTabsWarning();
2207 return null;
2208 }
2209 }
2210
Michael Kolb18eb3772010-12-10 14:29:51 -08002211 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2212 if (mSettings.openInBackground() && !forceForeground) {
2213 Tab tab = mTabControl.createNewTab(false, null, null,
2214 (parent != null) && parent.isPrivateBrowsingEnabled());
2215 if (tab != null) {
2216 addTab(tab);
2217 WebView view = tab.getWebView();
2218 loadUrl(view, url);
2219 }
2220 return tab;
2221 } else {
2222 return openTabAndShow(parent, new UrlData(url), false, null);
2223 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002224 }
2225
2226 // 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);
Michael Kolba4261fd2011-05-05 11:27:37 -07002264 loadUrlDataIn(tab, new UrlData(INCOGNITO_URI));
2265 return tab;
2266 } else {
2267 mUi.showMaxTabsWarning();
2268 return null;
2269 }
2270 }
2271
2272 @Override
2273 public Tab createNewTab(String url, boolean incognito) {
2274 if (mTabControl.canCreateNewTab()) {
2275 Tab tab = mTabControl.createNewTab(false, null, null, incognito);
2276 WebView w = tab.getWebView();
2277 addTab(tab);
2278 loadUrl(w, (incognito ? INCOGNITO_URI : url));
Michael Kolb8233fac2010-10-26 16:08:53 -07002279 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002280 } else {
2281 mUi.showMaxTabsWarning();
2282 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002283 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002284 }
2285
2286 /**
2287 * @param index Index of the tab to change to, as defined by
2288 * mTabControl.getTabIndex(Tab t).
2289 * @return boolean True if we successfully switched to a different tab. If
2290 * the indexth tab is null, or if that tab is the same as
2291 * the current one, return false.
2292 */
2293 @Override
2294 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002295 // hide combo view if open
2296 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002297 Tab tab = mTabControl.getTab(index);
2298 Tab currentTab = mTabControl.getCurrentTab();
2299 if (tab == null || tab == currentTab) {
2300 return false;
2301 }
2302 setActiveTab(tab);
2303 return true;
2304 }
2305
2306 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002307 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002308 // hide combo view if open
2309 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002310 final Tab current = mTabControl.getCurrentTab();
2311 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002312 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002313 return;
2314 }
2315 final Tab parent = current.getParentTab();
2316 int indexToShow = -1;
2317 if (parent != null) {
2318 indexToShow = mTabControl.getTabIndex(parent);
2319 } else {
2320 final int currentIndex = mTabControl.getCurrentIndex();
2321 // Try to move to the tab to the right
2322 indexToShow = currentIndex + 1;
2323 if (indexToShow > mTabControl.getTabCount() - 1) {
2324 // Try to move to the tab to the left
2325 indexToShow = currentIndex - 1;
2326 }
2327 }
2328 if (switchToTab(indexToShow)) {
2329 // Close window
2330 closeTab(current);
2331 }
2332 }
2333
2334 /**
2335 * Close the tab, remove its associated title bar, and adjust mTabControl's
2336 * current tab to a valid value.
2337 */
2338 @Override
2339 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002340 // hide combo view if open
2341 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002342 int currentIndex = mTabControl.getCurrentIndex();
2343 int removeIndex = mTabControl.getTabIndex(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002344 Tab newtab = mTabControl.getTab(currentIndex);
2345 setActiveTab(newtab);
Michael Kolb2d59c322011-01-25 13:18:55 -08002346 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002347 }
2348
2349 /**************** TODO: Url loading clean up *******************************/
2350
2351 // Called when loading from context menu or LOAD_URL message
2352 protected void loadUrlFromContext(WebView view, String url) {
2353 // In case the user enters nothing.
2354 if (url != null && url.length() != 0 && view != null) {
2355 url = UrlUtils.smartUrlFilter(url);
2356 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2357 loadUrl(view, url);
2358 }
2359 }
2360 }
2361
2362 /**
2363 * Load the URL into the given WebView and update the title bar
2364 * to reflect the new load. Call this instead of WebView.loadUrl
2365 * directly.
2366 * @param view The WebView used to load url.
2367 * @param url The URL to load.
2368 */
2369 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002370 view.loadUrl(url);
2371 }
2372
2373 /**
2374 * Load UrlData into a Tab and update the title bar to reflect the new
2375 * load. Call this instead of UrlData.loadIn directly.
2376 * @param t The Tab used to load.
2377 * @param data The UrlData being loaded.
2378 */
2379 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002380 data.loadIn(t);
2381 }
2382
John Reck30c714c2010-12-16 17:30:34 -08002383 @Override
2384 public void onUserCanceledSsl(Tab tab) {
2385 WebView web = tab.getWebView();
2386 // TODO: Figure out the "right" behavior
2387 if (web.canGoBack()) {
2388 web.goBack();
2389 } else {
2390 web.loadUrl(mSettings.getHomePage());
2391 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002392 }
2393
2394 void goBackOnePageOrQuit() {
2395 Tab current = mTabControl.getCurrentTab();
2396 if (current == null) {
2397 /*
2398 * Instead of finishing the activity, simply push this to the back
2399 * of the stack and let ActivityManager to choose the foreground
2400 * activity. As BrowserActivity is singleTask, it will be always the
2401 * root of the task. So we can use either true or false for
2402 * moveTaskToBack().
2403 */
2404 mActivity.moveTaskToBack(true);
2405 return;
2406 }
2407 WebView w = current.getWebView();
2408 if (w.canGoBack()) {
2409 w.goBack();
2410 } else {
2411 // Check to see if we are closing a window that was created by
2412 // another window. If so, we switch back to that window.
2413 Tab parent = current.getParentTab();
2414 if (parent != null) {
2415 switchToTab(mTabControl.getTabIndex(parent));
2416 // Now we close the other tab
2417 closeTab(current);
2418 } else {
2419 if (current.closeOnExit()) {
Patrick Scottfc1518a2011-02-28 13:57:03 -05002420 // This will finish the activity if there is only one tab
2421 // open or it will switch to the next available tab if
2422 // available.
Michael Kolb96683f72011-02-15 14:24:35 -08002423 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002424 }
2425 /*
2426 * Instead of finishing the activity, simply push this to the back
2427 * of the stack and let ActivityManager to choose the foreground
2428 * activity. As BrowserActivity is singleTask, it will be always the
2429 * root of the task. So we can use either true or false for
2430 * moveTaskToBack().
2431 */
2432 mActivity.moveTaskToBack(true);
2433 }
2434 }
2435 }
2436
2437 /**
2438 * Feed the previously stored results strings to the BrowserProvider so that
2439 * the SearchDialog will show them instead of the standard searches.
2440 * @param result String to show on the editable line of the SearchDialog.
2441 */
2442 @Override
2443 public void showVoiceSearchResults(String result) {
2444 ContentProviderClient client = mActivity.getContentResolver()
2445 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2446 ContentProvider prov = client.getLocalContentProvider();
2447 BrowserProvider bp = (BrowserProvider) prov;
2448 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2449 client.release();
2450
2451 Bundle bundle = createGoogleSearchSourceBundle(
2452 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2453 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2454 startSearch(result, false, bundle, false);
2455 }
2456
2457 private void startSearch(String initialQuery, boolean selectInitialQuery,
2458 Bundle appSearchData, boolean globalSearch) {
2459 if (appSearchData == null) {
2460 appSearchData = createGoogleSearchSourceBundle(
2461 GOOGLE_SEARCH_SOURCE_TYPE);
2462 }
2463
2464 SearchEngine searchEngine = mSettings.getSearchEngine();
2465 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2466 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2467 }
2468 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2469 globalSearch);
2470 }
2471
2472 private Bundle createGoogleSearchSourceBundle(String source) {
2473 Bundle bundle = new Bundle();
2474 bundle.putString(Search.SOURCE, source);
2475 return bundle;
2476 }
2477
2478 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002479 * helper method for key handler
2480 * returns the current tab if it can't advance
2481 */
2482 private int getNextTabIndex() {
2483 return Math.min(mTabControl.getTabCount() - 1,
2484 mTabControl.getCurrentIndex() + 1);
2485 }
2486
2487 /**
2488 * helper method for key handler
2489 * returns the current tab if it can't advance
2490 */
2491 private int getPrevTabIndex() {
2492 return Math.max(0, mTabControl.getCurrentIndex() - 1);
2493 }
2494
2495 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002496 * handle key events in browser
2497 *
2498 * @param keyCode
2499 * @param event
2500 * @return true if handled, false to pass to super
2501 */
2502 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002503 boolean noModifiers = event.hasNoModifiers();
2504
Michael Kolb8233fac2010-10-26 16:08:53 -07002505 // Even if MENU is already held down, we need to call to super to open
2506 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002507 if (!noModifiers
2508 && ((KeyEvent.KEYCODE_MENU == keyCode)
2509 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2510 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002511 mMenuIsDown = true;
2512 return false;
2513 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002514
Cary Clark8ff8c662010-12-29 15:03:05 -05002515 WebView webView = getCurrentTopWebView();
2516 if (webView == null) return false;
2517
Cary Clark160bbb92011-01-10 11:17:07 -05002518 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2519 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002520
Michael Kolb8233fac2010-10-26 16:08:53 -07002521 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002522 case KeyEvent.KEYCODE_TAB:
2523 if (event.isCtrlPressed()) {
2524 if (event.isShiftPressed()) {
2525 // prev tab
2526 switchToTab(getPrevTabIndex());
2527 } else {
2528 // next tab
2529 switchToTab(getNextTabIndex());
2530 }
2531 return true;
2532 }
2533 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002534 case KeyEvent.KEYCODE_SPACE:
2535 // WebView/WebTextView handle the keys in the KeyDown. As
2536 // the Activity's shortcut keys are only handled when WebView
2537 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002538 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002539 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002540 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002541 pageDown();
2542 }
2543 return true;
2544 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002545 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002546 event.startTracking();
2547 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002548 case KeyEvent.KEYCODE_DPAD_LEFT:
2549 if (ctrl) {
2550 webView.goBack();
2551 return true;
2552 }
2553 break;
2554 case KeyEvent.KEYCODE_DPAD_RIGHT:
2555 if (ctrl) {
2556 webView.goForward();
2557 return true;
2558 }
2559 break;
2560 case KeyEvent.KEYCODE_A:
2561 if (ctrl) {
2562 webView.selectAll();
2563 return true;
2564 }
2565 break;
Michael Kolba4183062011-01-16 10:43:21 -08002566// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002567 case KeyEvent.KEYCODE_C:
2568 if (ctrl) {
2569 webView.copySelection();
2570 return true;
2571 }
2572 break;
Michael Kolba4183062011-01-16 10:43:21 -08002573// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002574// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002575// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002576// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002577// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002578// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002579// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002580// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002581// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002582// case KeyEvent.KEYCODE_M: // unused
2583// case KeyEvent.KEYCODE_N: // in Chrome: new window
2584// case KeyEvent.KEYCODE_O: // in Chrome: open file
2585// case KeyEvent.KEYCODE_P: // in Chrome: print page
2586// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002587// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002588// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2589 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002590 // we can't use the ctrl/shift flags, they check for
2591 // exclusive use of a modifier
2592 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002593 if (event.isShiftPressed()) {
2594 openIncognitoTab();
2595 } else {
2596 openTabToHomePage();
2597 }
2598 return true;
2599 }
2600 break;
2601// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2602// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb1a2eba42011-03-16 16:42:49 -07002603 case KeyEvent.KEYCODE_W: // in Chrome: close tab
2604 if (ctrl) {
2605 closeCurrentTab();
2606 return true;
2607 }
2608 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002609// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2610// case KeyEvent.KEYCODE_Y: // unused
2611// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002612 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002613 // it is a regular key and webview is not null
2614 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002615 }
2616
John Recke6bf4ab2011-02-24 15:48:05 -08002617 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2618 switch(keyCode) {
2619 case KeyEvent.KEYCODE_BACK:
2620 if (mUi.showsWeb()) {
2621 bookmarksOrHistoryPicker(true);
2622 return true;
2623 }
2624 break;
2625 }
2626 return false;
2627 }
2628
Michael Kolb8233fac2010-10-26 16:08:53 -07002629 boolean onKeyUp(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002630 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002631 switch(keyCode) {
2632 case KeyEvent.KEYCODE_MENU:
2633 mMenuIsDown = false;
2634 break;
2635 case KeyEvent.KEYCODE_BACK:
2636 if (event.isTracking() && !event.isCanceled()) {
2637 onBackKey();
2638 return true;
2639 }
2640 break;
2641 }
2642 return false;
2643 }
2644
2645 public boolean isMenuDown() {
2646 return mMenuIsDown;
2647 }
2648
Ben Murdoch8029a772010-11-16 11:58:21 +00002649 public void setupAutoFill(Message message) {
2650 // Open the settings activity at the AutoFill profile fragment so that
2651 // the user can create a new profile. When they return, we will dispatch
2652 // the message so that we can autofill the form using their new profile.
2653 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2654 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2655 AutoFillSettingsFragment.class.getName());
2656 mAutoFillSetupMessage = message;
2657 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2658 }
John Reckb3417f02011-01-14 11:01:05 -08002659
2660 @Override
2661 public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
2662 mOptionsMenuHandler = handler;
2663 }
2664
2665 @Override
2666 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
2667 if (mOptionsMenuHandler == handler) {
2668 mOptionsMenuHandler = null;
2669 }
2670 }
2671
Narayan Kamath5119edd2011-02-23 15:49:17 +00002672 @Override
2673 public void registerDropdownChangeListener(DropdownChangeListener d) {
2674 mUi.registerDropdownChangeListener(d);
2675 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002676}