blob: 2a7e8eba2dee721715cad6e063b342d129133c5d [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.text.TextUtils;
60import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080061import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070062import android.view.ActionMode;
63import android.view.ContextMenu;
64import android.view.ContextMenu.ContextMenuInfo;
65import android.view.Gravity;
66import android.view.KeyEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070067import android.view.Menu;
68import android.view.MenuInflater;
69import android.view.MenuItem;
70import android.view.MenuItem.OnMenuItemClickListener;
71import android.view.View;
72import android.webkit.CookieManager;
73import android.webkit.CookieSyncManager;
74import android.webkit.HttpAuthHandler;
75import android.webkit.SslErrorHandler;
76import android.webkit.ValueCallback;
77import android.webkit.WebChromeClient;
78import android.webkit.WebIconDatabase;
79import android.webkit.WebSettings;
80import android.webkit.WebView;
Leon Scrogginsac993842011-02-02 12:54:07 -050081import android.widget.Toast;
Michael Kolb8233fac2010-10-26 16:08:53 -070082
83import java.io.ByteArrayOutputStream;
84import java.io.File;
85import java.net.URLEncoder;
86import java.util.Calendar;
87import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -080088import java.util.List;
Michael Kolb8233fac2010-10-26 16:08:53 -070089
90/**
91 * Controller for browser
92 */
93public class Controller
94 implements WebViewController, UiController {
95
96 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -080097 private static final String SEND_APP_ID_EXTRA =
98 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
Michael Kolba4261fd2011-05-05 11:27:37 -070099 private static final String INCOGNITO_URI = "browser:incognito";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800100
Michael Kolb8233fac2010-10-26 16:08:53 -0700101
102 // public message ids
103 public final static int LOAD_URL = 1001;
104 public final static int STOP_LOAD = 1002;
105
106 // Message Ids
107 private static final int FOCUS_NODE_HREF = 102;
108 private static final int RELEASE_WAKELOCK = 107;
109
110 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
111
112 private static final int OPEN_BOOKMARKS = 201;
113
114 private static final int EMPTY_MENU = -1;
115
Michael Kolb8233fac2010-10-26 16:08:53 -0700116 // activity requestCode
117 final static int PREFERENCES_PAGE = 3;
118 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000119 final static int AUTOFILL_SETUP = 5;
120
Michael Kolb8233fac2010-10-26 16:08:53 -0700121 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
122
123 // As the ids are dynamically created, we can't guarantee that they will
124 // be in sequence, so this static array maps ids to a window number.
125 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
126 { R.id.window_one_menu_id, R.id.window_two_menu_id,
127 R.id.window_three_menu_id, R.id.window_four_menu_id,
128 R.id.window_five_menu_id, R.id.window_six_menu_id,
129 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
130
131 // "source" parameter for Google search through search key
132 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
133 // "source" parameter for Google search through simplily type
134 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
135
Guang Zhu9e78f512011-05-04 11:45:11 -0700136 // "no-crash-recovery" parameter in intetnt to suppress crash recovery
137 final static String NO_CRASH_RECOVERY = "no-crash-recovery";
138
Michael Kolb8233fac2010-10-26 16:08:53 -0700139 private Activity mActivity;
140 private UI mUi;
141 private TabControl mTabControl;
142 private BrowserSettings mSettings;
143 private WebViewFactory mFactory;
John Reckb3417f02011-01-14 11:01:05 -0800144 private OptionsMenuHandler mOptionsMenuHandler = null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700145
146 private WakeLock mWakeLock;
147
148 private UrlHandler mUrlHandler;
149 private UploadHandler mUploadHandler;
150 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700151 private PageDialogsHandler mPageDialogsHandler;
152 private NetworkStateHandler mNetworkHandler;
153
Ben Murdoch8029a772010-11-16 11:58:21 +0000154 private Message mAutoFillSetupMessage;
155
Michael Kolb8233fac2010-10-26 16:08:53 -0700156 private boolean mShouldShowErrorConsole;
157
158 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
159
160 // FIXME, temp address onPrepareMenu performance problem.
161 // When we move everything out of view, we should rewrite this.
162 private int mCurrentMenuState = 0;
163 private int mMenuState = R.id.MAIN_MENU;
164 private int mOldMenuState = EMPTY_MENU;
165 private Menu mCachedMenu;
166
Michael Kolb8233fac2010-10-26 16:08:53 -0700167 private boolean mMenuIsDown;
168
169 // For select and find, we keep track of the ActionMode so that
170 // finish() can be called as desired.
171 private ActionMode mActionMode;
172
173 /**
174 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
175 * of whether the configuration has changed. The first onMenuOpened call
176 * after a configuration change is simply a reopening of the same menu
177 * (i.e. mIconView did not change).
178 */
179 private boolean mConfigChanged;
180
181 /**
182 * Keeps track of whether the options menu is open. This is important in
183 * determining whether to show or hide the title bar overlay
184 */
185 private boolean mOptionsMenuOpen;
186
187 /**
188 * Whether or not the options menu is in its bigger, popup menu form. When
189 * true, we want the title bar overlay to be gone. When false, we do not.
190 * Only meaningful if mOptionsMenuOpen is true.
191 */
192 private boolean mExtendedMenuOpen;
193
194 private boolean mInLoad;
195
196 private boolean mActivityPaused = true;
197 private boolean mLoadStopped;
198
199 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500200 // Checks to see when the bookmarks database has changed, and updates the
201 // Tabs' notion of whether they represent bookmarked sites.
202 private ContentObserver mBookmarksObserver;
John Reck0ebd3ac2010-12-09 11:14:04 -0800203 private DataController mDataController;
John Reck847b5322011-04-14 17:02:18 -0700204 private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700205
206 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
207 @Override
208 public Void doInBackground(File... files) {
209 if (files != null) {
210 for (File f : files) {
211 if (!f.delete()) {
212 Log.e(LOGTAG, f.getPath() + " was not deleted");
213 }
214 }
215 }
216 return null;
217 }
218 }
219
220 public Controller(Activity browser) {
221 mActivity = browser;
222 mSettings = BrowserSettings.getInstance();
John Reck0ebd3ac2010-12-09 11:14:04 -0800223 mDataController = DataController.getInstance(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700224 mTabControl = new TabControl(this);
225 mSettings.setController(this);
John Reck847b5322011-04-14 17:02:18 -0700226 mCrashRecoveryHandler = new CrashRecoveryHandler(this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700227
228 mUrlHandler = new UrlHandler(this);
229 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700230 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
231
232 PowerManager pm = (PowerManager) mActivity
233 .getSystemService(Context.POWER_SERVICE);
234 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
235
236 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500237 mBookmarksObserver = new ContentObserver(mHandler) {
238 @Override
239 public void onChange(boolean selfChange) {
240 int size = mTabControl.getTabCount();
241 for (int i = 0; i < size; i++) {
242 mTabControl.getTab(i).updateBookmarkedStatus();
243 }
244 }
245
246 };
247 browser.getContentResolver().registerContentObserver(
248 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700249
250 mNetworkHandler = new NetworkStateHandler(mActivity, this);
251 // Start watching the default geolocation permissions
252 mSystemAllowGeolocationOrigins =
253 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
254 mSystemAllowGeolocationOrigins.start();
255
256 retainIconsOnStartup();
257 }
258
Patrick Scott7d50a932011-02-04 09:27:26 -0500259 void start(final Bundle icicle, final Intent intent) {
Guang Zhu9e78f512011-05-04 11:45:11 -0700260 boolean noCrashRecovery = intent.getBooleanExtra(NO_CRASH_RECOVERY, false);
261 if (icicle != null || noCrashRecovery) {
John Reck847b5322011-04-14 17:02:18 -0700262 mCrashRecoveryHandler.clearState();
263 doStart(icicle, intent);
264 } else {
265 mCrashRecoveryHandler.startRecovery(intent);
266 }
267 }
268
269 void doStart(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700270 // Unless the last browser usage was within 24 hours, destroy any
271 // remaining incognito tabs.
272
273 Calendar lastActiveDate = icicle != null ?
274 (Calendar) icicle.getSerializable("lastActiveDate") : null;
275 Calendar today = Calendar.getInstance();
276 Calendar yesterday = Calendar.getInstance();
277 yesterday.add(Calendar.DATE, -1);
278
Patrick Scott7d50a932011-02-04 09:27:26 -0500279 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700280 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800281 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700282
Patrick Scott7d50a932011-02-04 09:27:26 -0500283 // Find out if we will restore any state and remember the tab.
Michael Kolbc831b632011-05-11 09:30:34 -0700284 final long currentTabId =
Patrick Scott7d50a932011-02-04 09:27:26 -0500285 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000286
Michael Kolbc831b632011-05-11 09:30:34 -0700287 if (currentTabId == -1) {
Patrick Scott7d50a932011-02-04 09:27:26 -0500288 // Not able to restore so we go ahead and clear session cookies. We
289 // must do this before trying to login the user as we don't want to
290 // clear any session cookies set during login.
291 CookieManager.getInstance().removeSessionCookie();
292 }
293
Patrick Scottd43e75a2011-03-14 14:47:23 -0400294 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500295 new Runnable() {
296 @Override public void run() {
Michael Kolbc831b632011-05-11 09:30:34 -0700297 onPreloginFinished(icicle, intent, currentTabId, restoreIncognitoTabs);
Patrick Scott7d50a932011-02-04 09:27:26 -0500298 }
299 });
300 }
301
Michael Kolbc831b632011-05-11 09:30:34 -0700302 private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId,
Patrick Scott7d50a932011-02-04 09:27:26 -0500303 boolean restoreIncognitoTabs) {
Michael Kolbc831b632011-05-11 09:30:34 -0700304 if (currentTabId == -1) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700305 final Bundle extra = intent.getExtras();
306 // Create an initial tab.
307 // If the intent is ACTION_VIEW and data is not null, the Browser is
308 // invoked to view the content by another application. In this case,
309 // the tab will be close when exit.
310 UrlData urlData = mIntentHandler.getUrlDataFromIntent(intent);
Michael Kolb7bcafde2011-05-09 13:55:59 -0700311 Tab t = null;
312 if (urlData.isEmpty()) {
313 t = openTabToHomePage();
314 } else {
315 t = openTab(urlData);
316 }
317 if (t != null) {
318 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
319 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700320 WebView webView = t.getWebView();
321 if (extra != null) {
322 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
323 if (scale > 0 && scale <= 1000) {
324 webView.setInitialScale(scale);
325 }
326 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700327 } else {
Michael Kolbc831b632011-05-11 09:30:34 -0700328 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
Patrick Scott7d50a932011-02-04 09:27:26 -0500329 mUi.needsRestoreAllTabs());
Michael Kolb1bf23132010-11-19 12:55:12 -0800330 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700331 // TabControl.restoreState() will create a new tab even if
332 // restoring the state fails.
333 setActiveTab(mTabControl.getCurrentTab());
334 }
335 // clear up the thumbnail directory, which is no longer used;
336 // ideally this should only be run once after an upgrade from
337 // a previous version of the browser
338 new ClearThumbnails().execute(mTabControl.getThumbnailDir()
339 .listFiles());
340 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700341 String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb8233fac2010-10-26 16:08:53 -0700342 if (jsFlags.trim().length() != 0) {
343 getCurrentWebView().setJsFlags(jsFlags);
344 }
John Reck439c9a52010-12-14 10:04:39 -0800345 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
346 bookmarksOrHistoryPicker(false);
347 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700348 }
349
350 void setWebViewFactory(WebViewFactory factory) {
351 mFactory = factory;
352 }
353
Michael Kolb1514bb72010-11-22 09:11:48 -0800354 @Override
355 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700356 return mFactory;
357 }
358
359 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800360 public void onSetWebView(Tab tab, WebView view) {
361 mUi.onSetWebView(tab, view);
362 }
363
364 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800365 public void createSubWindow(Tab tab) {
366 endActionMode();
367 WebView mainView = tab.getWebView();
368 WebView subView = mFactory.createWebView((mainView == null)
369 ? false
370 : mainView.isPrivateBrowsingEnabled());
371 mUi.createSubWindow(tab, subView);
372 }
373
374 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700375 public Activity getActivity() {
376 return mActivity;
377 }
378
379 void setUi(UI ui) {
380 mUi = ui;
381 }
382
383 BrowserSettings getSettings() {
384 return mSettings;
385 }
386
387 IntentHandler getIntentHandler() {
388 return mIntentHandler;
389 }
390
391 @Override
392 public UI getUi() {
393 return mUi;
394 }
395
396 int getMaxTabs() {
397 return mActivity.getResources().getInteger(R.integer.max_tabs);
398 }
399
400 @Override
401 public TabControl getTabControl() {
402 return mTabControl;
403 }
404
Michael Kolb1bf23132010-11-19 12:55:12 -0800405 @Override
406 public List<Tab> getTabs() {
407 return mTabControl.getTabs();
408 }
409
Michael Kolb8233fac2010-10-26 16:08:53 -0700410 // Open the icon database and retain all the icons for visited sites.
Ben Murdoch9446b932010-11-25 16:20:14 +0000411 // This is done on a background thread so as not to stall startup.
Michael Kolb8233fac2010-10-26 16:08:53 -0700412 private void retainIconsOnStartup() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000413 // WebIconDatabase needs to be retrieved on the UI thread so that if
414 // it has not been created successfully yet the Handler is started on the
415 // UI thread.
416 new RetainIconsOnStartupTask(WebIconDatabase.getInstance()).execute();
417 }
418
419 private class RetainIconsOnStartupTask extends AsyncTask<Void, Void, Void> {
420 private WebIconDatabase mDb;
421
422 public RetainIconsOnStartupTask(WebIconDatabase db) {
423 mDb = db;
424 }
425
John Recka00cbbd2010-12-16 12:38:19 -0800426 @Override
Ben Murdoch9446b932010-11-25 16:20:14 +0000427 protected Void doInBackground(Void... unused) {
428 mDb.open(mActivity.getDir("icons", 0).getPath());
429 Cursor c = null;
430 try {
431 c = Browser.getAllBookmarks(mActivity.getContentResolver());
432 if (c.moveToFirst()) {
433 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
434 do {
435 String url = c.getString(urlIndex);
436 mDb.retainIconForPageUrl(url);
437 } while (c.moveToNext());
438 }
439 } catch (IllegalStateException e) {
440 Log.e(LOGTAG, "retainIconsOnStartup", e);
441 } finally {
442 if (c != null) c.close();
Michael Kolb8233fac2010-10-26 16:08:53 -0700443 }
Ben Murdoch9446b932010-11-25 16:20:14 +0000444
445 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700446 }
447 }
448
449 private void startHandler() {
450 mHandler = new Handler() {
451
452 @Override
453 public void handleMessage(Message msg) {
454 switch (msg.what) {
455 case OPEN_BOOKMARKS:
456 bookmarksOrHistoryPicker(false);
457 break;
458 case FOCUS_NODE_HREF:
459 {
460 String url = (String) msg.getData().get("url");
461 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500462 String src = (String) msg.getData().get("src");
463 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700464 if (TextUtils.isEmpty(url)) {
465 break;
466 }
467 HashMap focusNodeMap = (HashMap) msg.obj;
468 WebView view = (WebView) focusNodeMap.get("webview");
469 // Only apply the action if the top window did not change.
470 if (getCurrentTopWebView() != view) {
471 break;
472 }
473 switch (msg.arg1) {
474 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -0700475 loadUrlFromContext(getCurrentTopWebView(), url);
476 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500477 case R.id.view_image_context_menu_id:
478 loadUrlFromContext(getCurrentTopWebView(), src);
479 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500480 case R.id.open_newtab_context_menu_id:
481 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb7bcafde2011-05-09 13:55:59 -0700482 final Tab newTab =
483 openTab(url,
484 (parent != null)
485 && parent.isPrivateBrowsingEnabled(),
486 !mSettings.openInBackground(),
487 true);
Leon Scroggins026f2542010-11-22 13:26:12 -0500488 if (newTab != null && newTab != parent) {
489 parent.addChildTab(newTab);
490 }
491 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700492 case R.id.copy_link_context_menu_id:
493 copy(url);
494 break;
495 case R.id.save_link_context_menu_id:
496 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500497 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000498 mActivity, url, null, null, null,
499 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700500 break;
501 }
502 break;
503 }
504
505 case LOAD_URL:
506 loadUrlFromContext(getCurrentTopWebView(), (String) msg.obj);
507 break;
508
509 case STOP_LOAD:
510 stopLoading();
511 break;
512
513 case RELEASE_WAKELOCK:
514 if (mWakeLock.isHeld()) {
515 mWakeLock.release();
516 // if we reach here, Browser should be still in the
517 // background loading after WAKELOCK_TIMEOUT (5-min).
518 // To avoid burning the battery, stop loading.
519 mTabControl.stopAllLoading();
520 }
521 break;
522
523 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800524 Tab tab = (Tab) msg.obj;
525 if (tab != null) {
526 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700527 }
528 break;
529 }
530 }
531 };
532
533 }
534
Michael Kolbba99c5d2010-11-29 14:57:41 -0800535 @Override
536 public void shareCurrentPage() {
537 shareCurrentPage(mTabControl.getCurrentTab());
538 }
539
540 private void shareCurrentPage(Tab tab) {
541 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800542 sharePage(mActivity, tab.getTitle(),
543 tab.getUrl(), tab.getFavicon(),
544 createScreenshot(tab.getWebView(),
545 getDesiredThumbnailWidth(mActivity),
546 getDesiredThumbnailHeight(mActivity)));
547 }
548 }
549
Michael Kolb8233fac2010-10-26 16:08:53 -0700550 /**
551 * Share a page, providing the title, url, favicon, and a screenshot. Uses
552 * an {@link Intent} to launch the Activity chooser.
553 * @param c Context used to launch a new Activity.
554 * @param title Title of the page. Stored in the Intent with
555 * {@link Intent#EXTRA_SUBJECT}
556 * @param url URL of the page. Stored in the Intent with
557 * {@link Intent#EXTRA_TEXT}
558 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
559 * with {@link Browser#EXTRA_SHARE_FAVICON}
560 * @param screenshot Bitmap of a screenshot of the page. Stored in the
561 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
562 */
563 static final void sharePage(Context c, String title, String url,
564 Bitmap favicon, Bitmap screenshot) {
565 Intent send = new Intent(Intent.ACTION_SEND);
566 send.setType("text/plain");
567 send.putExtra(Intent.EXTRA_TEXT, url);
568 send.putExtra(Intent.EXTRA_SUBJECT, title);
569 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
570 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
571 try {
572 c.startActivity(Intent.createChooser(send, c.getString(
573 R.string.choosertitle_sharevia)));
574 } catch(android.content.ActivityNotFoundException ex) {
575 // if no app handles it, do nothing
576 }
577 }
578
579 private void copy(CharSequence text) {
580 ClipboardManager cm = (ClipboardManager) mActivity
581 .getSystemService(Context.CLIPBOARD_SERVICE);
582 cm.setText(text);
583 }
584
585 // lifecycle
586
587 protected void onConfgurationChanged(Configuration config) {
588 mConfigChanged = true;
589 if (mPageDialogsHandler != null) {
590 mPageDialogsHandler.onConfigurationChanged(config);
591 }
592 mUi.onConfigurationChanged(config);
593 }
594
595 @Override
596 public void handleNewIntent(Intent intent) {
597 mIntentHandler.onNewIntent(intent);
598 }
599
600 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800601 if (mUi.isCustomViewShowing()) {
602 hideCustomView();
603 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700604 if (mActivityPaused) {
605 Log.e(LOGTAG, "BrowserActivity is already paused.");
606 return;
607 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700608 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800609 Tab tab = mTabControl.getCurrentTab();
610 if (tab != null) {
611 tab.pause();
612 if (!pauseWebViewTimers(tab)) {
613 mWakeLock.acquire();
614 mHandler.sendMessageDelayed(mHandler
615 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
616 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700617 }
618 mUi.onPause();
619 mNetworkHandler.onPause();
620
621 WebView.disablePlatformNotifications();
John Reck847b5322011-04-14 17:02:18 -0700622 mCrashRecoveryHandler.clearState();
Michael Kolb8233fac2010-10-26 16:08:53 -0700623 }
624
625 void onSaveInstanceState(Bundle outState) {
626 // the default implementation requires each view to have an id. As the
627 // browser handles the state itself and it doesn't use id for the views,
628 // don't call the default implementation. Otherwise it will trigger the
629 // warning like this, "couldn't save which view has focus because the
630 // focused view XXX has no id".
631
632 // Save all the tabs
633 mTabControl.saveState(outState);
634 // Save time so that we know how old incognito tabs (if any) are.
635 outState.putSerializable("lastActiveDate", Calendar.getInstance());
636 }
637
638 void onResume() {
639 if (!mActivityPaused) {
640 Log.e(LOGTAG, "BrowserActivity is already resumed.");
641 return;
642 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700643 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800644 Tab current = mTabControl.getCurrentTab();
645 if (current != null) {
646 current.resume();
647 resumeWebViewTimers(current);
648 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700649 if (mWakeLock.isHeld()) {
650 mHandler.removeMessages(RELEASE_WAKELOCK);
651 mWakeLock.release();
652 }
653 mUi.onResume();
654 mNetworkHandler.onResume();
655 WebView.enablePlatformNotifications();
656 }
657
Michael Kolb70976932010-11-30 11:34:01 -0800658 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800659 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800660 * @param tab guaranteed non-null
661 */
662 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700663 boolean inLoad = tab.inPageLoad();
664 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
665 CookieSyncManager.getInstance().startSync();
666 WebView w = tab.getWebView();
667 if (w != null) {
668 w.resumeTimers();
669 }
670 }
671 }
672
Michael Kolb70976932010-11-30 11:34:01 -0800673 /**
674 * Pause all WebView timers using the WebView of the given tab
675 * @param tab
676 * @return true if the timers are paused or tab is null
677 */
678 private boolean pauseWebViewTimers(Tab tab) {
679 if (tab == null) {
680 return true;
681 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700682 CookieSyncManager.getInstance().stopSync();
683 WebView w = getCurrentWebView();
684 if (w != null) {
685 w.pauseTimers();
686 }
687 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700688 }
Michael Kolb70976932010-11-30 11:34:01 -0800689 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700690 }
691
692 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800693 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700694 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
695 mUploadHandler = null;
696 }
697 if (mTabControl == null) return;
698 mUi.onDestroy();
699 // Remove the current tab and sub window
700 Tab t = mTabControl.getCurrentTab();
701 if (t != null) {
702 dismissSubWindow(t);
703 removeTab(t);
704 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500705 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700706 // Destroy all the tabs
707 mTabControl.destroy();
708 WebIconDatabase.getInstance().close();
709 // Stop watching the default geolocation permissions
710 mSystemAllowGeolocationOrigins.stop();
711 mSystemAllowGeolocationOrigins = null;
712 }
713
714 protected boolean isActivityPaused() {
715 return mActivityPaused;
716 }
717
718 protected void onLowMemory() {
719 mTabControl.freeMemory();
720 }
721
722 @Override
723 public boolean shouldShowErrorConsole() {
724 return mShouldShowErrorConsole;
725 }
726
727 protected void setShouldShowErrorConsole(boolean show) {
728 if (show == mShouldShowErrorConsole) {
729 // Nothing to do.
730 return;
731 }
732 mShouldShowErrorConsole = show;
733 Tab t = mTabControl.getCurrentTab();
734 if (t == null) {
735 // There is no current tab so we cannot toggle the error console
736 return;
737 }
738 mUi.setShouldShowErrorConsole(t, show);
739 }
740
741 @Override
742 public void stopLoading() {
743 mLoadStopped = true;
744 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700745 WebView w = getCurrentTopWebView();
746 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700747 mUi.onPageStopped(tab);
748 }
749
750 boolean didUserStopLoading() {
751 return mLoadStopped;
752 }
753
754 // WebViewController
755
756 @Override
John Reck324d4402011-01-11 16:56:42 -0800757 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700758
759 // We've started to load a new page. If there was a pending message
760 // to save a screenshot then we will now take the new page and save
761 // an incorrect screenshot. Therefore, remove any pending thumbnail
762 // messages from the queue.
763 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800764 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700765
766 // reset sync timer to avoid sync starts during loading a page
767 CookieSyncManager.getInstance().resetSync();
768
769 if (!mNetworkHandler.isNetworkUp()) {
770 view.setNetworkAvailable(false);
771 }
772
773 // when BrowserActivity just starts, onPageStarted may be called before
774 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
775 // to start the timer. As we won't switch tabs while an activity is in
776 // pause state, we can ensure calling resume and pause in pair.
777 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800778 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700779 }
780 mLoadStopped = false;
781 if (!mNetworkHandler.isNetworkUp()) {
782 mNetworkHandler.createAndShowNetworkDialog();
783 }
784 endActionMode();
785
John Reck30c714c2010-12-16 17:30:34 -0800786 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700787
John Reck324d4402011-01-11 16:56:42 -0800788 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700789 // update the bookmark database for favicon
790 maybeUpdateFavicon(tab, null, url, favicon);
791
792 Performance.tracePageStart(url);
793
794 // Performance probe
795 if (false) {
796 Performance.onPageStarted();
797 }
798
799 }
800
801 @Override
John Reck324d4402011-01-11 16:56:42 -0800802 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800803 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800804 if (!tab.isPrivateBrowsingEnabled()
805 && !TextUtils.isEmpty(tab.getUrl())) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700806 if (tab.inForeground() && !didUserStopLoading()
807 || !tab.inForeground()) {
808 // Only update the bookmark screenshot if the user did not
809 // cancel the load early.
810 mHandler.sendMessageDelayed(mHandler.obtainMessage(
John Reck34ef2672011-02-10 11:30:55 -0800811 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
Michael Kolb8233fac2010-10-26 16:08:53 -0700812 500);
813 }
814 }
815 // pause the WebView timer and release the wake lock if it is finished
816 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800817 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700818 if (mWakeLock.isHeld()) {
819 mHandler.removeMessages(RELEASE_WAKELOCK);
820 mWakeLock.release();
821 }
822 }
823 // Performance probe
824 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800825 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700826 }
827
828 Performance.tracePageFinished();
829 }
830
831 @Override
John Reck30c714c2010-12-16 17:30:34 -0800832 public void onProgressChanged(Tab tab) {
833 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700834
835 if (newProgress == 100) {
836 CookieSyncManager.getInstance().sync();
837 // onProgressChanged() may continue to be called after the main
838 // frame has finished loading, as any remaining sub frames continue
839 // to load. We'll only get called once though with newProgress as
840 // 100 when everything is loaded. (onPageFinished is called once
841 // when the main frame completes loading regardless of the state of
842 // any sub frames so calls to onProgressChanges may continue after
843 // onPageFinished has executed)
844 if (mInLoad) {
845 mInLoad = false;
846 updateInLoadMenuItems(mCachedMenu);
847 }
848 } else {
849 if (!mInLoad) {
850 // onPageFinished may have already been called but a subframe is
851 // still loading and updating the progress. Reset mInLoad and
852 // update the menu items.
853 mInLoad = true;
854 updateInLoadMenuItems(mCachedMenu);
855 }
856 }
John Reck30c714c2010-12-16 17:30:34 -0800857 mUi.onProgressChanged(tab);
858 }
859
860 @Override
861 public void onUpdatedLockIcon(Tab tab) {
862 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700863 }
864
865 @Override
866 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800867 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800868 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800869 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700870 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
871 return;
872 }
873 // Update the title in the history database if not in private browsing mode
874 if (!tab.isPrivateBrowsingEnabled()) {
John Reck0ebd3ac2010-12-09 11:14:04 -0800875 mDataController.updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700876 }
877 }
878
879 @Override
880 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800881 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700882 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
883 }
884
885 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800886 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
887 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700888 }
889
890 @Override
891 public boolean shouldOverrideKeyEvent(KeyEvent event) {
892 if (mMenuIsDown) {
893 // only check shortcut key when MENU is held
894 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
895 event);
896 } else {
897 return false;
898 }
899 }
900
901 @Override
902 public void onUnhandledKeyEvent(KeyEvent event) {
903 if (!isActivityPaused()) {
904 if (event.getAction() == KeyEvent.ACTION_DOWN) {
905 mActivity.onKeyDown(event.getKeyCode(), event);
906 } else {
907 mActivity.onKeyUp(event.getKeyCode(), event);
908 }
909 }
910 }
911
912 @Override
John Reck324d4402011-01-11 16:56:42 -0800913 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700914 // Don't save anything in private browsing mode
915 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800916 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700917
John Reck324d4402011-01-11 16:56:42 -0800918 if (TextUtils.isEmpty(url)
919 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700920 return;
921 }
John Reck0ebd3ac2010-12-09 11:14:04 -0800922 mDataController.updateVisitedHistory(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700923 WebIconDatabase.getInstance().retainIconForPageUrl(url);
John Reck847b5322011-04-14 17:02:18 -0700924 if (!mActivityPaused) {
925 // Since we clear the state in onPause, don't backup the current
926 // state if we are already paused
927 mCrashRecoveryHandler.backupState();
928 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700929 }
930
931 @Override
932 public void getVisitedHistory(final ValueCallback<String[]> callback) {
933 AsyncTask<Void, Void, String[]> task =
934 new AsyncTask<Void, Void, String[]>() {
935 @Override
936 public String[] doInBackground(Void... unused) {
937 return Browser.getVisitedHistory(mActivity.getContentResolver());
938 }
939 @Override
940 public void onPostExecute(String[] result) {
941 callback.onReceiveValue(result);
942 }
943 };
944 task.execute();
945 }
946
947 @Override
948 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
949 final HttpAuthHandler handler, final String host,
950 final String realm) {
951 String username = null;
952 String password = null;
953
954 boolean reuseHttpAuthUsernamePassword
955 = handler.useHttpAuthUsernamePassword();
956
957 if (reuseHttpAuthUsernamePassword && view != null) {
958 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
959 if (credentials != null && credentials.length == 2) {
960 username = credentials[0];
961 password = credentials[1];
962 }
963 }
964
965 if (username != null && password != null) {
966 handler.proceed(username, password);
967 } else {
968 if (tab.inForeground()) {
969 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
970 } else {
971 handler.cancel();
972 }
973 }
974 }
975
976 @Override
977 public void onDownloadStart(Tab tab, String url, String userAgent,
978 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000979 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -0500980 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000981 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
982 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700983 // This Tab was opened for the sole purpose of downloading a
984 // file. Remove it.
985 if (tab == mTabControl.getCurrentTab()) {
986 // In this case, the Tab is still on top.
987 goBackOnePageOrQuit();
988 } else {
989 // In this case, it is not.
990 closeTab(tab);
991 }
992 }
993 }
994
995 @Override
996 public Bitmap getDefaultVideoPoster() {
997 return mUi.getDefaultVideoPoster();
998 }
999
1000 @Override
1001 public View getVideoLoadingProgressView() {
1002 return mUi.getVideoLoadingProgressView();
1003 }
1004
1005 @Override
1006 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1007 SslError error) {
1008 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1009 }
1010
Patrick Scott92066772011-03-10 08:46:27 -05001011 @Override
1012 public void showAutoLogin(Tab tab) {
1013 assert tab.inForeground();
1014 // Update the title bar to show the auto-login request.
1015 mUi.showAutoLogin(tab);
1016 }
1017
1018 @Override
1019 public void hideAutoLogin(Tab tab) {
1020 assert tab.inForeground();
1021 mUi.hideAutoLogin(tab);
1022 }
1023
Michael Kolb8233fac2010-10-26 16:08:53 -07001024 // helper method
1025
1026 /*
1027 * Update the favorites icon if the private browsing isn't enabled and the
1028 * icon is valid.
1029 */
1030 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1031 final String url, Bitmap favicon) {
1032 if (favicon == null) {
1033 return;
1034 }
1035 if (!tab.isPrivateBrowsingEnabled()) {
1036 Bookmarks.updateFavicon(mActivity
1037 .getContentResolver(), originalUrl, url, favicon);
1038 }
1039 }
1040
Leon Scroggins4cd97792010-12-03 15:31:56 -05001041 @Override
1042 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001043 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001044 mUi.bookmarkedStatusHasChanged(tab);
1045 }
1046
Michael Kolb8233fac2010-10-26 16:08:53 -07001047 // end WebViewController
1048
1049 protected void pageUp() {
1050 getCurrentTopWebView().pageUp(false);
1051 }
1052
1053 protected void pageDown() {
1054 getCurrentTopWebView().pageDown(false);
1055 }
1056
1057 // callback from phone title bar
1058 public void editUrl() {
1059 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001060 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001061 }
1062
Michael Kolbcfa3af52010-12-14 10:36:11 -08001063 public void startVoiceSearch() {
1064 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1065 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1066 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1067 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1068 mActivity.getComponentName().flattenToString());
1069 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001070 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001071 mActivity.startActivity(intent);
1072 }
1073
Michael Kolb11d19782011-03-20 10:17:40 -07001074 @Override
1075 public void activateVoiceSearchMode(String title, List<String> results) {
1076 mUi.showVoiceTitleBar(title, results);
Michael Kolb8233fac2010-10-26 16:08:53 -07001077 }
1078
1079 public void revertVoiceSearchMode(Tab tab) {
1080 mUi.revertVoiceTitleBar(tab);
1081 }
1082
Michael Kolb736990c2011-03-20 10:01:20 -07001083 public boolean supportsVoiceSearch() {
John Reck35e9dd62011-04-25 09:01:54 -07001084 SearchEngine searchEngine = getSettings().getSearchEngine();
Michael Kolb736990c2011-03-20 10:01:20 -07001085 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1086 }
1087
Michael Kolb8233fac2010-10-26 16:08:53 -07001088 public void showCustomView(Tab tab, View view,
1089 WebChromeClient.CustomViewCallback callback) {
1090 if (tab.inForeground()) {
1091 if (mUi.isCustomViewShowing()) {
1092 callback.onCustomViewHidden();
1093 return;
1094 }
1095 mUi.showCustomView(view, callback);
1096 // Save the menu state and set it to empty while the custom
1097 // view is showing.
1098 mOldMenuState = mMenuState;
1099 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001100 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001101 }
1102 }
1103
1104 @Override
1105 public void hideCustomView() {
1106 if (mUi.isCustomViewShowing()) {
1107 mUi.onHideCustomView();
1108 // Reset the old menu state.
1109 mMenuState = mOldMenuState;
1110 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001111 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001112 }
1113 }
1114
1115 protected void onActivityResult(int requestCode, int resultCode,
1116 Intent intent) {
1117 if (getCurrentTopWebView() == null) return;
1118 switch (requestCode) {
1119 case PREFERENCES_PAGE:
1120 if (resultCode == Activity.RESULT_OK && intent != null) {
1121 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001122 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001123 mTabControl.removeParentChildRelationShips();
1124 }
1125 }
1126 break;
1127 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001128 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001129 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001130 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001131 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001132 case AUTOFILL_SETUP:
1133 // Determine whether a profile was actually set up or not
1134 // and if so, send the message back to the WebTextView to
1135 // fill the form with the new profile.
1136 if (getSettings().getAutoFillProfile() != null) {
1137 mAutoFillSetupMessage.sendToTarget();
1138 mAutoFillSetupMessage = null;
1139 }
1140 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001141 default:
1142 break;
1143 }
1144 getCurrentTopWebView().requestFocus();
1145 }
1146
1147 /**
1148 * Open the Go page.
1149 * @param startWithHistory If true, open starting on the history tab.
1150 * Otherwise, start with the bookmarks tab.
1151 */
1152 @Override
1153 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1154 if (mTabControl.getCurrentWebView() == null) {
1155 return;
1156 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001157 // clear action mode
1158 if (isInCustomActionMode()) {
1159 endActionMode();
1160 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001161 Bundle extras = new Bundle();
1162 // Disable opening in a new window if we have maxed out the windows
1163 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1164 !mTabControl.canCreateNewTab());
1165 mUi.showComboView(startWithHistory, extras);
1166 }
1167
1168 // combo view callbacks
1169
1170 /**
1171 * callback from ComboPage when clear history is requested
1172 */
1173 public void onRemoveParentChildRelationships() {
1174 mTabControl.removeParentChildRelationShips();
1175 }
1176
1177 /**
1178 * callback from ComboPage when bookmark/history selection
1179 */
1180 @Override
1181 public void onUrlSelected(String url, boolean newTab) {
1182 removeComboView();
1183 if (!TextUtils.isEmpty(url)) {
1184 if (newTab) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07001185 final Tab parent = mTabControl.getCurrentTab();
1186 openTab(url,
1187 (parent != null) && parent.isPrivateBrowsingEnabled(),
1188 !mSettings.openInBackground(),
1189 true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001190 } else {
1191 final Tab currentTab = mTabControl.getCurrentTab();
1192 dismissSubWindow(currentTab);
1193 loadUrl(getCurrentTopWebView(), url);
1194 }
1195 }
1196 }
1197
1198 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07001199 * dismiss the ComboPage
1200 */
1201 @Override
1202 public void removeComboView() {
1203 mUi.hideComboView();
1204 }
1205
1206 // active tabs page handling
1207
1208 protected void showActiveTabsPage() {
1209 mMenuState = EMPTY_MENU;
1210 mUi.showActiveTabsPage();
1211 }
1212
1213 /**
1214 * Remove the active tabs page.
1215 * @param needToAttach If true, the active tabs page did not attach a tab
1216 * to the content view, so we need to do that here.
1217 */
1218 @Override
1219 public void removeActiveTabsPage(boolean needToAttach) {
1220 mMenuState = R.id.MAIN_MENU;
1221 mUi.removeActiveTabsPage();
1222 if (needToAttach) {
1223 setActiveTab(mTabControl.getCurrentTab());
1224 }
1225 getCurrentTopWebView().requestFocus();
1226 }
1227
1228 // key handling
1229 protected void onBackKey() {
1230 if (!mUi.onBackKey()) {
1231 WebView subwindow = mTabControl.getCurrentSubWindow();
1232 if (subwindow != null) {
1233 if (subwindow.canGoBack()) {
1234 subwindow.goBack();
1235 } else {
1236 dismissSubWindow(mTabControl.getCurrentTab());
1237 }
1238 } else {
1239 goBackOnePageOrQuit();
1240 }
1241 }
1242 }
1243
1244 // menu handling and state
1245 // TODO: maybe put into separate handler
1246
1247 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckb3417f02011-01-14 11:01:05 -08001248 if (mOptionsMenuHandler != null) {
1249 return mOptionsMenuHandler.onCreateOptionsMenu(menu);
1250 }
1251
John Reckd73c5a22010-12-22 10:22:50 -08001252 if (mMenuState == EMPTY_MENU) {
1253 return false;
1254 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001255 MenuInflater inflater = mActivity.getMenuInflater();
1256 inflater.inflate(R.menu.browser, menu);
1257 updateInLoadMenuItems(menu);
1258 // hold on to the menu reference here; it is used by the page callbacks
1259 // to update the menu based on loading state
1260 mCachedMenu = menu;
1261 return true;
1262 }
1263
1264 protected void onCreateContextMenu(ContextMenu menu, View v,
1265 ContextMenuInfo menuInfo) {
1266 if (v instanceof TitleBarBase) {
1267 return;
1268 }
1269 if (!(v instanceof WebView)) {
1270 return;
1271 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001272 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001273 WebView.HitTestResult result = webview.getHitTestResult();
1274 if (result == null) {
1275 return;
1276 }
1277
1278 int type = result.getType();
1279 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1280 Log.w(LOGTAG,
1281 "We should not show context menu when nothing is touched");
1282 return;
1283 }
1284 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1285 // let TextView handles context menu
1286 return;
1287 }
1288
1289 // Note, http://b/issue?id=1106666 is requesting that
1290 // an inflated menu can be used again. This is not available
1291 // yet, so inflate each time (yuk!)
1292 MenuInflater inflater = mActivity.getMenuInflater();
1293 inflater.inflate(R.menu.browsercontext, menu);
1294
1295 // Show the correct menu group
1296 final String extra = result.getExtra();
1297 menu.setGroupVisible(R.id.PHONE_MENU,
1298 type == WebView.HitTestResult.PHONE_TYPE);
1299 menu.setGroupVisible(R.id.EMAIL_MENU,
1300 type == WebView.HitTestResult.EMAIL_TYPE);
1301 menu.setGroupVisible(R.id.GEO_MENU,
1302 type == WebView.HitTestResult.GEO_TYPE);
1303 menu.setGroupVisible(R.id.IMAGE_MENU,
1304 type == WebView.HitTestResult.IMAGE_TYPE
1305 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1306 menu.setGroupVisible(R.id.ANCHOR_MENU,
1307 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1308 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001309 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1310 || type == WebView.HitTestResult.PHONE_TYPE
1311 || type == WebView.HitTestResult.EMAIL_TYPE
1312 || type == WebView.HitTestResult.GEO_TYPE;
1313 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1314 if (hitText) {
1315 menu.findItem(R.id.select_text_menu_id)
1316 .setOnMenuItemClickListener(new SelectText(webview));
1317 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001318 // Setup custom handling depending on the type
1319 switch (type) {
1320 case WebView.HitTestResult.PHONE_TYPE:
1321 menu.setHeaderTitle(Uri.decode(extra));
1322 menu.findItem(R.id.dial_context_menu_id).setIntent(
1323 new Intent(Intent.ACTION_VIEW, Uri
1324 .parse(WebView.SCHEME_TEL + extra)));
1325 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1326 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1327 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1328 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1329 addIntent);
1330 menu.findItem(R.id.copy_phone_context_menu_id)
1331 .setOnMenuItemClickListener(
1332 new Copy(extra));
1333 break;
1334
1335 case WebView.HitTestResult.EMAIL_TYPE:
1336 menu.setHeaderTitle(extra);
1337 menu.findItem(R.id.email_context_menu_id).setIntent(
1338 new Intent(Intent.ACTION_VIEW, Uri
1339 .parse(WebView.SCHEME_MAILTO + extra)));
1340 menu.findItem(R.id.copy_mail_context_menu_id)
1341 .setOnMenuItemClickListener(
1342 new Copy(extra));
1343 break;
1344
1345 case WebView.HitTestResult.GEO_TYPE:
1346 menu.setHeaderTitle(extra);
1347 menu.findItem(R.id.map_context_menu_id).setIntent(
1348 new Intent(Intent.ACTION_VIEW, Uri
1349 .parse(WebView.SCHEME_GEO
1350 + URLEncoder.encode(extra))));
1351 menu.findItem(R.id.copy_geo_context_menu_id)
1352 .setOnMenuItemClickListener(
1353 new Copy(extra));
1354 break;
1355
1356 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1357 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001358 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001359 // decide whether to show the open link in new tab option
1360 boolean showNewTab = mTabControl.canCreateNewTab();
1361 MenuItem newTabItem
1362 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001363 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001364 ? R.string.contextmenu_openlink_newwindow_background
1365 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001366 newTabItem.setVisible(showNewTab);
1367 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001368 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1369 newTabItem.setOnMenuItemClickListener(
1370 new MenuItem.OnMenuItemClickListener() {
1371 @Override
1372 public boolean onMenuItemClick(MenuItem item) {
1373 final HashMap<String, WebView> hrefMap =
1374 new HashMap<String, WebView>();
1375 hrefMap.put("webview", webview);
1376 final Message msg = mHandler.obtainMessage(
1377 FOCUS_NODE_HREF,
1378 R.id.open_newtab_context_menu_id,
1379 0, hrefMap);
1380 webview.requestFocusNodeHref(msg);
1381 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001382 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001383 });
1384 } else {
1385 newTabItem.setOnMenuItemClickListener(
1386 new MenuItem.OnMenuItemClickListener() {
1387 @Override
1388 public boolean onMenuItemClick(MenuItem item) {
1389 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb7bcafde2011-05-09 13:55:59 -07001390 final Tab newTab =
1391 openTab(extra,
1392 (parent != null)
1393 && parent.isPrivateBrowsingEnabled(),
1394 !mSettings.openInBackground(),
1395 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001396 if (newTab != parent) {
1397 parent.addChildTab(newTab);
1398 }
1399 return true;
1400 }
1401 });
1402 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001403 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001404 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1405 break;
1406 }
1407 // otherwise fall through to handle image part
1408 case WebView.HitTestResult.IMAGE_TYPE:
1409 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1410 menu.setHeaderTitle(extra);
1411 }
1412 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1413 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1414 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001415 setOnMenuItemClickListener(
1416 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001417 menu.findItem(R.id.set_wallpaper_context_menu_id).
1418 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1419 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001420 break;
1421
1422 default:
1423 Log.w(LOGTAG, "We should not get here.");
1424 break;
1425 }
1426 //update the ui
1427 mUi.onContextMenuCreated(menu);
1428 }
1429
1430 /**
1431 * As the menu can be open when loading state changes
1432 * we must manually update the state of the stop/reload menu
1433 * item
1434 */
1435 private void updateInLoadMenuItems(Menu menu) {
1436 if (menu == null) {
1437 return;
1438 }
1439 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1440 MenuItem src = mInLoad ?
1441 menu.findItem(R.id.stop_menu_id):
1442 menu.findItem(R.id.reload_menu_id);
1443 if (src != null) {
1444 dest.setIcon(src.getIcon());
1445 dest.setTitle(src.getTitle());
1446 }
1447 }
1448
John Reckb3417f02011-01-14 11:01:05 -08001449 boolean onPrepareOptionsMenu(Menu menu) {
1450 if (mOptionsMenuHandler != null) {
1451 return mOptionsMenuHandler.onPrepareOptionsMenu(menu);
1452 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001453 // Note: setVisible will decide whether an item is visible; while
1454 // setEnabled() will decide whether an item is enabled, which also means
1455 // whether the matching shortcut key will function.
1456 switch (mMenuState) {
1457 case EMPTY_MENU:
1458 if (mCurrentMenuState != mMenuState) {
1459 menu.setGroupVisible(R.id.MAIN_MENU, false);
1460 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1461 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1462 }
1463 break;
1464 default:
1465 if (mCurrentMenuState != mMenuState) {
1466 menu.setGroupVisible(R.id.MAIN_MENU, true);
1467 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1468 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1469 }
1470 final WebView w = getCurrentTopWebView();
1471 boolean canGoBack = false;
1472 boolean canGoForward = false;
1473 boolean isHome = false;
1474 if (w != null) {
1475 canGoBack = w.canGoBack();
1476 canGoForward = w.canGoForward();
1477 isHome = mSettings.getHomePage().equals(w.getUrl());
1478 }
1479 final MenuItem back = menu.findItem(R.id.back_menu_id);
1480 back.setEnabled(canGoBack);
1481
1482 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1483 home.setEnabled(!isHome);
1484
1485 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1486 forward.setEnabled(canGoForward);
1487
1488 // decide whether to show the share link option
1489 PackageManager pm = mActivity.getPackageManager();
1490 Intent send = new Intent(Intent.ACTION_SEND);
1491 send.setType("text/plain");
1492 ResolveInfo ri = pm.resolveActivity(send,
1493 PackageManager.MATCH_DEFAULT_ONLY);
1494 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1495
John Reck35e9dd62011-04-25 09:01:54 -07001496 boolean isNavDump = mSettings.enableNavDump();
Michael Kolb8233fac2010-10-26 16:08:53 -07001497 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1498 nav.setVisible(isNavDump);
1499 nav.setEnabled(isNavDump);
1500
John Reck35e9dd62011-04-25 09:01:54 -07001501 boolean showDebugSettings = mSettings.isDebugEnabled();
Michael Kolb8233fac2010-10-26 16:08:53 -07001502 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1503 counter.setVisible(showDebugSettings);
1504 counter.setEnabled(showDebugSettings);
1505
John Reckb3417f02011-01-14 11:01:05 -08001506 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1507 newtab.setEnabled(getTabControl().canCreateNewTab());
Michael Kolb8233fac2010-10-26 16:08:53 -07001508
Leon Scroggins81983762011-02-11 15:17:36 -05001509 MenuItem archive = menu.findItem(R.id.save_webarchive_menu_id);
John Reck51d8bad2011-02-28 15:47:47 -08001510 Tab tab = getTabControl().getCurrentTab();
1511 String url = tab != null ? tab.getUrl() : null;
1512 archive.setVisible(!TextUtils.isEmpty(url)
1513 && !url.endsWith(".webarchivexml"));
Michael Kolb8233fac2010-10-26 16:08:53 -07001514 break;
1515 }
1516 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001517 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001518 }
1519
1520 public boolean onOptionsItemSelected(MenuItem item) {
John Reckb3417f02011-01-14 11:01:05 -08001521 if (mOptionsMenuHandler != null &&
1522 mOptionsMenuHandler.onOptionsItemSelected(item)) {
1523 return true;
1524 }
1525
Michael Kolb8233fac2010-10-26 16:08:53 -07001526 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1527 // menu remains active, so ensure comboview is dismissed
1528 // if main menu option is selected
1529 removeComboView();
1530 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001531 if (null == getCurrentTopWebView()) {
1532 return false;
1533 }
1534 if (mMenuIsDown) {
1535 // The shortcut action consumes the MENU. Even if it is still down,
1536 // it won't trigger the next shortcut action. In the case of the
1537 // shortcut action triggering a new activity, like Bookmarks, we
1538 // won't get onKeyUp for MENU. So it is important to reset it here.
1539 mMenuIsDown = false;
1540 }
1541 switch (item.getItemId()) {
1542 // -- Main menu
1543 case R.id.new_tab_menu_id:
1544 openTabToHomePage();
1545 break;
1546
1547 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001548 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001549 break;
1550
1551 case R.id.goto_menu_id:
1552 editUrl();
1553 break;
1554
1555 case R.id.bookmarks_menu_id:
1556 bookmarksOrHistoryPicker(false);
1557 break;
1558
1559 case R.id.active_tabs_menu_id:
1560 showActiveTabsPage();
1561 break;
1562
1563 case R.id.add_bookmark_menu_id:
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001564 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001565 break;
1566
1567 case R.id.stop_reload_menu_id:
1568 if (mInLoad) {
1569 stopLoading();
1570 } else {
1571 getCurrentTopWebView().reload();
1572 }
1573 break;
1574
1575 case R.id.back_menu_id:
1576 getCurrentTopWebView().goBack();
1577 break;
1578
1579 case R.id.forward_menu_id:
1580 getCurrentTopWebView().goForward();
1581 break;
1582
1583 case R.id.close_menu_id:
1584 // Close the subwindow if it exists.
1585 if (mTabControl.getCurrentSubWindow() != null) {
1586 dismissSubWindow(mTabControl.getCurrentTab());
1587 break;
1588 }
1589 closeCurrentTab();
1590 break;
1591
1592 case R.id.homepage_menu_id:
1593 Tab current = mTabControl.getCurrentTab();
1594 if (current != null) {
1595 dismissSubWindow(current);
1596 loadUrl(current.getWebView(), mSettings.getHomePage());
1597 }
1598 break;
1599
1600 case R.id.preferences_menu_id:
1601 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1602 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1603 getCurrentTopWebView().getUrl());
1604 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1605 break;
1606
1607 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001608 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001609 break;
1610
Leon Scrogginsac993842011-02-02 12:54:07 -05001611 case R.id.save_webarchive_menu_id:
1612 String state = Environment.getExternalStorageState();
1613 if (!Environment.MEDIA_MOUNTED.equals(state)) {
1614 Log.e(LOGTAG, "External storage not mounted");
1615 Toast.makeText(mActivity, R.string.webarchive_failed,
1616 Toast.LENGTH_SHORT).show();
1617 break;
1618 }
1619 final String directory = Environment.getExternalStoragePublicDirectory(
1620 Environment.DIRECTORY_DOWNLOADS) + File.separator;
1621 File dir = new File(directory);
1622 if (!dir.exists() && !dir.mkdirs()) {
1623 Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
1624 Toast.makeText(mActivity, R.string.webarchive_failed,
1625 Toast.LENGTH_SHORT).show();
1626 break;
1627 }
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001628 final WebView topWebView = getCurrentTopWebView();
Leon Scrogginsac993842011-02-02 12:54:07 -05001629 final String title = topWebView.getTitle();
John Reck51d8bad2011-02-28 15:47:47 -08001630 final String url = topWebView.getUrl();
Leon Scrogginsac993842011-02-02 12:54:07 -05001631 topWebView.saveWebArchive(directory, true,
1632 new ValueCallback<String>() {
1633 @Override
1634 public void onReceiveValue(final String value) {
1635 if (value != null) {
1636 File file = new File(value);
1637 final long length = file.length();
1638 if (file.exists() && length > 0) {
Leon Scroggins1cb96552011-02-11 14:22:57 -05001639 Toast.makeText(mActivity, R.string.webarchive_saved,
1640 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001641 final DownloadManager manager = (DownloadManager) mActivity
1642 .getSystemService(Context.DOWNLOAD_SERVICE);
1643 new Thread("Add WebArchive to download manager") {
1644 @Override
1645 public void run() {
Vasu Noria9e30a72011-03-07 11:37:34 -08001646 manager.addCompletedDownload(
1647 null == title ? value : title,
Leon Scrogginsac993842011-02-02 12:54:07 -05001648 value, true, "application/x-webarchive-xml",
1649 value, length, true);
1650 }
1651 }.start();
1652 return;
1653 }
1654 }
John Reck51d8bad2011-02-28 15:47:47 -08001655 DownloadHandler.onDownloadStartNoStream(mActivity,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001656 url, null, null, null, topWebView.isPrivateBrowsingEnabled());
Leon Scrogginsac993842011-02-02 12:54:07 -05001657 }
1658 });
1659 break;
1660
Michael Kolb8233fac2010-10-26 16:08:53 -07001661 case R.id.page_info_menu_id:
1662 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1663 false);
1664 break;
1665
1666 case R.id.classic_history_menu_id:
1667 bookmarksOrHistoryPicker(true);
1668 break;
1669
1670 case R.id.title_bar_share_page_url:
1671 case R.id.share_page_menu_id:
1672 Tab currentTab = mTabControl.getCurrentTab();
1673 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001674 return false;
1675 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001676 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001677 break;
1678
1679 case R.id.dump_nav_menu_id:
1680 getCurrentTopWebView().debugDump();
1681 break;
1682
1683 case R.id.dump_counters_menu_id:
1684 getCurrentTopWebView().dumpV8Counters();
1685 break;
1686
1687 case R.id.zoom_in_menu_id:
1688 getCurrentTopWebView().zoomIn();
1689 break;
1690
1691 case R.id.zoom_out_menu_id:
1692 getCurrentTopWebView().zoomOut();
1693 break;
1694
1695 case R.id.view_downloads_menu_id:
1696 viewDownloads();
1697 break;
1698
1699 case R.id.window_one_menu_id:
1700 case R.id.window_two_menu_id:
1701 case R.id.window_three_menu_id:
1702 case R.id.window_four_menu_id:
1703 case R.id.window_five_menu_id:
1704 case R.id.window_six_menu_id:
1705 case R.id.window_seven_menu_id:
1706 case R.id.window_eight_menu_id:
1707 {
1708 int menuid = item.getItemId();
1709 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1710 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1711 Tab desiredTab = mTabControl.getTab(id);
1712 if (desiredTab != null &&
1713 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001714 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001715 }
1716 break;
1717 }
1718 }
1719 }
1720 break;
1721
1722 default:
1723 return false;
1724 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001725 return true;
1726 }
1727
1728 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001729 // Let the History and Bookmark fragments handle menus they created.
1730 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1731 return false;
1732 }
1733
Michael Kolb8233fac2010-10-26 16:08:53 -07001734 int id = item.getItemId();
1735 boolean result = true;
1736 switch (id) {
1737 // For the context menu from the title bar
1738 case R.id.title_bar_copy_page_url:
1739 Tab currentTab = mTabControl.getCurrentTab();
1740 if (null == currentTab) {
1741 result = false;
1742 break;
1743 }
1744 WebView mainView = currentTab.getWebView();
1745 if (null == mainView) {
1746 result = false;
1747 break;
1748 }
1749 copy(mainView.getUrl());
1750 break;
1751 // -- Browser context menu
1752 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001753 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001754 case R.id.copy_link_context_menu_id:
1755 final WebView webView = getCurrentTopWebView();
1756 if (null == webView) {
1757 result = false;
1758 break;
1759 }
1760 final HashMap<String, WebView> hrefMap =
1761 new HashMap<String, WebView>();
1762 hrefMap.put("webview", webView);
1763 final Message msg = mHandler.obtainMessage(
1764 FOCUS_NODE_HREF, id, 0, hrefMap);
1765 webView.requestFocusNodeHref(msg);
1766 break;
1767
1768 default:
1769 // For other context menus
1770 result = onOptionsItemSelected(item);
1771 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001772 return result;
1773 }
1774
1775 /**
1776 * support programmatically opening the context menu
1777 */
1778 public void openContextMenu(View view) {
1779 mActivity.openContextMenu(view);
1780 }
1781
1782 /**
1783 * programmatically open the options menu
1784 */
1785 public void openOptionsMenu() {
1786 mActivity.openOptionsMenu();
1787 }
1788
1789 public boolean onMenuOpened(int featureId, Menu menu) {
1790 if (mOptionsMenuOpen) {
1791 if (mConfigChanged) {
1792 // We do not need to make any changes to the state of the
1793 // title bar, since the only thing that happened was a
1794 // change in orientation
1795 mConfigChanged = false;
1796 } else {
1797 if (!mExtendedMenuOpen) {
1798 mExtendedMenuOpen = true;
1799 mUi.onExtendedMenuOpened();
1800 } else {
1801 // Switching the menu back to icon view, so show the
1802 // title bar once again.
1803 mExtendedMenuOpen = false;
1804 mUi.onExtendedMenuClosed(mInLoad);
Michael Kolb8233fac2010-10-26 16:08:53 -07001805 }
1806 }
1807 } else {
1808 // The options menu is closed, so open it, and show the title
1809 mOptionsMenuOpen = true;
1810 mConfigChanged = false;
1811 mExtendedMenuOpen = false;
1812 mUi.onOptionsMenuOpened();
1813 }
1814 return true;
1815 }
1816
1817 public void onOptionsMenuClosed(Menu menu) {
1818 mOptionsMenuOpen = false;
1819 mUi.onOptionsMenuClosed(mInLoad);
1820 }
1821
1822 public void onContextMenuClosed(Menu menu) {
1823 mUi.onContextMenuClosed(menu, mInLoad);
1824 }
1825
1826 // Helper method for getting the top window.
1827 @Override
1828 public WebView getCurrentTopWebView() {
1829 return mTabControl.getCurrentTopWebView();
1830 }
1831
1832 @Override
1833 public WebView getCurrentWebView() {
1834 return mTabControl.getCurrentWebView();
1835 }
1836
1837 /*
1838 * This method is called as a result of the user selecting the options
1839 * menu to see the download window. It shows the download window on top of
1840 * the current window.
1841 */
1842 void viewDownloads() {
1843 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1844 mActivity.startActivity(intent);
1845 }
1846
1847 // action mode
1848
1849 void onActionModeStarted(ActionMode mode) {
1850 mUi.onActionModeStarted(mode);
1851 mActionMode = mode;
1852 }
1853
1854 /*
1855 * True if a custom ActionMode (i.e. find or select) is in use.
1856 */
1857 @Override
1858 public boolean isInCustomActionMode() {
1859 return mActionMode != null;
1860 }
1861
1862 /*
1863 * End the current ActionMode.
1864 */
1865 @Override
1866 public void endActionMode() {
1867 if (mActionMode != null) {
1868 mActionMode.finish();
1869 }
1870 }
1871
1872 /*
1873 * Called by find and select when they are finished. Replace title bars
1874 * as necessary.
1875 */
1876 public void onActionModeFinished(ActionMode mode) {
1877 if (!isInCustomActionMode()) return;
1878 mUi.onActionModeFinished(mInLoad);
1879 mActionMode = null;
1880 }
1881
1882 boolean isInLoad() {
1883 return mInLoad;
1884 }
1885
1886 // bookmark handling
1887
1888 /**
1889 * add the current page as a bookmark to the given folder id
1890 * @param folderId use -1 for the default folder
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001891 * @param canBeAnEdit If true, check to see whether the site is already
1892 * bookmarked, and if it is, edit that bookmark. If false, and
1893 * the site is already bookmarked, do not attempt to edit the
1894 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001895 */
1896 @Override
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001897 public void bookmarkCurrentPage(long folderId, boolean canBeAnEdit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001898 Intent i = new Intent(mActivity,
1899 AddBookmarkPage.class);
1900 WebView w = getCurrentTopWebView();
1901 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1902 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1903 String touchIconUrl = w.getTouchIconUrl();
1904 if (touchIconUrl != null) {
1905 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1906 WebSettings settings = w.getSettings();
1907 if (settings != null) {
1908 i.putExtra(AddBookmarkPage.USER_AGENT,
1909 settings.getUserAgentString());
1910 }
1911 }
1912 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1913 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1914 getDesiredThumbnailHeight(mActivity)));
1915 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1916 i.putExtra(BrowserContract.Bookmarks.PARENT,
1917 folderId);
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001918 if (canBeAnEdit) {
1919 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1920 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001921 // Put the dialog at the upper right of the screen, covering the
1922 // star on the title bar.
1923 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1924 mActivity.startActivity(i);
1925 }
1926
1927 // file chooser
1928 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1929 mUploadHandler = new UploadHandler(this);
1930 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1931 }
1932
1933 // thumbnails
1934
1935 /**
1936 * Return the desired width for thumbnail screenshots, which are stored in
1937 * the database, and used on the bookmarks screen.
1938 * @param context Context for finding out the density of the screen.
1939 * @return desired width for thumbnail screenshot.
1940 */
1941 static int getDesiredThumbnailWidth(Context context) {
1942 return context.getResources().getDimensionPixelOffset(
1943 R.dimen.bookmarkThumbnailWidth);
1944 }
1945
1946 /**
1947 * Return the desired height for thumbnail screenshots, which are stored in
1948 * the database, and used on the bookmarks screen.
1949 * @param context Context for finding out the density of the screen.
1950 * @return desired height for thumbnail screenshot.
1951 */
1952 static int getDesiredThumbnailHeight(Context context) {
1953 return context.getResources().getDimensionPixelOffset(
1954 R.dimen.bookmarkThumbnailHeight);
1955 }
1956
Michael Kolb1acef692011-03-08 14:12:06 -08001957 static Bitmap createScreenshot(Tab tab, int width, int height) {
1958 if ((tab != null) && (tab.getWebView() != null)) {
1959 return createScreenshot(tab.getWebView(), width, height);
1960 }
1961 return null;
1962 }
1963
Michael Kolb8233fac2010-10-26 16:08:53 -07001964 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001965 // We render to a bitmap 2x the desired size so that we can then
1966 // re-scale it with filtering since canvas.scale doesn't filter
1967 // This helps reduce aliasing at the cost of being slightly blurry
1968 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001969 Picture thumbnail = view.capturePicture();
1970 if (thumbnail == null) {
1971 return null;
1972 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001973 width *= filter_scale;
1974 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001975 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1976 Canvas canvas = new Canvas(bm);
1977 // May need to tweak these values to determine what is the
1978 // best scale factor
1979 int thumbnailWidth = thumbnail.getWidth();
1980 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001981 float scaleFactor = 1.0f;
Michael Kolbeb95db42011-03-03 10:38:40 -08001982 if (thumbnailWidth > 0 && thumbnailHeight > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001983 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001984 } else {
1985 return null;
1986 }
John Reckfe49ab42010-11-16 17:09:37 -08001987
Michael Kolbeb95db42011-03-03 10:38:40 -08001988 float scaleFactorY = (float) height / (float)thumbnailHeight;
1989 if (scaleFactorY > scaleFactor) {
1990 // The picture is narrower than the requested AR
1991 // Center the thumnail and crop the sides
1992 scaleFactor = scaleFactorY;
John Reckfe49ab42010-11-16 17:09:37 -08001993 float wx = (thumbnailWidth * scaleFactor) - width;
1994 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001995 }
1996
John Reckfe49ab42010-11-16 17:09:37 -08001997 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001998
1999 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08002000 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
2001 height / filter_scale, true);
2002 bm.recycle();
2003 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07002004 }
2005
John Reck34ef2672011-02-10 11:30:55 -08002006 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002007 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07002008 // FIXME: Would like to make sure there is actually something to
2009 // draw, but the API for that (WebViewCore.pictureReady()) is not
2010 // currently accessible here.
2011
John Reck34ef2672011-02-10 11:30:55 -08002012 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08002013 if (view == null) {
2014 // Tab was destroyed
2015 return;
2016 }
John Reck34ef2672011-02-10 11:30:55 -08002017 final String url = tab.getUrl();
2018 final String originalUrl = view.getOriginalUrl();
2019
2020 if (TextUtils.isEmpty(url)) {
2021 return;
2022 }
2023
2024 // Only update thumbnails for web urls (http(s)://), not for
2025 // about:, javascript:, data:, etc...
2026 // Unless it is a bookmarked site, then always update
2027 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2028 return;
2029 }
2030
Michael Kolb8233fac2010-10-26 16:08:53 -07002031 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2032 getDesiredThumbnailHeight(mActivity));
2033 if (bm == null) {
2034 return;
2035 }
2036
2037 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002038 new AsyncTask<Void, Void, Void>() {
2039 @Override
2040 protected Void doInBackground(Void... unused) {
2041 Cursor cursor = null;
2042 try {
2043 // TODO: Clean this up
2044 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2045 if (cursor != null && cursor.moveToFirst()) {
2046 final ByteArrayOutputStream os =
2047 new ByteArrayOutputStream();
2048 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002049
John Reck34ef2672011-02-10 11:30:55 -08002050 ContentValues values = new ContentValues();
2051 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002052
John Reck34ef2672011-02-10 11:30:55 -08002053 do {
John Reck617fd832011-02-16 14:35:59 -08002054 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002055 cr.update(Images.CONTENT_URI, values, null, null);
2056 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002057 }
John Reck34ef2672011-02-10 11:30:55 -08002058 } catch (IllegalStateException e) {
2059 // Ignore
2060 } finally {
2061 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002062 }
John Reck34ef2672011-02-10 11:30:55 -08002063 return null;
2064 }
2065 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002066 }
2067
2068 private class Copy implements OnMenuItemClickListener {
2069 private CharSequence mText;
2070
2071 public boolean onMenuItemClick(MenuItem item) {
2072 copy(mText);
2073 return true;
2074 }
2075
2076 public Copy(CharSequence toCopy) {
2077 mText = toCopy;
2078 }
2079 }
2080
Leon Scroggins63c02662010-11-18 15:16:27 -05002081 private static class Download implements OnMenuItemClickListener {
2082 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002083 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002084 private boolean mPrivateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002085
2086 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002087 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002088 null, null, mPrivateBrowsing);
Michael Kolb8233fac2010-10-26 16:08:53 -07002089 return true;
2090 }
2091
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002092 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002093 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002094 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002095 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002096 }
2097 }
2098
Cary Clark8974d282010-11-22 10:46:05 -05002099 private static class SelectText implements OnMenuItemClickListener {
2100 private WebView mWebView;
2101
2102 public boolean onMenuItemClick(MenuItem item) {
2103 if (mWebView != null) {
2104 return mWebView.selectText();
2105 }
2106 return false;
2107 }
2108
2109 public SelectText(WebView webView) {
2110 mWebView = webView;
2111 }
2112
2113 }
2114
Michael Kolb8233fac2010-10-26 16:08:53 -07002115 /********************** TODO: UI stuff *****************************/
2116
2117 // these methods have been copied, they still need to be cleaned up
2118
2119 /****************** tabs ***************************************************/
2120
2121 // basic tab interactions:
2122
2123 // it is assumed that tabcontrol already knows about the tab
2124 protected void addTab(Tab tab) {
2125 mUi.addTab(tab);
2126 }
2127
2128 protected void removeTab(Tab tab) {
2129 mUi.removeTab(tab);
2130 mTabControl.removeTab(tab);
2131 }
2132
Michael Kolbf2055602011-04-09 17:20:03 -07002133 @Override
2134 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002135 // monkey protection against delayed start
2136 if (tab != null) {
2137 mTabControl.setCurrentTab(tab);
2138 // the tab is guaranteed to have a webview after setCurrentTab
2139 mUi.setActiveTab(tab);
2140 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002141 }
2142
2143 protected void closeEmptyChildTab() {
2144 Tab current = mTabControl.getCurrentTab();
2145 if (current != null
2146 && current.getWebView().copyBackForwardList().getSize() == 0) {
Michael Kolbc831b632011-05-11 09:30:34 -07002147 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002148 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002149 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002150 closeTab(current);
2151 }
2152 }
2153 }
2154
2155 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002156 // Dismiss the subwindow if applicable.
2157 dismissSubWindow(appTab);
2158 // Since we might kill the WebView, remove it from the
2159 // content view first.
2160 mUi.detachTab(appTab);
2161 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002162 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002163 // TODO: analyze why the remove and add are necessary
2164 mUi.attachTab(appTab);
2165 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002166 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002167 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002168 } else {
2169 // If the tab was the current tab, we have to attach
2170 // it to the view system again.
2171 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002172 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002173 }
2174 }
2175
2176 // Remove the sub window if it exists. Also called by TabControl when the
2177 // user clicks the 'X' to dismiss a sub window.
2178 public void dismissSubWindow(Tab tab) {
2179 removeSubWindow(tab);
2180 // dismiss the subwindow. This will destroy the WebView.
2181 tab.dismissSubWindow();
2182 getCurrentTopWebView().requestFocus();
2183 }
2184
2185 @Override
2186 public void removeSubWindow(Tab t) {
2187 if (t.getSubWebView() != null) {
2188 mUi.removeSubWindow(t.getSubViewContainer());
2189 }
2190 }
2191
2192 @Override
2193 public void attachSubWindow(Tab tab) {
2194 if (tab.getSubWebView() != null) {
2195 mUi.attachSubWindow(tab.getSubViewContainer());
2196 getCurrentTopWebView().requestFocus();
2197 }
2198 }
2199
Michael Kolb7bcafde2011-05-09 13:55:59 -07002200 // open a non inconito tab with the given url data
2201 // and set as active tab
2202 public Tab openTab(UrlData urlData) {
2203 Tab tab = createNewTab(false, true, true);
2204 if ((tab != null) && !urlData.isEmpty()) {
2205 loadUrlDataIn(tab, urlData);
2206 }
2207 return tab;
2208 }
2209
Michael Kolb843510f2010-12-09 10:51:49 -08002210 @Override
2211 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002212 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002213 }
2214
Michael Kolb8233fac2010-10-26 16:08:53 -07002215 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002216 public Tab openIncognitoTab() {
2217 return openTab(INCOGNITO_URI, true, true, false);
2218 }
2219
2220 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002221 public Tab openTab(String url, boolean incognito, boolean setActive,
2222 boolean useCurrent) {
2223 Tab tab = createNewTab(incognito, setActive, useCurrent);
2224 if (tab != null) {
Michael Kolba4261fd2011-05-05 11:27:37 -07002225 WebView w = tab.getWebView();
Michael Kolb519d2282011-05-09 17:03:19 -07002226 if (url != null) {
2227 loadUrl(w, url);
2228 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002229 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002230 return tab;
2231 }
2232
2233 // this method will attempt to create a new tab
2234 // incognito: private browsing tab
2235 // setActive: ste tab as current tab
2236 // useCurrent: if no new tab can be created, return current tab
2237 private Tab createNewTab(boolean incognito, boolean setActive,
2238 boolean useCurrent) {
2239 Tab tab = null;
2240 if (mTabControl.canCreateNewTab()) {
2241 tab = mTabControl.createNewTab(incognito);
2242 addTab(tab);
2243 if (setActive) {
2244 setActiveTab(tab);
2245 }
2246 } else {
2247 if (useCurrent) {
2248 tab = mTabControl.getCurrentTab();
2249 // Get rid of the subwindow if it exists
2250 dismissSubWindow(tab);
2251 } else {
2252 mUi.showMaxTabsWarning();
2253 }
2254 }
2255 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002256 }
2257
2258 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002259 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002260 * @return boolean True if we successfully switched to a different tab. If
2261 * the indexth tab is null, or if that tab is the same as
2262 * the current one, return false.
2263 */
2264 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002265 public boolean switchToTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002266 // hide combo view if open
2267 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002268 Tab currentTab = mTabControl.getCurrentTab();
2269 if (tab == null || tab == currentTab) {
2270 return false;
2271 }
2272 setActiveTab(tab);
2273 return true;
2274 }
2275
2276 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002277 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002278 // hide combo view if open
2279 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002280 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002281 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002282 return;
2283 }
Michael Kolbc831b632011-05-11 09:30:34 -07002284 final Tab current = mTabControl.getCurrentTab();
2285 final int pos = mTabControl.getCurrentPosition();
2286 Tab newTab = current.getParent();
2287 if (newTab == null) {
2288 newTab = mTabControl.getTab(pos + 1);
2289 if (newTab == null) {
2290 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002291 }
2292 }
Michael Kolbc831b632011-05-11 09:30:34 -07002293 if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002294 // Close window
2295 closeTab(current);
2296 }
2297 }
2298
2299 /**
2300 * Close the tab, remove its associated title bar, and adjust mTabControl's
2301 * current tab to a valid value.
2302 */
2303 @Override
2304 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002305 // hide combo view if open
2306 removeComboView();
Michael Kolb2d59c322011-01-25 13:18:55 -08002307 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002308 }
2309
2310 /**************** TODO: Url loading clean up *******************************/
2311
2312 // Called when loading from context menu or LOAD_URL message
2313 protected void loadUrlFromContext(WebView view, String url) {
2314 // In case the user enters nothing.
2315 if (url != null && url.length() != 0 && view != null) {
2316 url = UrlUtils.smartUrlFilter(url);
2317 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2318 loadUrl(view, url);
2319 }
2320 }
2321 }
2322
2323 /**
2324 * Load the URL into the given WebView and update the title bar
2325 * to reflect the new load. Call this instead of WebView.loadUrl
2326 * directly.
2327 * @param view The WebView used to load url.
2328 * @param url The URL to load.
2329 */
2330 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002331 view.loadUrl(url);
2332 }
2333
2334 /**
2335 * Load UrlData into a Tab and update the title bar to reflect the new
2336 * load. Call this instead of UrlData.loadIn directly.
2337 * @param t The Tab used to load.
2338 * @param data The UrlData being loaded.
2339 */
2340 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002341 data.loadIn(t);
2342 }
2343
John Reck30c714c2010-12-16 17:30:34 -08002344 @Override
2345 public void onUserCanceledSsl(Tab tab) {
2346 WebView web = tab.getWebView();
2347 // TODO: Figure out the "right" behavior
2348 if (web.canGoBack()) {
2349 web.goBack();
2350 } else {
2351 web.loadUrl(mSettings.getHomePage());
2352 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002353 }
2354
2355 void goBackOnePageOrQuit() {
2356 Tab current = mTabControl.getCurrentTab();
2357 if (current == null) {
2358 /*
2359 * Instead of finishing the activity, simply push this to the back
2360 * of the stack and let ActivityManager to choose the foreground
2361 * activity. As BrowserActivity is singleTask, it will be always the
2362 * root of the task. So we can use either true or false for
2363 * moveTaskToBack().
2364 */
2365 mActivity.moveTaskToBack(true);
2366 return;
2367 }
2368 WebView w = current.getWebView();
2369 if (w.canGoBack()) {
2370 w.goBack();
2371 } else {
2372 // Check to see if we are closing a window that was created by
2373 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002374 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002375 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002376 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002377 // Now we close the other tab
2378 closeTab(current);
2379 } else {
Michael Kolb8233fac2010-10-26 16:08:53 -07002380 /*
2381 * Instead of finishing the activity, simply push this to the back
2382 * of the stack and let ActivityManager to choose the foreground
2383 * activity. As BrowserActivity is singleTask, it will be always the
2384 * root of the task. So we can use either true or false for
2385 * moveTaskToBack().
2386 */
2387 mActivity.moveTaskToBack(true);
2388 }
2389 }
2390 }
2391
2392 /**
2393 * Feed the previously stored results strings to the BrowserProvider so that
2394 * the SearchDialog will show them instead of the standard searches.
2395 * @param result String to show on the editable line of the SearchDialog.
2396 */
2397 @Override
2398 public void showVoiceSearchResults(String result) {
2399 ContentProviderClient client = mActivity.getContentResolver()
2400 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2401 ContentProvider prov = client.getLocalContentProvider();
2402 BrowserProvider bp = (BrowserProvider) prov;
2403 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2404 client.release();
2405
2406 Bundle bundle = createGoogleSearchSourceBundle(
2407 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2408 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2409 startSearch(result, false, bundle, false);
2410 }
2411
2412 private void startSearch(String initialQuery, boolean selectInitialQuery,
2413 Bundle appSearchData, boolean globalSearch) {
2414 if (appSearchData == null) {
2415 appSearchData = createGoogleSearchSourceBundle(
2416 GOOGLE_SEARCH_SOURCE_TYPE);
2417 }
2418
2419 SearchEngine searchEngine = mSettings.getSearchEngine();
2420 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2421 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2422 }
2423 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2424 globalSearch);
2425 }
2426
2427 private Bundle createGoogleSearchSourceBundle(String source) {
2428 Bundle bundle = new Bundle();
2429 bundle.putString(Search.SOURCE, source);
2430 return bundle;
2431 }
2432
2433 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002434 * helper method for key handler
2435 * returns the current tab if it can't advance
2436 */
Michael Kolbc831b632011-05-11 09:30:34 -07002437 private Tab getNextTab() {
2438 return mTabControl.getTab(Math.min(mTabControl.getTabCount() - 1,
2439 mTabControl.getCurrentPosition() + 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002440 }
2441
2442 /**
2443 * helper method for key handler
2444 * returns the current tab if it can't advance
2445 */
Michael Kolbc831b632011-05-11 09:30:34 -07002446 private Tab getPrevTab() {
2447 return mTabControl.getTab(Math.max(0,
2448 mTabControl.getCurrentPosition() - 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002449 }
2450
2451 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002452 * handle key events in browser
2453 *
2454 * @param keyCode
2455 * @param event
2456 * @return true if handled, false to pass to super
2457 */
2458 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002459 boolean noModifiers = event.hasNoModifiers();
2460
Michael Kolb8233fac2010-10-26 16:08:53 -07002461 // Even if MENU is already held down, we need to call to super to open
2462 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002463 if (!noModifiers
2464 && ((KeyEvent.KEYCODE_MENU == keyCode)
2465 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2466 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002467 mMenuIsDown = true;
2468 return false;
2469 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002470
Cary Clark8ff8c662010-12-29 15:03:05 -05002471 WebView webView = getCurrentTopWebView();
2472 if (webView == null) return false;
2473
Cary Clark160bbb92011-01-10 11:17:07 -05002474 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2475 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002476
Michael Kolb8233fac2010-10-26 16:08:53 -07002477 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002478 case KeyEvent.KEYCODE_TAB:
2479 if (event.isCtrlPressed()) {
2480 if (event.isShiftPressed()) {
2481 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002482 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002483 } else {
2484 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002485 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002486 }
2487 return true;
2488 }
2489 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002490 case KeyEvent.KEYCODE_SPACE:
2491 // WebView/WebTextView handle the keys in the KeyDown. As
2492 // the Activity's shortcut keys are only handled when WebView
2493 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002494 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002495 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002496 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002497 pageDown();
2498 }
2499 return true;
2500 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002501 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002502 event.startTracking();
2503 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002504 case KeyEvent.KEYCODE_DPAD_LEFT:
2505 if (ctrl) {
2506 webView.goBack();
2507 return true;
2508 }
2509 break;
2510 case KeyEvent.KEYCODE_DPAD_RIGHT:
2511 if (ctrl) {
2512 webView.goForward();
2513 return true;
2514 }
2515 break;
2516 case KeyEvent.KEYCODE_A:
2517 if (ctrl) {
2518 webView.selectAll();
2519 return true;
2520 }
2521 break;
Michael Kolba4183062011-01-16 10:43:21 -08002522// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002523 case KeyEvent.KEYCODE_C:
2524 if (ctrl) {
2525 webView.copySelection();
2526 return true;
2527 }
2528 break;
Michael Kolba4183062011-01-16 10:43:21 -08002529// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002530// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002531// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002532// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002533// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002534// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002535// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002536// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002537// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002538// case KeyEvent.KEYCODE_M: // unused
2539// case KeyEvent.KEYCODE_N: // in Chrome: new window
2540// case KeyEvent.KEYCODE_O: // in Chrome: open file
2541// case KeyEvent.KEYCODE_P: // in Chrome: print page
2542// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002543// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002544// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2545 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002546 // we can't use the ctrl/shift flags, they check for
2547 // exclusive use of a modifier
2548 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002549 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002550 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002551 } else {
2552 openTabToHomePage();
2553 }
2554 return true;
2555 }
2556 break;
2557// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2558// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb1a2eba42011-03-16 16:42:49 -07002559 case KeyEvent.KEYCODE_W: // in Chrome: close tab
2560 if (ctrl) {
2561 closeCurrentTab();
2562 return true;
2563 }
2564 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002565// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2566// case KeyEvent.KEYCODE_Y: // unused
2567// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002568 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002569 // it is a regular key and webview is not null
2570 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002571 }
2572
John Recke6bf4ab2011-02-24 15:48:05 -08002573 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2574 switch(keyCode) {
2575 case KeyEvent.KEYCODE_BACK:
2576 if (mUi.showsWeb()) {
2577 bookmarksOrHistoryPicker(true);
2578 return true;
2579 }
2580 break;
2581 }
2582 return false;
2583 }
2584
Michael Kolb8233fac2010-10-26 16:08:53 -07002585 boolean onKeyUp(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002586 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002587 switch(keyCode) {
2588 case KeyEvent.KEYCODE_MENU:
2589 mMenuIsDown = false;
2590 break;
2591 case KeyEvent.KEYCODE_BACK:
2592 if (event.isTracking() && !event.isCanceled()) {
2593 onBackKey();
2594 return true;
2595 }
2596 break;
2597 }
2598 return false;
2599 }
2600
2601 public boolean isMenuDown() {
2602 return mMenuIsDown;
2603 }
2604
Ben Murdoch8029a772010-11-16 11:58:21 +00002605 public void setupAutoFill(Message message) {
2606 // Open the settings activity at the AutoFill profile fragment so that
2607 // the user can create a new profile. When they return, we will dispatch
2608 // the message so that we can autofill the form using their new profile.
2609 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2610 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2611 AutoFillSettingsFragment.class.getName());
2612 mAutoFillSetupMessage = message;
2613 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2614 }
John Reckb3417f02011-01-14 11:01:05 -08002615
2616 @Override
2617 public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
2618 mOptionsMenuHandler = handler;
2619 }
2620
2621 @Override
2622 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
2623 if (mOptionsMenuHandler == handler) {
2624 mOptionsMenuHandler = null;
2625 }
2626 }
2627
Narayan Kamath5119edd2011-02-23 15:49:17 +00002628 @Override
2629 public void registerDropdownChangeListener(DropdownChangeListener d) {
2630 mUi.registerDropdownChangeListener(d);
2631 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002632}