blob: ee40a93ca8377bca4001e5e2aabfff767fb61cd7 [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
Michael Kolb8233fac2010-10-26 16:08:53 -070019import android.app.Activity;
20import android.app.DownloadManager;
21import android.app.SearchManager;
22import android.content.ClipboardManager;
23import android.content.ContentProvider;
24import android.content.ContentProviderClient;
25import android.content.ContentResolver;
26import android.content.ContentValues;
27import android.content.Context;
28import android.content.Intent;
29import android.content.pm.PackageManager;
30import android.content.pm.ResolveInfo;
31import android.content.res.Configuration;
Leon Scroggins1961ed22010-12-07 15:22:21 -050032import android.database.ContentObserver;
Michael Kolb8233fac2010-10-26 16:08:53 -070033import android.database.Cursor;
34import android.database.sqlite.SQLiteDatabase;
Michael Kolb8233fac2010-10-26 16:08:53 -070035import android.graphics.Bitmap;
36import android.graphics.Canvas;
37import android.graphics.Picture;
38import android.net.Uri;
39import android.net.http.SslError;
40import android.os.AsyncTask;
41import android.os.Bundle;
Leon Scrogginsac993842011-02-02 12:54:07 -050042import android.os.Environment;
Michael Kolb8233fac2010-10-26 16:08:53 -070043import android.os.Handler;
44import android.os.Message;
45import android.os.PowerManager;
46import android.os.PowerManager.WakeLock;
Ben Murdoch8029a772010-11-16 11:58:21 +000047import android.preference.PreferenceActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -070048import android.provider.Browser;
49import android.provider.BrowserContract;
Michael Kolb8233fac2010-10-26 16:08:53 -070050import android.provider.BrowserContract.Images;
51import android.provider.ContactsContract;
52import android.provider.ContactsContract.Intents.Insert;
Michael Kolbcfa3af52010-12-14 10:36:11 -080053import android.speech.RecognizerIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070054import android.text.TextUtils;
55import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080056import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070057import android.view.ActionMode;
58import android.view.ContextMenu;
59import android.view.ContextMenu.ContextMenuInfo;
60import android.view.Gravity;
61import android.view.KeyEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070062import android.view.Menu;
63import android.view.MenuInflater;
64import android.view.MenuItem;
65import android.view.MenuItem.OnMenuItemClickListener;
66import android.view.View;
67import android.webkit.CookieManager;
68import android.webkit.CookieSyncManager;
69import android.webkit.HttpAuthHandler;
70import android.webkit.SslErrorHandler;
71import android.webkit.ValueCallback;
72import android.webkit.WebChromeClient;
73import android.webkit.WebIconDatabase;
74import android.webkit.WebSettings;
75import android.webkit.WebView;
Leon Scrogginsac993842011-02-02 12:54:07 -050076import android.widget.Toast;
Michael Kolb8233fac2010-10-26 16:08:53 -070077
Michael Kolb4bd767d2011-05-27 11:33:55 -070078import com.android.browser.IntentHandler.UrlData;
79import com.android.browser.UI.DropdownChangeListener;
80import com.android.browser.provider.BrowserProvider;
81import com.android.browser.search.SearchEngine;
82import com.android.common.Search;
83
Michael Kolb8233fac2010-10-26 16:08:53 -070084import java.io.ByteArrayOutputStream;
85import java.io.File;
86import java.net.URLEncoder;
87import java.util.Calendar;
88import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -080089import java.util.List;
Michael Kolb8233fac2010-10-26 16:08:53 -070090
91/**
92 * Controller for browser
93 */
94public class Controller
95 implements WebViewController, UiController {
96
97 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -080098 private static final String SEND_APP_ID_EXTRA =
99 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
Michael Kolba4261fd2011-05-05 11:27:37 -0700100 private static final String INCOGNITO_URI = "browser:incognito";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800101
Michael Kolb8233fac2010-10-26 16:08:53 -0700102
103 // public message ids
104 public final static int LOAD_URL = 1001;
105 public final static int STOP_LOAD = 1002;
106
107 // Message Ids
108 private static final int FOCUS_NODE_HREF = 102;
109 private static final int RELEASE_WAKELOCK = 107;
110
111 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
112
113 private static final int OPEN_BOOKMARKS = 201;
114
115 private static final int EMPTY_MENU = -1;
116
Michael Kolb8233fac2010-10-26 16:08:53 -0700117 // activity requestCode
118 final static int PREFERENCES_PAGE = 3;
119 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000120 final static int AUTOFILL_SETUP = 5;
121
Michael Kolb8233fac2010-10-26 16:08:53 -0700122 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
123
124 // As the ids are dynamically created, we can't guarantee that they will
125 // be in sequence, so this static array maps ids to a window number.
126 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
127 { R.id.window_one_menu_id, R.id.window_two_menu_id,
128 R.id.window_three_menu_id, R.id.window_four_menu_id,
129 R.id.window_five_menu_id, R.id.window_six_menu_id,
130 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
131
132 // "source" parameter for Google search through search key
133 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
134 // "source" parameter for Google search through simplily type
135 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
136
Guang Zhu9e78f512011-05-04 11:45:11 -0700137 // "no-crash-recovery" parameter in intetnt to suppress crash recovery
138 final static String NO_CRASH_RECOVERY = "no-crash-recovery";
139
Michael Kolb8233fac2010-10-26 16:08:53 -0700140 private Activity mActivity;
141 private UI mUi;
142 private TabControl mTabControl;
143 private BrowserSettings mSettings;
144 private WebViewFactory mFactory;
John Reckb3417f02011-01-14 11:01:05 -0800145 private OptionsMenuHandler mOptionsMenuHandler = null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700146
147 private WakeLock mWakeLock;
148
149 private UrlHandler mUrlHandler;
150 private UploadHandler mUploadHandler;
151 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700152 private PageDialogsHandler mPageDialogsHandler;
153 private NetworkStateHandler mNetworkHandler;
154
Ben Murdoch8029a772010-11-16 11:58:21 +0000155 private Message mAutoFillSetupMessage;
156
Michael Kolb8233fac2010-10-26 16:08:53 -0700157 private boolean mShouldShowErrorConsole;
158
159 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
160
161 // FIXME, temp address onPrepareMenu performance problem.
162 // When we move everything out of view, we should rewrite this.
163 private int mCurrentMenuState = 0;
164 private int mMenuState = R.id.MAIN_MENU;
165 private int mOldMenuState = EMPTY_MENU;
166 private Menu mCachedMenu;
167
Michael Kolb8233fac2010-10-26 16:08:53 -0700168 private boolean mMenuIsDown;
169
170 // For select and find, we keep track of the ActionMode so that
171 // finish() can be called as desired.
172 private ActionMode mActionMode;
173
174 /**
175 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
176 * of whether the configuration has changed. The first onMenuOpened call
177 * after a configuration change is simply a reopening of the same menu
178 * (i.e. mIconView did not change).
179 */
180 private boolean mConfigChanged;
181
182 /**
183 * Keeps track of whether the options menu is open. This is important in
184 * determining whether to show or hide the title bar overlay
185 */
186 private boolean mOptionsMenuOpen;
187
188 /**
189 * Whether or not the options menu is in its bigger, popup menu form. When
190 * true, we want the title bar overlay to be gone. When false, we do not.
191 * Only meaningful if mOptionsMenuOpen is true.
192 */
193 private boolean mExtendedMenuOpen;
194
195 private boolean mInLoad;
196
197 private boolean mActivityPaused = true;
198 private boolean mLoadStopped;
199
200 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500201 // Checks to see when the bookmarks database has changed, and updates the
202 // Tabs' notion of whether they represent bookmarked sites.
203 private ContentObserver mBookmarksObserver;
John Reck0ebd3ac2010-12-09 11:14:04 -0800204 private DataController mDataController;
John Reck847b5322011-04-14 17:02:18 -0700205 private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700206
207 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
208 @Override
209 public Void doInBackground(File... files) {
210 if (files != null) {
211 for (File f : files) {
212 if (!f.delete()) {
213 Log.e(LOGTAG, f.getPath() + " was not deleted");
214 }
215 }
216 }
217 return null;
218 }
219 }
220
221 public Controller(Activity browser) {
222 mActivity = browser;
223 mSettings = BrowserSettings.getInstance();
John Reck0ebd3ac2010-12-09 11:14:04 -0800224 mDataController = DataController.getInstance(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700225 mTabControl = new TabControl(this);
226 mSettings.setController(this);
John Reck847b5322011-04-14 17:02:18 -0700227 mCrashRecoveryHandler = new CrashRecoveryHandler(this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700228
229 mUrlHandler = new UrlHandler(this);
230 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700231 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
232
233 PowerManager pm = (PowerManager) mActivity
234 .getSystemService(Context.POWER_SERVICE);
235 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
236
237 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500238 mBookmarksObserver = new ContentObserver(mHandler) {
239 @Override
240 public void onChange(boolean selfChange) {
241 int size = mTabControl.getTabCount();
242 for (int i = 0; i < size; i++) {
243 mTabControl.getTab(i).updateBookmarkedStatus();
244 }
245 }
246
247 };
248 browser.getContentResolver().registerContentObserver(
249 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700250
251 mNetworkHandler = new NetworkStateHandler(mActivity, this);
252 // Start watching the default geolocation permissions
253 mSystemAllowGeolocationOrigins =
254 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
255 mSystemAllowGeolocationOrigins.start();
256
257 retainIconsOnStartup();
258 }
259
Patrick Scott7d50a932011-02-04 09:27:26 -0500260 void start(final Bundle icicle, final Intent intent) {
Guang Zhu9e78f512011-05-04 11:45:11 -0700261 boolean noCrashRecovery = intent.getBooleanExtra(NO_CRASH_RECOVERY, false);
262 if (icicle != null || noCrashRecovery) {
John Reck847b5322011-04-14 17:02:18 -0700263 mCrashRecoveryHandler.clearState();
264 doStart(icicle, intent);
265 } else {
266 mCrashRecoveryHandler.startRecovery(intent);
267 }
268 }
269
270 void doStart(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700271 // Unless the last browser usage was within 24 hours, destroy any
272 // remaining incognito tabs.
273
274 Calendar lastActiveDate = icicle != null ?
275 (Calendar) icicle.getSerializable("lastActiveDate") : null;
276 Calendar today = Calendar.getInstance();
277 Calendar yesterday = Calendar.getInstance();
278 yesterday.add(Calendar.DATE, -1);
279
Patrick Scott7d50a932011-02-04 09:27:26 -0500280 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700281 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800282 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700283
Patrick Scott7d50a932011-02-04 09:27:26 -0500284 // Find out if we will restore any state and remember the tab.
Michael Kolbc831b632011-05-11 09:30:34 -0700285 final long currentTabId =
Patrick Scott7d50a932011-02-04 09:27:26 -0500286 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000287
Michael Kolbc831b632011-05-11 09:30:34 -0700288 if (currentTabId == -1) {
Patrick Scott7d50a932011-02-04 09:27:26 -0500289 // Not able to restore so we go ahead and clear session cookies. We
290 // must do this before trying to login the user as we don't want to
291 // clear any session cookies set during login.
292 CookieManager.getInstance().removeSessionCookie();
293 }
294
Patrick Scottd43e75a2011-03-14 14:47:23 -0400295 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500296 new Runnable() {
297 @Override public void run() {
Michael Kolbc831b632011-05-11 09:30:34 -0700298 onPreloginFinished(icicle, intent, currentTabId, restoreIncognitoTabs);
Patrick Scott7d50a932011-02-04 09:27:26 -0500299 }
300 });
301 }
302
Michael Kolbc831b632011-05-11 09:30:34 -0700303 private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId,
Patrick Scott7d50a932011-02-04 09:27:26 -0500304 boolean restoreIncognitoTabs) {
Michael Kolbc831b632011-05-11 09:30:34 -0700305 if (currentTabId == -1) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700306 final Bundle extra = intent.getExtras();
307 // Create an initial tab.
308 // If the intent is ACTION_VIEW and data is not null, the Browser is
309 // invoked to view the content by another application. In this case,
310 // the tab will be close when exit.
311 UrlData urlData = mIntentHandler.getUrlDataFromIntent(intent);
Michael Kolb7bcafde2011-05-09 13:55:59 -0700312 Tab t = null;
313 if (urlData.isEmpty()) {
314 t = openTabToHomePage();
315 } else {
316 t = openTab(urlData);
317 }
318 if (t != null) {
319 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
320 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700321 WebView webView = t.getWebView();
322 if (extra != null) {
323 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
324 if (scale > 0 && scale <= 1000) {
325 webView.setInitialScale(scale);
326 }
327 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700328 } else {
Michael Kolbc831b632011-05-11 09:30:34 -0700329 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
Patrick Scott7d50a932011-02-04 09:27:26 -0500330 mUi.needsRestoreAllTabs());
Michael Kolb1bf23132010-11-19 12:55:12 -0800331 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700332 // TabControl.restoreState() will create a new tab even if
333 // restoring the state fails.
334 setActiveTab(mTabControl.getCurrentTab());
335 }
336 // clear up the thumbnail directory, which is no longer used;
337 // ideally this should only be run once after an upgrade from
338 // a previous version of the browser
339 new ClearThumbnails().execute(mTabControl.getThumbnailDir()
340 .listFiles());
341 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700342 String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb8233fac2010-10-26 16:08:53 -0700343 if (jsFlags.trim().length() != 0) {
344 getCurrentWebView().setJsFlags(jsFlags);
345 }
John Reck439c9a52010-12-14 10:04:39 -0800346 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
347 bookmarksOrHistoryPicker(false);
348 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700349 }
350
351 void setWebViewFactory(WebViewFactory factory) {
352 mFactory = factory;
353 }
354
Michael Kolb1514bb72010-11-22 09:11:48 -0800355 @Override
356 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700357 return mFactory;
358 }
359
360 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800361 public void onSetWebView(Tab tab, WebView view) {
362 mUi.onSetWebView(tab, view);
363 }
364
365 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800366 public void createSubWindow(Tab tab) {
367 endActionMode();
368 WebView mainView = tab.getWebView();
369 WebView subView = mFactory.createWebView((mainView == null)
370 ? false
371 : mainView.isPrivateBrowsingEnabled());
372 mUi.createSubWindow(tab, subView);
373 }
374
375 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700376 public Activity getActivity() {
377 return mActivity;
378 }
379
380 void setUi(UI ui) {
381 mUi = ui;
382 }
383
384 BrowserSettings getSettings() {
385 return mSettings;
386 }
387
388 IntentHandler getIntentHandler() {
389 return mIntentHandler;
390 }
391
392 @Override
393 public UI getUi() {
394 return mUi;
395 }
396
397 int getMaxTabs() {
398 return mActivity.getResources().getInteger(R.integer.max_tabs);
399 }
400
401 @Override
402 public TabControl getTabControl() {
403 return mTabControl;
404 }
405
Michael Kolb1bf23132010-11-19 12:55:12 -0800406 @Override
407 public List<Tab> getTabs() {
408 return mTabControl.getTabs();
409 }
410
Michael Kolb8233fac2010-10-26 16:08:53 -0700411 // Open the icon database and retain all the icons for visited sites.
Ben Murdoch9446b932010-11-25 16:20:14 +0000412 // This is done on a background thread so as not to stall startup.
Michael Kolb8233fac2010-10-26 16:08:53 -0700413 private void retainIconsOnStartup() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000414 // WebIconDatabase needs to be retrieved on the UI thread so that if
415 // it has not been created successfully yet the Handler is started on the
416 // UI thread.
417 new RetainIconsOnStartupTask(WebIconDatabase.getInstance()).execute();
418 }
419
420 private class RetainIconsOnStartupTask extends AsyncTask<Void, Void, Void> {
421 private WebIconDatabase mDb;
422
423 public RetainIconsOnStartupTask(WebIconDatabase db) {
424 mDb = db;
425 }
426
John Recka00cbbd2010-12-16 12:38:19 -0800427 @Override
Ben Murdoch9446b932010-11-25 16:20:14 +0000428 protected Void doInBackground(Void... unused) {
429 mDb.open(mActivity.getDir("icons", 0).getPath());
430 Cursor c = null;
431 try {
432 c = Browser.getAllBookmarks(mActivity.getContentResolver());
433 if (c.moveToFirst()) {
434 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
435 do {
436 String url = c.getString(urlIndex);
437 mDb.retainIconForPageUrl(url);
438 } while (c.moveToNext());
439 }
440 } catch (IllegalStateException e) {
441 Log.e(LOGTAG, "retainIconsOnStartup", e);
442 } finally {
443 if (c != null) c.close();
Michael Kolb8233fac2010-10-26 16:08:53 -0700444 }
Ben Murdoch9446b932010-11-25 16:20:14 +0000445
446 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700447 }
448 }
449
450 private void startHandler() {
451 mHandler = new Handler() {
452
453 @Override
454 public void handleMessage(Message msg) {
455 switch (msg.what) {
456 case OPEN_BOOKMARKS:
457 bookmarksOrHistoryPicker(false);
458 break;
459 case FOCUS_NODE_HREF:
460 {
461 String url = (String) msg.getData().get("url");
462 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500463 String src = (String) msg.getData().get("src");
464 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700465 if (TextUtils.isEmpty(url)) {
466 break;
467 }
468 HashMap focusNodeMap = (HashMap) msg.obj;
469 WebView view = (WebView) focusNodeMap.get("webview");
470 // Only apply the action if the top window did not change.
471 if (getCurrentTopWebView() != view) {
472 break;
473 }
474 switch (msg.arg1) {
475 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -0700476 loadUrlFromContext(getCurrentTopWebView(), url);
477 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500478 case R.id.view_image_context_menu_id:
479 loadUrlFromContext(getCurrentTopWebView(), src);
480 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500481 case R.id.open_newtab_context_menu_id:
482 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb7bcafde2011-05-09 13:55:59 -0700483 final Tab newTab =
484 openTab(url,
485 (parent != null)
486 && parent.isPrivateBrowsingEnabled(),
487 !mSettings.openInBackground(),
488 true);
Leon Scroggins026f2542010-11-22 13:26:12 -0500489 if (newTab != null && newTab != parent) {
490 parent.addChildTab(newTab);
491 }
492 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700493 case R.id.copy_link_context_menu_id:
494 copy(url);
495 break;
496 case R.id.save_link_context_menu_id:
497 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500498 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000499 mActivity, url, null, null, null,
500 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700501 break;
502 }
503 break;
504 }
505
506 case LOAD_URL:
507 loadUrlFromContext(getCurrentTopWebView(), (String) msg.obj);
508 break;
509
510 case STOP_LOAD:
511 stopLoading();
512 break;
513
514 case RELEASE_WAKELOCK:
515 if (mWakeLock.isHeld()) {
516 mWakeLock.release();
517 // if we reach here, Browser should be still in the
518 // background loading after WAKELOCK_TIMEOUT (5-min).
519 // To avoid burning the battery, stop loading.
520 mTabControl.stopAllLoading();
521 }
522 break;
523
524 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800525 Tab tab = (Tab) msg.obj;
526 if (tab != null) {
527 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700528 }
529 break;
530 }
531 }
532 };
533
534 }
535
Michael Kolbba99c5d2010-11-29 14:57:41 -0800536 @Override
537 public void shareCurrentPage() {
538 shareCurrentPage(mTabControl.getCurrentTab());
539 }
540
541 private void shareCurrentPage(Tab tab) {
542 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800543 sharePage(mActivity, tab.getTitle(),
544 tab.getUrl(), tab.getFavicon(),
545 createScreenshot(tab.getWebView(),
546 getDesiredThumbnailWidth(mActivity),
547 getDesiredThumbnailHeight(mActivity)));
548 }
549 }
550
Michael Kolb8233fac2010-10-26 16:08:53 -0700551 /**
552 * Share a page, providing the title, url, favicon, and a screenshot. Uses
553 * an {@link Intent} to launch the Activity chooser.
554 * @param c Context used to launch a new Activity.
555 * @param title Title of the page. Stored in the Intent with
556 * {@link Intent#EXTRA_SUBJECT}
557 * @param url URL of the page. Stored in the Intent with
558 * {@link Intent#EXTRA_TEXT}
559 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
560 * with {@link Browser#EXTRA_SHARE_FAVICON}
561 * @param screenshot Bitmap of a screenshot of the page. Stored in the
562 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
563 */
564 static final void sharePage(Context c, String title, String url,
565 Bitmap favicon, Bitmap screenshot) {
566 Intent send = new Intent(Intent.ACTION_SEND);
567 send.setType("text/plain");
568 send.putExtra(Intent.EXTRA_TEXT, url);
569 send.putExtra(Intent.EXTRA_SUBJECT, title);
570 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
571 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
572 try {
573 c.startActivity(Intent.createChooser(send, c.getString(
574 R.string.choosertitle_sharevia)));
575 } catch(android.content.ActivityNotFoundException ex) {
576 // if no app handles it, do nothing
577 }
578 }
579
580 private void copy(CharSequence text) {
581 ClipboardManager cm = (ClipboardManager) mActivity
582 .getSystemService(Context.CLIPBOARD_SERVICE);
583 cm.setText(text);
584 }
585
586 // lifecycle
587
588 protected void onConfgurationChanged(Configuration config) {
589 mConfigChanged = true;
590 if (mPageDialogsHandler != null) {
591 mPageDialogsHandler.onConfigurationChanged(config);
592 }
593 mUi.onConfigurationChanged(config);
594 }
595
596 @Override
597 public void handleNewIntent(Intent intent) {
598 mIntentHandler.onNewIntent(intent);
599 }
600
601 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800602 if (mUi.isCustomViewShowing()) {
603 hideCustomView();
604 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700605 if (mActivityPaused) {
606 Log.e(LOGTAG, "BrowserActivity is already paused.");
607 return;
608 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700609 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800610 Tab tab = mTabControl.getCurrentTab();
611 if (tab != null) {
612 tab.pause();
613 if (!pauseWebViewTimers(tab)) {
614 mWakeLock.acquire();
615 mHandler.sendMessageDelayed(mHandler
616 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
617 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700618 }
619 mUi.onPause();
620 mNetworkHandler.onPause();
621
622 WebView.disablePlatformNotifications();
John Reck847b5322011-04-14 17:02:18 -0700623 mCrashRecoveryHandler.clearState();
Michael Kolb8233fac2010-10-26 16:08:53 -0700624 }
625
626 void onSaveInstanceState(Bundle outState) {
627 // the default implementation requires each view to have an id. As the
628 // browser handles the state itself and it doesn't use id for the views,
629 // don't call the default implementation. Otherwise it will trigger the
630 // warning like this, "couldn't save which view has focus because the
631 // focused view XXX has no id".
632
633 // Save all the tabs
634 mTabControl.saveState(outState);
635 // Save time so that we know how old incognito tabs (if any) are.
636 outState.putSerializable("lastActiveDate", Calendar.getInstance());
637 }
638
639 void onResume() {
640 if (!mActivityPaused) {
641 Log.e(LOGTAG, "BrowserActivity is already resumed.");
642 return;
643 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700644 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800645 Tab current = mTabControl.getCurrentTab();
646 if (current != null) {
647 current.resume();
648 resumeWebViewTimers(current);
649 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700650 if (mWakeLock.isHeld()) {
651 mHandler.removeMessages(RELEASE_WAKELOCK);
652 mWakeLock.release();
653 }
654 mUi.onResume();
655 mNetworkHandler.onResume();
656 WebView.enablePlatformNotifications();
657 }
658
Michael Kolb70976932010-11-30 11:34:01 -0800659 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800660 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800661 * @param tab guaranteed non-null
662 */
663 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700664 boolean inLoad = tab.inPageLoad();
665 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
666 CookieSyncManager.getInstance().startSync();
667 WebView w = tab.getWebView();
668 if (w != null) {
669 w.resumeTimers();
670 }
671 }
672 }
673
Michael Kolb70976932010-11-30 11:34:01 -0800674 /**
675 * Pause all WebView timers using the WebView of the given tab
676 * @param tab
677 * @return true if the timers are paused or tab is null
678 */
679 private boolean pauseWebViewTimers(Tab tab) {
680 if (tab == null) {
681 return true;
682 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700683 CookieSyncManager.getInstance().stopSync();
684 WebView w = getCurrentWebView();
685 if (w != null) {
686 w.pauseTimers();
687 }
688 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700689 }
Michael Kolb70976932010-11-30 11:34:01 -0800690 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700691 }
692
693 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800694 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700695 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
696 mUploadHandler = null;
697 }
698 if (mTabControl == null) return;
699 mUi.onDestroy();
700 // Remove the current tab and sub window
701 Tab t = mTabControl.getCurrentTab();
702 if (t != null) {
703 dismissSubWindow(t);
704 removeTab(t);
705 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500706 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700707 // Destroy all the tabs
708 mTabControl.destroy();
709 WebIconDatabase.getInstance().close();
710 // Stop watching the default geolocation permissions
711 mSystemAllowGeolocationOrigins.stop();
712 mSystemAllowGeolocationOrigins = null;
713 }
714
715 protected boolean isActivityPaused() {
716 return mActivityPaused;
717 }
718
719 protected void onLowMemory() {
720 mTabControl.freeMemory();
721 }
722
723 @Override
724 public boolean shouldShowErrorConsole() {
725 return mShouldShowErrorConsole;
726 }
727
728 protected void setShouldShowErrorConsole(boolean show) {
729 if (show == mShouldShowErrorConsole) {
730 // Nothing to do.
731 return;
732 }
733 mShouldShowErrorConsole = show;
734 Tab t = mTabControl.getCurrentTab();
735 if (t == null) {
736 // There is no current tab so we cannot toggle the error console
737 return;
738 }
739 mUi.setShouldShowErrorConsole(t, show);
740 }
741
742 @Override
743 public void stopLoading() {
744 mLoadStopped = true;
745 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700746 WebView w = getCurrentTopWebView();
747 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700748 mUi.onPageStopped(tab);
749 }
750
751 boolean didUserStopLoading() {
752 return mLoadStopped;
753 }
754
755 // WebViewController
756
757 @Override
John Reck324d4402011-01-11 16:56:42 -0800758 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700759
760 // We've started to load a new page. If there was a pending message
761 // to save a screenshot then we will now take the new page and save
762 // an incorrect screenshot. Therefore, remove any pending thumbnail
763 // messages from the queue.
764 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800765 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700766
767 // reset sync timer to avoid sync starts during loading a page
768 CookieSyncManager.getInstance().resetSync();
769
770 if (!mNetworkHandler.isNetworkUp()) {
771 view.setNetworkAvailable(false);
772 }
773
774 // when BrowserActivity just starts, onPageStarted may be called before
775 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
776 // to start the timer. As we won't switch tabs while an activity is in
777 // pause state, we can ensure calling resume and pause in pair.
778 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800779 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700780 }
781 mLoadStopped = false;
782 if (!mNetworkHandler.isNetworkUp()) {
783 mNetworkHandler.createAndShowNetworkDialog();
784 }
785 endActionMode();
786
John Reck30c714c2010-12-16 17:30:34 -0800787 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700788
John Reck324d4402011-01-11 16:56:42 -0800789 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700790 // update the bookmark database for favicon
791 maybeUpdateFavicon(tab, null, url, favicon);
792
793 Performance.tracePageStart(url);
794
795 // Performance probe
796 if (false) {
797 Performance.onPageStarted();
798 }
799
800 }
801
802 @Override
John Reck324d4402011-01-11 16:56:42 -0800803 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800804 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800805 if (!tab.isPrivateBrowsingEnabled()
806 && !TextUtils.isEmpty(tab.getUrl())) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700807 if (tab.inForeground() && !didUserStopLoading()
808 || !tab.inForeground()) {
809 // Only update the bookmark screenshot if the user did not
810 // cancel the load early.
811 mHandler.sendMessageDelayed(mHandler.obtainMessage(
John Reck34ef2672011-02-10 11:30:55 -0800812 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
Michael Kolb8233fac2010-10-26 16:08:53 -0700813 500);
814 }
815 }
816 // pause the WebView timer and release the wake lock if it is finished
817 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800818 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700819 if (mWakeLock.isHeld()) {
820 mHandler.removeMessages(RELEASE_WAKELOCK);
821 mWakeLock.release();
822 }
823 }
824 // Performance probe
825 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800826 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700827 }
828
829 Performance.tracePageFinished();
830 }
831
832 @Override
John Reck30c714c2010-12-16 17:30:34 -0800833 public void onProgressChanged(Tab tab) {
834 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700835
836 if (newProgress == 100) {
837 CookieSyncManager.getInstance().sync();
838 // onProgressChanged() may continue to be called after the main
839 // frame has finished loading, as any remaining sub frames continue
840 // to load. We'll only get called once though with newProgress as
841 // 100 when everything is loaded. (onPageFinished is called once
842 // when the main frame completes loading regardless of the state of
843 // any sub frames so calls to onProgressChanges may continue after
844 // onPageFinished has executed)
845 if (mInLoad) {
846 mInLoad = false;
847 updateInLoadMenuItems(mCachedMenu);
848 }
849 } else {
850 if (!mInLoad) {
851 // onPageFinished may have already been called but a subframe is
852 // still loading and updating the progress. Reset mInLoad and
853 // update the menu items.
854 mInLoad = true;
855 updateInLoadMenuItems(mCachedMenu);
856 }
857 }
John Reck30c714c2010-12-16 17:30:34 -0800858 mUi.onProgressChanged(tab);
859 }
860
861 @Override
862 public void onUpdatedLockIcon(Tab tab) {
863 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700864 }
865
866 @Override
867 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800868 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800869 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800870 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700871 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
872 return;
873 }
874 // Update the title in the history database if not in private browsing mode
875 if (!tab.isPrivateBrowsingEnabled()) {
John Reck0ebd3ac2010-12-09 11:14:04 -0800876 mDataController.updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700877 }
878 }
879
880 @Override
881 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800882 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700883 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
884 }
885
886 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800887 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
888 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700889 }
890
891 @Override
892 public boolean shouldOverrideKeyEvent(KeyEvent event) {
893 if (mMenuIsDown) {
894 // only check shortcut key when MENU is held
895 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
896 event);
897 } else {
898 return false;
899 }
900 }
901
902 @Override
903 public void onUnhandledKeyEvent(KeyEvent event) {
904 if (!isActivityPaused()) {
905 if (event.getAction() == KeyEvent.ACTION_DOWN) {
906 mActivity.onKeyDown(event.getKeyCode(), event);
907 } else {
908 mActivity.onKeyUp(event.getKeyCode(), event);
909 }
910 }
911 }
912
913 @Override
John Reck324d4402011-01-11 16:56:42 -0800914 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700915 // Don't save anything in private browsing mode
916 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800917 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700918
John Reck324d4402011-01-11 16:56:42 -0800919 if (TextUtils.isEmpty(url)
920 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700921 return;
922 }
John Reck0ebd3ac2010-12-09 11:14:04 -0800923 mDataController.updateVisitedHistory(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700924 WebIconDatabase.getInstance().retainIconForPageUrl(url);
John Reck847b5322011-04-14 17:02:18 -0700925 if (!mActivityPaused) {
926 // Since we clear the state in onPause, don't backup the current
927 // state if we are already paused
928 mCrashRecoveryHandler.backupState();
929 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700930 }
931
932 @Override
933 public void getVisitedHistory(final ValueCallback<String[]> callback) {
934 AsyncTask<Void, Void, String[]> task =
935 new AsyncTask<Void, Void, String[]>() {
936 @Override
937 public String[] doInBackground(Void... unused) {
938 return Browser.getVisitedHistory(mActivity.getContentResolver());
939 }
940 @Override
941 public void onPostExecute(String[] result) {
942 callback.onReceiveValue(result);
943 }
944 };
945 task.execute();
946 }
947
948 @Override
949 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
950 final HttpAuthHandler handler, final String host,
951 final String realm) {
952 String username = null;
953 String password = null;
954
955 boolean reuseHttpAuthUsernamePassword
956 = handler.useHttpAuthUsernamePassword();
957
958 if (reuseHttpAuthUsernamePassword && view != null) {
959 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
960 if (credentials != null && credentials.length == 2) {
961 username = credentials[0];
962 password = credentials[1];
963 }
964 }
965
966 if (username != null && password != null) {
967 handler.proceed(username, password);
968 } else {
969 if (tab.inForeground()) {
970 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
971 } else {
972 handler.cancel();
973 }
974 }
975 }
976
977 @Override
978 public void onDownloadStart(Tab tab, String url, String userAgent,
979 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000980 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -0500981 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000982 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
983 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700984 // This Tab was opened for the sole purpose of downloading a
985 // file. Remove it.
986 if (tab == mTabControl.getCurrentTab()) {
987 // In this case, the Tab is still on top.
988 goBackOnePageOrQuit();
989 } else {
990 // In this case, it is not.
991 closeTab(tab);
992 }
993 }
994 }
995
996 @Override
997 public Bitmap getDefaultVideoPoster() {
998 return mUi.getDefaultVideoPoster();
999 }
1000
1001 @Override
1002 public View getVideoLoadingProgressView() {
1003 return mUi.getVideoLoadingProgressView();
1004 }
1005
1006 @Override
1007 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1008 SslError error) {
1009 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1010 }
1011
Patrick Scott92066772011-03-10 08:46:27 -05001012 @Override
1013 public void showAutoLogin(Tab tab) {
1014 assert tab.inForeground();
1015 // Update the title bar to show the auto-login request.
1016 mUi.showAutoLogin(tab);
1017 }
1018
1019 @Override
1020 public void hideAutoLogin(Tab tab) {
1021 assert tab.inForeground();
1022 mUi.hideAutoLogin(tab);
1023 }
1024
Michael Kolb8233fac2010-10-26 16:08:53 -07001025 // helper method
1026
1027 /*
1028 * Update the favorites icon if the private browsing isn't enabled and the
1029 * icon is valid.
1030 */
1031 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1032 final String url, Bitmap favicon) {
1033 if (favicon == null) {
1034 return;
1035 }
1036 if (!tab.isPrivateBrowsingEnabled()) {
1037 Bookmarks.updateFavicon(mActivity
1038 .getContentResolver(), originalUrl, url, favicon);
1039 }
1040 }
1041
Leon Scroggins4cd97792010-12-03 15:31:56 -05001042 @Override
1043 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001044 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001045 mUi.bookmarkedStatusHasChanged(tab);
1046 }
1047
Michael Kolb8233fac2010-10-26 16:08:53 -07001048 // end WebViewController
1049
1050 protected void pageUp() {
1051 getCurrentTopWebView().pageUp(false);
1052 }
1053
1054 protected void pageDown() {
1055 getCurrentTopWebView().pageDown(false);
1056 }
1057
1058 // callback from phone title bar
1059 public void editUrl() {
1060 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001061 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001062 }
1063
Michael Kolbcfa3af52010-12-14 10:36:11 -08001064 public void startVoiceSearch() {
1065 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1066 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1067 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1068 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1069 mActivity.getComponentName().flattenToString());
1070 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001071 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001072 mActivity.startActivity(intent);
1073 }
1074
Michael Kolb11d19782011-03-20 10:17:40 -07001075 @Override
1076 public void activateVoiceSearchMode(String title, List<String> results) {
1077 mUi.showVoiceTitleBar(title, results);
Michael Kolb8233fac2010-10-26 16:08:53 -07001078 }
1079
1080 public void revertVoiceSearchMode(Tab tab) {
1081 mUi.revertVoiceTitleBar(tab);
1082 }
1083
Michael Kolb736990c2011-03-20 10:01:20 -07001084 public boolean supportsVoiceSearch() {
John Reck35e9dd62011-04-25 09:01:54 -07001085 SearchEngine searchEngine = getSettings().getSearchEngine();
Michael Kolb736990c2011-03-20 10:01:20 -07001086 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1087 }
1088
Michael Kolb8233fac2010-10-26 16:08:53 -07001089 public void showCustomView(Tab tab, View view,
1090 WebChromeClient.CustomViewCallback callback) {
1091 if (tab.inForeground()) {
1092 if (mUi.isCustomViewShowing()) {
1093 callback.onCustomViewHidden();
1094 return;
1095 }
1096 mUi.showCustomView(view, callback);
1097 // Save the menu state and set it to empty while the custom
1098 // view is showing.
1099 mOldMenuState = mMenuState;
1100 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001101 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001102 }
1103 }
1104
1105 @Override
1106 public void hideCustomView() {
1107 if (mUi.isCustomViewShowing()) {
1108 mUi.onHideCustomView();
1109 // Reset the old menu state.
1110 mMenuState = mOldMenuState;
1111 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001112 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001113 }
1114 }
1115
1116 protected void onActivityResult(int requestCode, int resultCode,
1117 Intent intent) {
1118 if (getCurrentTopWebView() == null) return;
1119 switch (requestCode) {
1120 case PREFERENCES_PAGE:
1121 if (resultCode == Activity.RESULT_OK && intent != null) {
1122 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001123 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001124 mTabControl.removeParentChildRelationShips();
1125 }
1126 }
1127 break;
1128 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001129 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001130 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001131 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001132 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001133 case AUTOFILL_SETUP:
1134 // Determine whether a profile was actually set up or not
1135 // and if so, send the message back to the WebTextView to
1136 // fill the form with the new profile.
1137 if (getSettings().getAutoFillProfile() != null) {
1138 mAutoFillSetupMessage.sendToTarget();
1139 mAutoFillSetupMessage = null;
1140 }
1141 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001142 default:
1143 break;
1144 }
1145 getCurrentTopWebView().requestFocus();
1146 }
1147
1148 /**
1149 * Open the Go page.
1150 * @param startWithHistory If true, open starting on the history tab.
1151 * Otherwise, start with the bookmarks tab.
1152 */
1153 @Override
1154 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1155 if (mTabControl.getCurrentWebView() == null) {
1156 return;
1157 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001158 // clear action mode
1159 if (isInCustomActionMode()) {
1160 endActionMode();
1161 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001162 Bundle extras = new Bundle();
1163 // Disable opening in a new window if we have maxed out the windows
1164 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1165 !mTabControl.canCreateNewTab());
1166 mUi.showComboView(startWithHistory, extras);
1167 }
1168
1169 // combo view callbacks
1170
1171 /**
1172 * callback from ComboPage when clear history is requested
1173 */
1174 public void onRemoveParentChildRelationships() {
1175 mTabControl.removeParentChildRelationShips();
1176 }
1177
1178 /**
1179 * callback from ComboPage when bookmark/history selection
1180 */
1181 @Override
1182 public void onUrlSelected(String url, boolean newTab) {
1183 removeComboView();
1184 if (!TextUtils.isEmpty(url)) {
1185 if (newTab) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07001186 final Tab parent = mTabControl.getCurrentTab();
1187 openTab(url,
1188 (parent != null) && parent.isPrivateBrowsingEnabled(),
1189 !mSettings.openInBackground(),
1190 true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001191 } else {
1192 final Tab currentTab = mTabControl.getCurrentTab();
1193 dismissSubWindow(currentTab);
1194 loadUrl(getCurrentTopWebView(), url);
1195 }
1196 }
1197 }
1198
1199 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07001200 * dismiss the ComboPage
1201 */
1202 @Override
1203 public void removeComboView() {
1204 mUi.hideComboView();
1205 }
1206
1207 // active tabs page handling
1208
1209 protected void showActiveTabsPage() {
1210 mMenuState = EMPTY_MENU;
1211 mUi.showActiveTabsPage();
1212 }
1213
1214 /**
1215 * Remove the active tabs page.
1216 * @param needToAttach If true, the active tabs page did not attach a tab
1217 * to the content view, so we need to do that here.
1218 */
1219 @Override
1220 public void removeActiveTabsPage(boolean needToAttach) {
1221 mMenuState = R.id.MAIN_MENU;
1222 mUi.removeActiveTabsPage();
1223 if (needToAttach) {
1224 setActiveTab(mTabControl.getCurrentTab());
1225 }
1226 getCurrentTopWebView().requestFocus();
1227 }
1228
1229 // key handling
1230 protected void onBackKey() {
1231 if (!mUi.onBackKey()) {
1232 WebView subwindow = mTabControl.getCurrentSubWindow();
1233 if (subwindow != null) {
1234 if (subwindow.canGoBack()) {
1235 subwindow.goBack();
1236 } else {
1237 dismissSubWindow(mTabControl.getCurrentTab());
1238 }
1239 } else {
1240 goBackOnePageOrQuit();
1241 }
1242 }
1243 }
1244
Michael Kolb4bd767d2011-05-27 11:33:55 -07001245 protected boolean onMenuKey() {
1246 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001247 }
1248
Michael Kolb8233fac2010-10-26 16:08:53 -07001249 // menu handling and state
1250 // TODO: maybe put into separate handler
1251
1252 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckb3417f02011-01-14 11:01:05 -08001253 if (mOptionsMenuHandler != null) {
1254 return mOptionsMenuHandler.onCreateOptionsMenu(menu);
1255 }
1256
John Reckd73c5a22010-12-22 10:22:50 -08001257 if (mMenuState == EMPTY_MENU) {
1258 return false;
1259 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001260 MenuInflater inflater = mActivity.getMenuInflater();
1261 inflater.inflate(R.menu.browser, menu);
1262 updateInLoadMenuItems(menu);
1263 // hold on to the menu reference here; it is used by the page callbacks
1264 // to update the menu based on loading state
1265 mCachedMenu = menu;
1266 return true;
1267 }
1268
1269 protected void onCreateContextMenu(ContextMenu menu, View v,
1270 ContextMenuInfo menuInfo) {
1271 if (v instanceof TitleBarBase) {
1272 return;
1273 }
1274 if (!(v instanceof WebView)) {
1275 return;
1276 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001277 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001278 WebView.HitTestResult result = webview.getHitTestResult();
1279 if (result == null) {
1280 return;
1281 }
1282
1283 int type = result.getType();
1284 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1285 Log.w(LOGTAG,
1286 "We should not show context menu when nothing is touched");
1287 return;
1288 }
1289 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1290 // let TextView handles context menu
1291 return;
1292 }
1293
1294 // Note, http://b/issue?id=1106666 is requesting that
1295 // an inflated menu can be used again. This is not available
1296 // yet, so inflate each time (yuk!)
1297 MenuInflater inflater = mActivity.getMenuInflater();
1298 inflater.inflate(R.menu.browsercontext, menu);
1299
1300 // Show the correct menu group
1301 final String extra = result.getExtra();
1302 menu.setGroupVisible(R.id.PHONE_MENU,
1303 type == WebView.HitTestResult.PHONE_TYPE);
1304 menu.setGroupVisible(R.id.EMAIL_MENU,
1305 type == WebView.HitTestResult.EMAIL_TYPE);
1306 menu.setGroupVisible(R.id.GEO_MENU,
1307 type == WebView.HitTestResult.GEO_TYPE);
1308 menu.setGroupVisible(R.id.IMAGE_MENU,
1309 type == WebView.HitTestResult.IMAGE_TYPE
1310 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1311 menu.setGroupVisible(R.id.ANCHOR_MENU,
1312 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1313 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001314 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1315 || type == WebView.HitTestResult.PHONE_TYPE
1316 || type == WebView.HitTestResult.EMAIL_TYPE
1317 || type == WebView.HitTestResult.GEO_TYPE;
1318 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1319 if (hitText) {
1320 menu.findItem(R.id.select_text_menu_id)
1321 .setOnMenuItemClickListener(new SelectText(webview));
1322 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001323 // Setup custom handling depending on the type
1324 switch (type) {
1325 case WebView.HitTestResult.PHONE_TYPE:
1326 menu.setHeaderTitle(Uri.decode(extra));
1327 menu.findItem(R.id.dial_context_menu_id).setIntent(
1328 new Intent(Intent.ACTION_VIEW, Uri
1329 .parse(WebView.SCHEME_TEL + extra)));
1330 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1331 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1332 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1333 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1334 addIntent);
1335 menu.findItem(R.id.copy_phone_context_menu_id)
1336 .setOnMenuItemClickListener(
1337 new Copy(extra));
1338 break;
1339
1340 case WebView.HitTestResult.EMAIL_TYPE:
1341 menu.setHeaderTitle(extra);
1342 menu.findItem(R.id.email_context_menu_id).setIntent(
1343 new Intent(Intent.ACTION_VIEW, Uri
1344 .parse(WebView.SCHEME_MAILTO + extra)));
1345 menu.findItem(R.id.copy_mail_context_menu_id)
1346 .setOnMenuItemClickListener(
1347 new Copy(extra));
1348 break;
1349
1350 case WebView.HitTestResult.GEO_TYPE:
1351 menu.setHeaderTitle(extra);
1352 menu.findItem(R.id.map_context_menu_id).setIntent(
1353 new Intent(Intent.ACTION_VIEW, Uri
1354 .parse(WebView.SCHEME_GEO
1355 + URLEncoder.encode(extra))));
1356 menu.findItem(R.id.copy_geo_context_menu_id)
1357 .setOnMenuItemClickListener(
1358 new Copy(extra));
1359 break;
1360
1361 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1362 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001363 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001364 // decide whether to show the open link in new tab option
1365 boolean showNewTab = mTabControl.canCreateNewTab();
1366 MenuItem newTabItem
1367 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001368 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001369 ? R.string.contextmenu_openlink_newwindow_background
1370 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001371 newTabItem.setVisible(showNewTab);
1372 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001373 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1374 newTabItem.setOnMenuItemClickListener(
1375 new MenuItem.OnMenuItemClickListener() {
1376 @Override
1377 public boolean onMenuItemClick(MenuItem item) {
1378 final HashMap<String, WebView> hrefMap =
1379 new HashMap<String, WebView>();
1380 hrefMap.put("webview", webview);
1381 final Message msg = mHandler.obtainMessage(
1382 FOCUS_NODE_HREF,
1383 R.id.open_newtab_context_menu_id,
1384 0, hrefMap);
1385 webview.requestFocusNodeHref(msg);
1386 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001387 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001388 });
1389 } else {
1390 newTabItem.setOnMenuItemClickListener(
1391 new MenuItem.OnMenuItemClickListener() {
1392 @Override
1393 public boolean onMenuItemClick(MenuItem item) {
1394 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb7bcafde2011-05-09 13:55:59 -07001395 final Tab newTab =
1396 openTab(extra,
1397 (parent != null)
1398 && parent.isPrivateBrowsingEnabled(),
1399 !mSettings.openInBackground(),
1400 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001401 if (newTab != parent) {
1402 parent.addChildTab(newTab);
1403 }
1404 return true;
1405 }
1406 });
1407 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001408 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001409 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1410 break;
1411 }
1412 // otherwise fall through to handle image part
1413 case WebView.HitTestResult.IMAGE_TYPE:
1414 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1415 menu.setHeaderTitle(extra);
1416 }
1417 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1418 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1419 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001420 setOnMenuItemClickListener(
1421 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001422 menu.findItem(R.id.set_wallpaper_context_menu_id).
1423 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1424 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001425 break;
1426
1427 default:
1428 Log.w(LOGTAG, "We should not get here.");
1429 break;
1430 }
1431 //update the ui
1432 mUi.onContextMenuCreated(menu);
1433 }
1434
1435 /**
1436 * As the menu can be open when loading state changes
1437 * we must manually update the state of the stop/reload menu
1438 * item
1439 */
1440 private void updateInLoadMenuItems(Menu menu) {
1441 if (menu == null) {
1442 return;
1443 }
1444 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1445 MenuItem src = mInLoad ?
1446 menu.findItem(R.id.stop_menu_id):
1447 menu.findItem(R.id.reload_menu_id);
1448 if (src != null) {
1449 dest.setIcon(src.getIcon());
1450 dest.setTitle(src.getTitle());
1451 }
1452 }
1453
John Reckb3417f02011-01-14 11:01:05 -08001454 boolean onPrepareOptionsMenu(Menu menu) {
1455 if (mOptionsMenuHandler != null) {
1456 return mOptionsMenuHandler.onPrepareOptionsMenu(menu);
1457 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001458 // Note: setVisible will decide whether an item is visible; while
1459 // setEnabled() will decide whether an item is enabled, which also means
1460 // whether the matching shortcut key will function.
1461 switch (mMenuState) {
1462 case EMPTY_MENU:
1463 if (mCurrentMenuState != mMenuState) {
1464 menu.setGroupVisible(R.id.MAIN_MENU, false);
1465 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1466 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1467 }
1468 break;
1469 default:
1470 if (mCurrentMenuState != mMenuState) {
1471 menu.setGroupVisible(R.id.MAIN_MENU, true);
1472 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1473 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1474 }
1475 final WebView w = getCurrentTopWebView();
1476 boolean canGoBack = false;
1477 boolean canGoForward = false;
1478 boolean isHome = false;
1479 if (w != null) {
1480 canGoBack = w.canGoBack();
1481 canGoForward = w.canGoForward();
1482 isHome = mSettings.getHomePage().equals(w.getUrl());
1483 }
1484 final MenuItem back = menu.findItem(R.id.back_menu_id);
1485 back.setEnabled(canGoBack);
1486
1487 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1488 home.setEnabled(!isHome);
1489
1490 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1491 forward.setEnabled(canGoForward);
1492
1493 // decide whether to show the share link option
1494 PackageManager pm = mActivity.getPackageManager();
1495 Intent send = new Intent(Intent.ACTION_SEND);
1496 send.setType("text/plain");
1497 ResolveInfo ri = pm.resolveActivity(send,
1498 PackageManager.MATCH_DEFAULT_ONLY);
1499 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1500
John Reck35e9dd62011-04-25 09:01:54 -07001501 boolean isNavDump = mSettings.enableNavDump();
Michael Kolb8233fac2010-10-26 16:08:53 -07001502 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1503 nav.setVisible(isNavDump);
1504 nav.setEnabled(isNavDump);
1505
John Reck35e9dd62011-04-25 09:01:54 -07001506 boolean showDebugSettings = mSettings.isDebugEnabled();
Michael Kolb8233fac2010-10-26 16:08:53 -07001507 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1508 counter.setVisible(showDebugSettings);
1509 counter.setEnabled(showDebugSettings);
1510
John Reckb3417f02011-01-14 11:01:05 -08001511 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1512 newtab.setEnabled(getTabControl().canCreateNewTab());
Michael Kolb8233fac2010-10-26 16:08:53 -07001513
Leon Scroggins81983762011-02-11 15:17:36 -05001514 MenuItem archive = menu.findItem(R.id.save_webarchive_menu_id);
John Reck51d8bad2011-02-28 15:47:47 -08001515 Tab tab = getTabControl().getCurrentTab();
1516 String url = tab != null ? tab.getUrl() : null;
1517 archive.setVisible(!TextUtils.isEmpty(url)
1518 && !url.endsWith(".webarchivexml"));
Michael Kolb8233fac2010-10-26 16:08:53 -07001519 break;
1520 }
1521 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001522 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001523 }
1524
1525 public boolean onOptionsItemSelected(MenuItem item) {
John Reckb3417f02011-01-14 11:01:05 -08001526 if (mOptionsMenuHandler != null &&
1527 mOptionsMenuHandler.onOptionsItemSelected(item)) {
1528 return true;
1529 }
1530
Michael Kolb8233fac2010-10-26 16:08:53 -07001531 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1532 // menu remains active, so ensure comboview is dismissed
1533 // if main menu option is selected
1534 removeComboView();
1535 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001536 if (null == getCurrentTopWebView()) {
1537 return false;
1538 }
1539 if (mMenuIsDown) {
1540 // The shortcut action consumes the MENU. Even if it is still down,
1541 // it won't trigger the next shortcut action. In the case of the
1542 // shortcut action triggering a new activity, like Bookmarks, we
1543 // won't get onKeyUp for MENU. So it is important to reset it here.
1544 mMenuIsDown = false;
1545 }
1546 switch (item.getItemId()) {
1547 // -- Main menu
1548 case R.id.new_tab_menu_id:
1549 openTabToHomePage();
1550 break;
1551
1552 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001553 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001554 break;
1555
1556 case R.id.goto_menu_id:
1557 editUrl();
1558 break;
1559
1560 case R.id.bookmarks_menu_id:
1561 bookmarksOrHistoryPicker(false);
1562 break;
1563
1564 case R.id.active_tabs_menu_id:
1565 showActiveTabsPage();
1566 break;
1567
1568 case R.id.add_bookmark_menu_id:
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001569 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001570 break;
1571
1572 case R.id.stop_reload_menu_id:
1573 if (mInLoad) {
1574 stopLoading();
1575 } else {
1576 getCurrentTopWebView().reload();
1577 }
1578 break;
1579
1580 case R.id.back_menu_id:
1581 getCurrentTopWebView().goBack();
1582 break;
1583
1584 case R.id.forward_menu_id:
1585 getCurrentTopWebView().goForward();
1586 break;
1587
1588 case R.id.close_menu_id:
1589 // Close the subwindow if it exists.
1590 if (mTabControl.getCurrentSubWindow() != null) {
1591 dismissSubWindow(mTabControl.getCurrentTab());
1592 break;
1593 }
1594 closeCurrentTab();
1595 break;
1596
1597 case R.id.homepage_menu_id:
1598 Tab current = mTabControl.getCurrentTab();
1599 if (current != null) {
1600 dismissSubWindow(current);
1601 loadUrl(current.getWebView(), mSettings.getHomePage());
1602 }
1603 break;
1604
1605 case R.id.preferences_menu_id:
1606 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1607 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1608 getCurrentTopWebView().getUrl());
1609 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1610 break;
1611
1612 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001613 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001614 break;
1615
Leon Scrogginsac993842011-02-02 12:54:07 -05001616 case R.id.save_webarchive_menu_id:
1617 String state = Environment.getExternalStorageState();
1618 if (!Environment.MEDIA_MOUNTED.equals(state)) {
1619 Log.e(LOGTAG, "External storage not mounted");
1620 Toast.makeText(mActivity, R.string.webarchive_failed,
1621 Toast.LENGTH_SHORT).show();
1622 break;
1623 }
1624 final String directory = Environment.getExternalStoragePublicDirectory(
1625 Environment.DIRECTORY_DOWNLOADS) + File.separator;
1626 File dir = new File(directory);
1627 if (!dir.exists() && !dir.mkdirs()) {
1628 Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
1629 Toast.makeText(mActivity, R.string.webarchive_failed,
1630 Toast.LENGTH_SHORT).show();
1631 break;
1632 }
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001633 final WebView topWebView = getCurrentTopWebView();
Leon Scrogginsac993842011-02-02 12:54:07 -05001634 final String title = topWebView.getTitle();
John Reck51d8bad2011-02-28 15:47:47 -08001635 final String url = topWebView.getUrl();
Leon Scrogginsac993842011-02-02 12:54:07 -05001636 topWebView.saveWebArchive(directory, true,
1637 new ValueCallback<String>() {
1638 @Override
1639 public void onReceiveValue(final String value) {
1640 if (value != null) {
1641 File file = new File(value);
1642 final long length = file.length();
1643 if (file.exists() && length > 0) {
Leon Scroggins1cb96552011-02-11 14:22:57 -05001644 Toast.makeText(mActivity, R.string.webarchive_saved,
1645 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001646 final DownloadManager manager = (DownloadManager) mActivity
1647 .getSystemService(Context.DOWNLOAD_SERVICE);
1648 new Thread("Add WebArchive to download manager") {
1649 @Override
1650 public void run() {
Vasu Noria9e30a72011-03-07 11:37:34 -08001651 manager.addCompletedDownload(
1652 null == title ? value : title,
Leon Scrogginsac993842011-02-02 12:54:07 -05001653 value, true, "application/x-webarchive-xml",
1654 value, length, true);
1655 }
1656 }.start();
1657 return;
1658 }
1659 }
John Reck51d8bad2011-02-28 15:47:47 -08001660 DownloadHandler.onDownloadStartNoStream(mActivity,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001661 url, null, null, null, topWebView.isPrivateBrowsingEnabled());
Leon Scrogginsac993842011-02-02 12:54:07 -05001662 }
1663 });
1664 break;
1665
Michael Kolb8233fac2010-10-26 16:08:53 -07001666 case R.id.page_info_menu_id:
1667 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1668 false);
1669 break;
1670
1671 case R.id.classic_history_menu_id:
1672 bookmarksOrHistoryPicker(true);
1673 break;
1674
1675 case R.id.title_bar_share_page_url:
1676 case R.id.share_page_menu_id:
1677 Tab currentTab = mTabControl.getCurrentTab();
1678 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001679 return false;
1680 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001681 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001682 break;
1683
1684 case R.id.dump_nav_menu_id:
1685 getCurrentTopWebView().debugDump();
1686 break;
1687
1688 case R.id.dump_counters_menu_id:
1689 getCurrentTopWebView().dumpV8Counters();
1690 break;
1691
1692 case R.id.zoom_in_menu_id:
1693 getCurrentTopWebView().zoomIn();
1694 break;
1695
1696 case R.id.zoom_out_menu_id:
1697 getCurrentTopWebView().zoomOut();
1698 break;
1699
1700 case R.id.view_downloads_menu_id:
1701 viewDownloads();
1702 break;
1703
1704 case R.id.window_one_menu_id:
1705 case R.id.window_two_menu_id:
1706 case R.id.window_three_menu_id:
1707 case R.id.window_four_menu_id:
1708 case R.id.window_five_menu_id:
1709 case R.id.window_six_menu_id:
1710 case R.id.window_seven_menu_id:
1711 case R.id.window_eight_menu_id:
1712 {
1713 int menuid = item.getItemId();
1714 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1715 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1716 Tab desiredTab = mTabControl.getTab(id);
1717 if (desiredTab != null &&
1718 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07001719 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001720 }
1721 break;
1722 }
1723 }
1724 }
1725 break;
1726
1727 default:
1728 return false;
1729 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001730 return true;
1731 }
1732
1733 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001734 // Let the History and Bookmark fragments handle menus they created.
1735 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1736 return false;
1737 }
1738
Michael Kolb8233fac2010-10-26 16:08:53 -07001739 int id = item.getItemId();
1740 boolean result = true;
1741 switch (id) {
1742 // For the context menu from the title bar
1743 case R.id.title_bar_copy_page_url:
1744 Tab currentTab = mTabControl.getCurrentTab();
1745 if (null == currentTab) {
1746 result = false;
1747 break;
1748 }
1749 WebView mainView = currentTab.getWebView();
1750 if (null == mainView) {
1751 result = false;
1752 break;
1753 }
1754 copy(mainView.getUrl());
1755 break;
1756 // -- Browser context menu
1757 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001758 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001759 case R.id.copy_link_context_menu_id:
1760 final WebView webView = getCurrentTopWebView();
1761 if (null == webView) {
1762 result = false;
1763 break;
1764 }
1765 final HashMap<String, WebView> hrefMap =
1766 new HashMap<String, WebView>();
1767 hrefMap.put("webview", webView);
1768 final Message msg = mHandler.obtainMessage(
1769 FOCUS_NODE_HREF, id, 0, hrefMap);
1770 webView.requestFocusNodeHref(msg);
1771 break;
1772
1773 default:
1774 // For other context menus
1775 result = onOptionsItemSelected(item);
1776 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001777 return result;
1778 }
1779
1780 /**
1781 * support programmatically opening the context menu
1782 */
1783 public void openContextMenu(View view) {
1784 mActivity.openContextMenu(view);
1785 }
1786
1787 /**
1788 * programmatically open the options menu
1789 */
1790 public void openOptionsMenu() {
1791 mActivity.openOptionsMenu();
1792 }
1793
1794 public boolean onMenuOpened(int featureId, Menu menu) {
1795 if (mOptionsMenuOpen) {
1796 if (mConfigChanged) {
1797 // We do not need to make any changes to the state of the
1798 // title bar, since the only thing that happened was a
1799 // change in orientation
1800 mConfigChanged = false;
1801 } else {
1802 if (!mExtendedMenuOpen) {
1803 mExtendedMenuOpen = true;
1804 mUi.onExtendedMenuOpened();
1805 } else {
1806 // Switching the menu back to icon view, so show the
1807 // title bar once again.
1808 mExtendedMenuOpen = false;
1809 mUi.onExtendedMenuClosed(mInLoad);
Michael Kolb8233fac2010-10-26 16:08:53 -07001810 }
1811 }
1812 } else {
1813 // The options menu is closed, so open it, and show the title
1814 mOptionsMenuOpen = true;
1815 mConfigChanged = false;
1816 mExtendedMenuOpen = false;
1817 mUi.onOptionsMenuOpened();
1818 }
1819 return true;
1820 }
1821
1822 public void onOptionsMenuClosed(Menu menu) {
1823 mOptionsMenuOpen = false;
1824 mUi.onOptionsMenuClosed(mInLoad);
1825 }
1826
1827 public void onContextMenuClosed(Menu menu) {
1828 mUi.onContextMenuClosed(menu, mInLoad);
1829 }
1830
1831 // Helper method for getting the top window.
1832 @Override
1833 public WebView getCurrentTopWebView() {
1834 return mTabControl.getCurrentTopWebView();
1835 }
1836
1837 @Override
1838 public WebView getCurrentWebView() {
1839 return mTabControl.getCurrentWebView();
1840 }
1841
1842 /*
1843 * This method is called as a result of the user selecting the options
1844 * menu to see the download window. It shows the download window on top of
1845 * the current window.
1846 */
1847 void viewDownloads() {
1848 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1849 mActivity.startActivity(intent);
1850 }
1851
1852 // action mode
1853
1854 void onActionModeStarted(ActionMode mode) {
1855 mUi.onActionModeStarted(mode);
1856 mActionMode = mode;
1857 }
1858
1859 /*
1860 * True if a custom ActionMode (i.e. find or select) is in use.
1861 */
1862 @Override
1863 public boolean isInCustomActionMode() {
1864 return mActionMode != null;
1865 }
1866
1867 /*
1868 * End the current ActionMode.
1869 */
1870 @Override
1871 public void endActionMode() {
1872 if (mActionMode != null) {
1873 mActionMode.finish();
1874 }
1875 }
1876
1877 /*
1878 * Called by find and select when they are finished. Replace title bars
1879 * as necessary.
1880 */
1881 public void onActionModeFinished(ActionMode mode) {
1882 if (!isInCustomActionMode()) return;
1883 mUi.onActionModeFinished(mInLoad);
1884 mActionMode = null;
1885 }
1886
1887 boolean isInLoad() {
1888 return mInLoad;
1889 }
1890
1891 // bookmark handling
1892
1893 /**
1894 * add the current page as a bookmark to the given folder id
1895 * @param folderId use -1 for the default folder
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001896 * @param canBeAnEdit If true, check to see whether the site is already
1897 * bookmarked, and if it is, edit that bookmark. If false, and
1898 * the site is already bookmarked, do not attempt to edit the
1899 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001900 */
1901 @Override
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001902 public void bookmarkCurrentPage(long folderId, boolean canBeAnEdit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001903 Intent i = new Intent(mActivity,
1904 AddBookmarkPage.class);
1905 WebView w = getCurrentTopWebView();
1906 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1907 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1908 String touchIconUrl = w.getTouchIconUrl();
1909 if (touchIconUrl != null) {
1910 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1911 WebSettings settings = w.getSettings();
1912 if (settings != null) {
1913 i.putExtra(AddBookmarkPage.USER_AGENT,
1914 settings.getUserAgentString());
1915 }
1916 }
1917 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1918 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1919 getDesiredThumbnailHeight(mActivity)));
1920 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1921 i.putExtra(BrowserContract.Bookmarks.PARENT,
1922 folderId);
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001923 if (canBeAnEdit) {
1924 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1925 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001926 // Put the dialog at the upper right of the screen, covering the
1927 // star on the title bar.
1928 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1929 mActivity.startActivity(i);
1930 }
1931
1932 // file chooser
1933 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1934 mUploadHandler = new UploadHandler(this);
1935 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1936 }
1937
1938 // thumbnails
1939
1940 /**
1941 * Return the desired width for thumbnail screenshots, which are stored in
1942 * the database, and used on the bookmarks screen.
1943 * @param context Context for finding out the density of the screen.
1944 * @return desired width for thumbnail screenshot.
1945 */
1946 static int getDesiredThumbnailWidth(Context context) {
1947 return context.getResources().getDimensionPixelOffset(
1948 R.dimen.bookmarkThumbnailWidth);
1949 }
1950
1951 /**
1952 * Return the desired height for thumbnail screenshots, which are stored in
1953 * the database, and used on the bookmarks screen.
1954 * @param context Context for finding out the density of the screen.
1955 * @return desired height for thumbnail screenshot.
1956 */
1957 static int getDesiredThumbnailHeight(Context context) {
1958 return context.getResources().getDimensionPixelOffset(
1959 R.dimen.bookmarkThumbnailHeight);
1960 }
1961
Michael Kolb1acef692011-03-08 14:12:06 -08001962 static Bitmap createScreenshot(Tab tab, int width, int height) {
1963 if ((tab != null) && (tab.getWebView() != null)) {
1964 return createScreenshot(tab.getWebView(), width, height);
1965 }
1966 return null;
1967 }
1968
Michael Kolb8233fac2010-10-26 16:08:53 -07001969 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001970 // We render to a bitmap 2x the desired size so that we can then
1971 // re-scale it with filtering since canvas.scale doesn't filter
1972 // This helps reduce aliasing at the cost of being slightly blurry
1973 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001974 Picture thumbnail = view.capturePicture();
1975 if (thumbnail == null) {
1976 return null;
1977 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001978 width *= filter_scale;
1979 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001980 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1981 Canvas canvas = new Canvas(bm);
1982 // May need to tweak these values to determine what is the
1983 // best scale factor
1984 int thumbnailWidth = thumbnail.getWidth();
1985 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001986 float scaleFactor = 1.0f;
Michael Kolbeb95db42011-03-03 10:38:40 -08001987 if (thumbnailWidth > 0 && thumbnailHeight > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001988 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001989 } else {
1990 return null;
1991 }
John Reckfe49ab42010-11-16 17:09:37 -08001992
Michael Kolbeb95db42011-03-03 10:38:40 -08001993 float scaleFactorY = (float) height / (float)thumbnailHeight;
1994 if (scaleFactorY > scaleFactor) {
1995 // The picture is narrower than the requested AR
1996 // Center the thumnail and crop the sides
1997 scaleFactor = scaleFactorY;
John Reckfe49ab42010-11-16 17:09:37 -08001998 float wx = (thumbnailWidth * scaleFactor) - width;
1999 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07002000 }
2001
John Reckfe49ab42010-11-16 17:09:37 -08002002 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07002003
2004 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08002005 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
2006 height / filter_scale, true);
2007 bm.recycle();
2008 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07002009 }
2010
John Reck34ef2672011-02-10 11:30:55 -08002011 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002012 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07002013 // FIXME: Would like to make sure there is actually something to
2014 // draw, but the API for that (WebViewCore.pictureReady()) is not
2015 // currently accessible here.
2016
John Reck34ef2672011-02-10 11:30:55 -08002017 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08002018 if (view == null) {
2019 // Tab was destroyed
2020 return;
2021 }
John Reck34ef2672011-02-10 11:30:55 -08002022 final String url = tab.getUrl();
2023 final String originalUrl = view.getOriginalUrl();
2024
2025 if (TextUtils.isEmpty(url)) {
2026 return;
2027 }
2028
2029 // Only update thumbnails for web urls (http(s)://), not for
2030 // about:, javascript:, data:, etc...
2031 // Unless it is a bookmarked site, then always update
2032 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2033 return;
2034 }
2035
Michael Kolb8233fac2010-10-26 16:08:53 -07002036 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2037 getDesiredThumbnailHeight(mActivity));
2038 if (bm == null) {
2039 return;
2040 }
2041
2042 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002043 new AsyncTask<Void, Void, Void>() {
2044 @Override
2045 protected Void doInBackground(Void... unused) {
2046 Cursor cursor = null;
2047 try {
2048 // TODO: Clean this up
2049 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2050 if (cursor != null && cursor.moveToFirst()) {
2051 final ByteArrayOutputStream os =
2052 new ByteArrayOutputStream();
2053 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002054
John Reck34ef2672011-02-10 11:30:55 -08002055 ContentValues values = new ContentValues();
2056 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002057
John Reck34ef2672011-02-10 11:30:55 -08002058 do {
John Reck617fd832011-02-16 14:35:59 -08002059 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002060 cr.update(Images.CONTENT_URI, values, null, null);
2061 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002062 }
John Reck34ef2672011-02-10 11:30:55 -08002063 } catch (IllegalStateException e) {
2064 // Ignore
2065 } finally {
2066 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002067 }
John Reck34ef2672011-02-10 11:30:55 -08002068 return null;
2069 }
2070 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002071 }
2072
2073 private class Copy implements OnMenuItemClickListener {
2074 private CharSequence mText;
2075
2076 public boolean onMenuItemClick(MenuItem item) {
2077 copy(mText);
2078 return true;
2079 }
2080
2081 public Copy(CharSequence toCopy) {
2082 mText = toCopy;
2083 }
2084 }
2085
Leon Scroggins63c02662010-11-18 15:16:27 -05002086 private static class Download implements OnMenuItemClickListener {
2087 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002088 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002089 private boolean mPrivateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002090
2091 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002092 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002093 null, null, mPrivateBrowsing);
Michael Kolb8233fac2010-10-26 16:08:53 -07002094 return true;
2095 }
2096
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002097 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002098 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002099 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002100 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002101 }
2102 }
2103
Cary Clark8974d282010-11-22 10:46:05 -05002104 private static class SelectText implements OnMenuItemClickListener {
2105 private WebView mWebView;
2106
2107 public boolean onMenuItemClick(MenuItem item) {
2108 if (mWebView != null) {
2109 return mWebView.selectText();
2110 }
2111 return false;
2112 }
2113
2114 public SelectText(WebView webView) {
2115 mWebView = webView;
2116 }
2117
2118 }
2119
Michael Kolb8233fac2010-10-26 16:08:53 -07002120 /********************** TODO: UI stuff *****************************/
2121
2122 // these methods have been copied, they still need to be cleaned up
2123
2124 /****************** tabs ***************************************************/
2125
2126 // basic tab interactions:
2127
2128 // it is assumed that tabcontrol already knows about the tab
2129 protected void addTab(Tab tab) {
2130 mUi.addTab(tab);
2131 }
2132
2133 protected void removeTab(Tab tab) {
2134 mUi.removeTab(tab);
2135 mTabControl.removeTab(tab);
2136 }
2137
Michael Kolbf2055602011-04-09 17:20:03 -07002138 @Override
2139 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002140 // monkey protection against delayed start
2141 if (tab != null) {
2142 mTabControl.setCurrentTab(tab);
2143 // the tab is guaranteed to have a webview after setCurrentTab
2144 mUi.setActiveTab(tab);
2145 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002146 }
2147
2148 protected void closeEmptyChildTab() {
2149 Tab current = mTabControl.getCurrentTab();
2150 if (current != null
2151 && current.getWebView().copyBackForwardList().getSize() == 0) {
Michael Kolbc831b632011-05-11 09:30:34 -07002152 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002153 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002154 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002155 closeTab(current);
2156 }
2157 }
2158 }
2159
2160 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002161 // Dismiss the subwindow if applicable.
2162 dismissSubWindow(appTab);
2163 // Since we might kill the WebView, remove it from the
2164 // content view first.
2165 mUi.detachTab(appTab);
2166 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002167 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002168 // TODO: analyze why the remove and add are necessary
2169 mUi.attachTab(appTab);
2170 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002171 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002172 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002173 } else {
2174 // If the tab was the current tab, we have to attach
2175 // it to the view system again.
2176 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002177 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002178 }
2179 }
2180
2181 // Remove the sub window if it exists. Also called by TabControl when the
2182 // user clicks the 'X' to dismiss a sub window.
2183 public void dismissSubWindow(Tab tab) {
2184 removeSubWindow(tab);
2185 // dismiss the subwindow. This will destroy the WebView.
2186 tab.dismissSubWindow();
2187 getCurrentTopWebView().requestFocus();
2188 }
2189
2190 @Override
2191 public void removeSubWindow(Tab t) {
2192 if (t.getSubWebView() != null) {
2193 mUi.removeSubWindow(t.getSubViewContainer());
2194 }
2195 }
2196
2197 @Override
2198 public void attachSubWindow(Tab tab) {
2199 if (tab.getSubWebView() != null) {
2200 mUi.attachSubWindow(tab.getSubViewContainer());
2201 getCurrentTopWebView().requestFocus();
2202 }
2203 }
2204
Michael Kolb7bcafde2011-05-09 13:55:59 -07002205 // open a non inconito tab with the given url data
2206 // and set as active tab
2207 public Tab openTab(UrlData urlData) {
2208 Tab tab = createNewTab(false, true, true);
2209 if ((tab != null) && !urlData.isEmpty()) {
2210 loadUrlDataIn(tab, urlData);
2211 }
2212 return tab;
2213 }
2214
Michael Kolb843510f2010-12-09 10:51:49 -08002215 @Override
2216 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002217 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002218 }
2219
Michael Kolb8233fac2010-10-26 16:08:53 -07002220 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002221 public Tab openIncognitoTab() {
2222 return openTab(INCOGNITO_URI, true, true, false);
2223 }
2224
2225 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002226 public Tab openTab(String url, boolean incognito, boolean setActive,
2227 boolean useCurrent) {
2228 Tab tab = createNewTab(incognito, setActive, useCurrent);
2229 if (tab != null) {
Michael Kolba4261fd2011-05-05 11:27:37 -07002230 WebView w = tab.getWebView();
Michael Kolb519d2282011-05-09 17:03:19 -07002231 if (url != null) {
2232 loadUrl(w, url);
2233 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002234 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002235 return tab;
2236 }
2237
2238 // this method will attempt to create a new tab
2239 // incognito: private browsing tab
2240 // setActive: ste tab as current tab
2241 // useCurrent: if no new tab can be created, return current tab
2242 private Tab createNewTab(boolean incognito, boolean setActive,
2243 boolean useCurrent) {
2244 Tab tab = null;
2245 if (mTabControl.canCreateNewTab()) {
2246 tab = mTabControl.createNewTab(incognito);
2247 addTab(tab);
2248 if (setActive) {
2249 setActiveTab(tab);
2250 }
2251 } else {
2252 if (useCurrent) {
2253 tab = mTabControl.getCurrentTab();
2254 // Get rid of the subwindow if it exists
2255 dismissSubWindow(tab);
2256 } else {
2257 mUi.showMaxTabsWarning();
2258 }
2259 }
2260 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002261 }
2262
2263 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002264 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002265 * @return boolean True if we successfully switched to a different tab. If
2266 * the indexth tab is null, or if that tab is the same as
2267 * the current one, return false.
2268 */
2269 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002270 public boolean switchToTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002271 // hide combo view if open
2272 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002273 Tab currentTab = mTabControl.getCurrentTab();
2274 if (tab == null || tab == currentTab) {
2275 return false;
2276 }
2277 setActiveTab(tab);
2278 return true;
2279 }
2280
2281 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002282 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002283 // hide combo view if open
2284 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002285 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002286 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002287 return;
2288 }
Michael Kolbc831b632011-05-11 09:30:34 -07002289 final Tab current = mTabControl.getCurrentTab();
2290 final int pos = mTabControl.getCurrentPosition();
2291 Tab newTab = current.getParent();
2292 if (newTab == null) {
2293 newTab = mTabControl.getTab(pos + 1);
2294 if (newTab == null) {
2295 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07002296 }
2297 }
Michael Kolbc831b632011-05-11 09:30:34 -07002298 if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002299 // Close window
2300 closeTab(current);
2301 }
2302 }
2303
2304 /**
2305 * Close the tab, remove its associated title bar, and adjust mTabControl's
2306 * current tab to a valid value.
2307 */
2308 @Override
2309 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002310 // hide combo view if open
2311 removeComboView();
Michael Kolb2d59c322011-01-25 13:18:55 -08002312 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002313 }
2314
2315 /**************** TODO: Url loading clean up *******************************/
2316
2317 // Called when loading from context menu or LOAD_URL message
2318 protected void loadUrlFromContext(WebView view, String url) {
2319 // In case the user enters nothing.
2320 if (url != null && url.length() != 0 && view != null) {
2321 url = UrlUtils.smartUrlFilter(url);
2322 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2323 loadUrl(view, url);
2324 }
2325 }
2326 }
2327
2328 /**
2329 * Load the URL into the given WebView and update the title bar
2330 * to reflect the new load. Call this instead of WebView.loadUrl
2331 * directly.
2332 * @param view The WebView used to load url.
2333 * @param url The URL to load.
2334 */
2335 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002336 view.loadUrl(url);
2337 }
2338
2339 /**
2340 * Load UrlData into a Tab and update the title bar to reflect the new
2341 * load. Call this instead of UrlData.loadIn directly.
2342 * @param t The Tab used to load.
2343 * @param data The UrlData being loaded.
2344 */
2345 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002346 data.loadIn(t);
2347 }
2348
John Reck30c714c2010-12-16 17:30:34 -08002349 @Override
2350 public void onUserCanceledSsl(Tab tab) {
2351 WebView web = tab.getWebView();
2352 // TODO: Figure out the "right" behavior
2353 if (web.canGoBack()) {
2354 web.goBack();
2355 } else {
2356 web.loadUrl(mSettings.getHomePage());
2357 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002358 }
2359
2360 void goBackOnePageOrQuit() {
2361 Tab current = mTabControl.getCurrentTab();
2362 if (current == null) {
2363 /*
2364 * Instead of finishing the activity, simply push this to the back
2365 * of the stack and let ActivityManager to choose the foreground
2366 * activity. As BrowserActivity is singleTask, it will be always the
2367 * root of the task. So we can use either true or false for
2368 * moveTaskToBack().
2369 */
2370 mActivity.moveTaskToBack(true);
2371 return;
2372 }
2373 WebView w = current.getWebView();
2374 if (w.canGoBack()) {
2375 w.goBack();
2376 } else {
2377 // Check to see if we are closing a window that was created by
2378 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07002379 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07002380 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07002381 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07002382 // Now we close the other tab
2383 closeTab(current);
2384 } else {
Michael Kolb8233fac2010-10-26 16:08:53 -07002385 /*
2386 * Instead of finishing the activity, simply push this to the back
2387 * of the stack and let ActivityManager to choose the foreground
2388 * activity. As BrowserActivity is singleTask, it will be always the
2389 * root of the task. So we can use either true or false for
2390 * moveTaskToBack().
2391 */
2392 mActivity.moveTaskToBack(true);
2393 }
2394 }
2395 }
2396
2397 /**
2398 * Feed the previously stored results strings to the BrowserProvider so that
2399 * the SearchDialog will show them instead of the standard searches.
2400 * @param result String to show on the editable line of the SearchDialog.
2401 */
2402 @Override
2403 public void showVoiceSearchResults(String result) {
2404 ContentProviderClient client = mActivity.getContentResolver()
2405 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2406 ContentProvider prov = client.getLocalContentProvider();
2407 BrowserProvider bp = (BrowserProvider) prov;
2408 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2409 client.release();
2410
2411 Bundle bundle = createGoogleSearchSourceBundle(
2412 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2413 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2414 startSearch(result, false, bundle, false);
2415 }
2416
2417 private void startSearch(String initialQuery, boolean selectInitialQuery,
2418 Bundle appSearchData, boolean globalSearch) {
2419 if (appSearchData == null) {
2420 appSearchData = createGoogleSearchSourceBundle(
2421 GOOGLE_SEARCH_SOURCE_TYPE);
2422 }
2423
2424 SearchEngine searchEngine = mSettings.getSearchEngine();
2425 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2426 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2427 }
2428 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2429 globalSearch);
2430 }
2431
2432 private Bundle createGoogleSearchSourceBundle(String source) {
2433 Bundle bundle = new Bundle();
2434 bundle.putString(Search.SOURCE, source);
2435 return bundle;
2436 }
2437
2438 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002439 * helper method for key handler
2440 * returns the current tab if it can't advance
2441 */
Michael Kolbc831b632011-05-11 09:30:34 -07002442 private Tab getNextTab() {
2443 return mTabControl.getTab(Math.min(mTabControl.getTabCount() - 1,
2444 mTabControl.getCurrentPosition() + 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002445 }
2446
2447 /**
2448 * helper method for key handler
2449 * returns the current tab if it can't advance
2450 */
Michael Kolbc831b632011-05-11 09:30:34 -07002451 private Tab getPrevTab() {
2452 return mTabControl.getTab(Math.max(0,
2453 mTabControl.getCurrentPosition() - 1));
Michael Kolb0035fad2011-03-14 13:25:28 -07002454 }
2455
2456 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002457 * handle key events in browser
2458 *
2459 * @param keyCode
2460 * @param event
2461 * @return true if handled, false to pass to super
2462 */
2463 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002464 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07002465 // Even if MENU is already held down, we need to call to super to open
2466 // the IME on long press.
Michael Kolb2814a362011-05-19 15:49:41 -07002467 if (KeyEvent.KEYCODE_MENU == keyCode) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002468 if (mOptionsMenuHandler != null) {
2469 return false;
2470 } else {
2471 event.startTracking();
2472 return true;
2473 }
Michael Kolb2814a362011-05-19 15:49:41 -07002474 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002475 if (!noModifiers
2476 && ((KeyEvent.KEYCODE_MENU == keyCode)
2477 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2478 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002479 mMenuIsDown = true;
2480 return false;
2481 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002482
Cary Clark8ff8c662010-12-29 15:03:05 -05002483 WebView webView = getCurrentTopWebView();
2484 if (webView == null) return false;
2485
Cary Clark160bbb92011-01-10 11:17:07 -05002486 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2487 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002488
Michael Kolb8233fac2010-10-26 16:08:53 -07002489 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002490 case KeyEvent.KEYCODE_TAB:
2491 if (event.isCtrlPressed()) {
2492 if (event.isShiftPressed()) {
2493 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07002494 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002495 } else {
2496 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07002497 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07002498 }
2499 return true;
2500 }
2501 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002502 case KeyEvent.KEYCODE_SPACE:
2503 // WebView/WebTextView handle the keys in the KeyDown. As
2504 // the Activity's shortcut keys are only handled when WebView
2505 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002506 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002507 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002508 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002509 pageDown();
2510 }
2511 return true;
2512 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002513 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002514 event.startTracking();
2515 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002516 case KeyEvent.KEYCODE_DPAD_LEFT:
2517 if (ctrl) {
2518 webView.goBack();
2519 return true;
2520 }
2521 break;
2522 case KeyEvent.KEYCODE_DPAD_RIGHT:
2523 if (ctrl) {
2524 webView.goForward();
2525 return true;
2526 }
2527 break;
2528 case KeyEvent.KEYCODE_A:
2529 if (ctrl) {
2530 webView.selectAll();
2531 return true;
2532 }
2533 break;
Michael Kolba4183062011-01-16 10:43:21 -08002534// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002535 case KeyEvent.KEYCODE_C:
2536 if (ctrl) {
2537 webView.copySelection();
2538 return true;
2539 }
2540 break;
Michael Kolba4183062011-01-16 10:43:21 -08002541// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002542// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002543// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002544// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002545// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002546// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002547// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002548// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002549// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002550// case KeyEvent.KEYCODE_M: // unused
2551// case KeyEvent.KEYCODE_N: // in Chrome: new window
2552// case KeyEvent.KEYCODE_O: // in Chrome: open file
2553// case KeyEvent.KEYCODE_P: // in Chrome: print page
2554// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002555// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002556// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2557 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002558 // we can't use the ctrl/shift flags, they check for
2559 // exclusive use of a modifier
2560 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002561 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07002562 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05002563 } else {
2564 openTabToHomePage();
2565 }
2566 return true;
2567 }
2568 break;
2569// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2570// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb1a2eba42011-03-16 16:42:49 -07002571 case KeyEvent.KEYCODE_W: // in Chrome: close tab
2572 if (ctrl) {
2573 closeCurrentTab();
2574 return true;
2575 }
2576 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002577// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2578// case KeyEvent.KEYCODE_Y: // unused
2579// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002580 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002581 // it is a regular key and webview is not null
2582 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002583 }
2584
John Recke6bf4ab2011-02-24 15:48:05 -08002585 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2586 switch(keyCode) {
2587 case KeyEvent.KEYCODE_BACK:
2588 if (mUi.showsWeb()) {
2589 bookmarksOrHistoryPicker(true);
2590 return true;
2591 }
2592 break;
2593 }
2594 return false;
2595 }
2596
Michael Kolb8233fac2010-10-26 16:08:53 -07002597 boolean onKeyUp(int keyCode, KeyEvent event) {
Michael Kolb2814a362011-05-19 15:49:41 -07002598 if (KeyEvent.KEYCODE_MENU == keyCode) {
2599 mMenuIsDown = false;
2600 if (event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07002601 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07002602 }
2603 }
Cary Clark160bbb92011-01-10 11:17:07 -05002604 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002605 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002606 case KeyEvent.KEYCODE_BACK:
2607 if (event.isTracking() && !event.isCanceled()) {
2608 onBackKey();
2609 return true;
2610 }
2611 break;
2612 }
2613 return false;
2614 }
2615
2616 public boolean isMenuDown() {
2617 return mMenuIsDown;
2618 }
2619
Ben Murdoch8029a772010-11-16 11:58:21 +00002620 public void setupAutoFill(Message message) {
2621 // Open the settings activity at the AutoFill profile fragment so that
2622 // the user can create a new profile. When they return, we will dispatch
2623 // the message so that we can autofill the form using their new profile.
2624 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2625 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2626 AutoFillSettingsFragment.class.getName());
2627 mAutoFillSetupMessage = message;
2628 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2629 }
John Reckb3417f02011-01-14 11:01:05 -08002630
2631 @Override
2632 public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
2633 mOptionsMenuHandler = handler;
2634 }
2635
2636 @Override
2637 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
2638 if (mOptionsMenuHandler == handler) {
2639 mOptionsMenuHandler = null;
2640 }
2641 }
2642
Narayan Kamath5119edd2011-02-23 15:49:17 +00002643 @Override
2644 public void registerDropdownChangeListener(DropdownChangeListener d) {
2645 mUi.registerDropdownChangeListener(d);
2646 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002647}