blob: 0f33380e45a51fae7e1a10641922a85da6c96485 [file] [log] [blame]
Michael Kolb8233fac2010-10-26 16:08:53 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
19import com.android.browser.IntentHandler.UrlData;
Narayan Kamath5119edd2011-02-23 15:49:17 +000020import com.android.browser.UI.DropdownChangeListener;
Michael Kolb8233fac2010-10-26 16:08:53 -070021import com.android.browser.search.SearchEngine;
22import com.android.common.Search;
23
24import android.app.Activity;
25import android.app.DownloadManager;
26import android.app.SearchManager;
27import android.content.ClipboardManager;
28import android.content.ContentProvider;
29import android.content.ContentProviderClient;
30import android.content.ContentResolver;
31import android.content.ContentValues;
32import android.content.Context;
33import android.content.Intent;
34import android.content.pm.PackageManager;
35import android.content.pm.ResolveInfo;
36import android.content.res.Configuration;
Leon Scroggins1961ed22010-12-07 15:22:21 -050037import android.database.ContentObserver;
Michael Kolb8233fac2010-10-26 16:08:53 -070038import android.database.Cursor;
39import android.database.sqlite.SQLiteDatabase;
Michael Kolb8233fac2010-10-26 16:08:53 -070040import android.graphics.Bitmap;
41import android.graphics.Canvas;
42import android.graphics.Picture;
43import android.net.Uri;
44import android.net.http.SslError;
45import android.os.AsyncTask;
46import android.os.Bundle;
Leon Scrogginsac993842011-02-02 12:54:07 -050047import android.os.Environment;
Michael Kolb8233fac2010-10-26 16:08:53 -070048import android.os.Handler;
49import android.os.Message;
50import android.os.PowerManager;
51import android.os.PowerManager.WakeLock;
Ben Murdoch8029a772010-11-16 11:58:21 +000052import android.preference.PreferenceActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -070053import android.provider.Browser;
54import android.provider.BrowserContract;
Michael Kolb8233fac2010-10-26 16:08:53 -070055import android.provider.BrowserContract.Images;
56import android.provider.ContactsContract;
57import android.provider.ContactsContract.Intents.Insert;
Michael Kolbcfa3af52010-12-14 10:36:11 -080058import android.speech.RecognizerIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070059import android.speech.RecognizerResultsIntent;
60import android.text.TextUtils;
61import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080062import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070063import android.view.ActionMode;
64import android.view.ContextMenu;
65import android.view.ContextMenu.ContextMenuInfo;
66import android.view.Gravity;
67import android.view.KeyEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070068import android.view.Menu;
69import android.view.MenuInflater;
70import android.view.MenuItem;
71import android.view.MenuItem.OnMenuItemClickListener;
72import android.view.View;
73import android.webkit.CookieManager;
74import android.webkit.CookieSyncManager;
75import android.webkit.HttpAuthHandler;
76import android.webkit.SslErrorHandler;
77import android.webkit.ValueCallback;
78import android.webkit.WebChromeClient;
79import android.webkit.WebIconDatabase;
80import android.webkit.WebSettings;
81import android.webkit.WebView;
Leon Scrogginsac993842011-02-02 12:54:07 -050082import android.widget.Toast;
Michael Kolb8233fac2010-10-26 16:08:53 -070083
84import java.io.ByteArrayOutputStream;
85import java.io.File;
86import java.net.URLEncoder;
87import java.util.Calendar;
88import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -080089import java.util.List;
Michael Kolb8233fac2010-10-26 16:08:53 -070090
91/**
92 * Controller for browser
93 */
94public class Controller
95 implements WebViewController, UiController {
96
97 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -080098 private static final String SEND_APP_ID_EXTRA =
99 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
100
Michael Kolb8233fac2010-10-26 16:08:53 -0700101
102 // public message ids
103 public final static int LOAD_URL = 1001;
104 public final static int STOP_LOAD = 1002;
105
106 // Message Ids
107 private static final int FOCUS_NODE_HREF = 102;
108 private static final int RELEASE_WAKELOCK = 107;
109
110 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
111
112 private static final int OPEN_BOOKMARKS = 201;
113
114 private static final int EMPTY_MENU = -1;
115
Michael Kolb8233fac2010-10-26 16:08:53 -0700116 // activity requestCode
117 final static int PREFERENCES_PAGE = 3;
118 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000119 final static int AUTOFILL_SETUP = 5;
120
Michael Kolb8233fac2010-10-26 16:08:53 -0700121 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
122
123 // As the ids are dynamically created, we can't guarantee that they will
124 // be in sequence, so this static array maps ids to a window number.
125 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
126 { R.id.window_one_menu_id, R.id.window_two_menu_id,
127 R.id.window_three_menu_id, R.id.window_four_menu_id,
128 R.id.window_five_menu_id, R.id.window_six_menu_id,
129 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
130
131 // "source" parameter for Google search through search key
132 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
133 // "source" parameter for Google search through simplily type
134 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
135
136 private Activity mActivity;
137 private UI mUi;
138 private TabControl mTabControl;
139 private BrowserSettings mSettings;
140 private WebViewFactory mFactory;
John Reckb3417f02011-01-14 11:01:05 -0800141 private OptionsMenuHandler mOptionsMenuHandler = null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700142
143 private WakeLock mWakeLock;
144
145 private UrlHandler mUrlHandler;
146 private UploadHandler mUploadHandler;
147 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700148 private PageDialogsHandler mPageDialogsHandler;
149 private NetworkStateHandler mNetworkHandler;
150
Ben Murdoch8029a772010-11-16 11:58:21 +0000151 private Message mAutoFillSetupMessage;
152
Michael Kolb8233fac2010-10-26 16:08:53 -0700153 private boolean mShouldShowErrorConsole;
154
155 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
156
157 // FIXME, temp address onPrepareMenu performance problem.
158 // When we move everything out of view, we should rewrite this.
159 private int mCurrentMenuState = 0;
160 private int mMenuState = R.id.MAIN_MENU;
161 private int mOldMenuState = EMPTY_MENU;
162 private Menu mCachedMenu;
163
Michael Kolb8233fac2010-10-26 16:08:53 -0700164 private boolean mMenuIsDown;
165
166 // For select and find, we keep track of the ActionMode so that
167 // finish() can be called as desired.
168 private ActionMode mActionMode;
169
170 /**
171 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
172 * of whether the configuration has changed. The first onMenuOpened call
173 * after a configuration change is simply a reopening of the same menu
174 * (i.e. mIconView did not change).
175 */
176 private boolean mConfigChanged;
177
178 /**
179 * Keeps track of whether the options menu is open. This is important in
180 * determining whether to show or hide the title bar overlay
181 */
182 private boolean mOptionsMenuOpen;
183
184 /**
185 * Whether or not the options menu is in its bigger, popup menu form. When
186 * true, we want the title bar overlay to be gone. When false, we do not.
187 * Only meaningful if mOptionsMenuOpen is true.
188 */
189 private boolean mExtendedMenuOpen;
190
191 private boolean mInLoad;
192
193 private boolean mActivityPaused = true;
194 private boolean mLoadStopped;
195
196 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500197 // Checks to see when the bookmarks database has changed, and updates the
198 // Tabs' notion of whether they represent bookmarked sites.
199 private ContentObserver mBookmarksObserver;
John Reck0ebd3ac2010-12-09 11:14:04 -0800200 private DataController mDataController;
John Reck847b5322011-04-14 17:02:18 -0700201 private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700202
203 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
204 @Override
205 public Void doInBackground(File... files) {
206 if (files != null) {
207 for (File f : files) {
208 if (!f.delete()) {
209 Log.e(LOGTAG, f.getPath() + " was not deleted");
210 }
211 }
212 }
213 return null;
214 }
215 }
216
217 public Controller(Activity browser) {
218 mActivity = browser;
219 mSettings = BrowserSettings.getInstance();
John Reck0ebd3ac2010-12-09 11:14:04 -0800220 mDataController = DataController.getInstance(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700221 mTabControl = new TabControl(this);
222 mSettings.setController(this);
John Reck847b5322011-04-14 17:02:18 -0700223 mCrashRecoveryHandler = new CrashRecoveryHandler(this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700224
225 mUrlHandler = new UrlHandler(this);
226 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700227 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
228
229 PowerManager pm = (PowerManager) mActivity
230 .getSystemService(Context.POWER_SERVICE);
231 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
232
233 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500234 mBookmarksObserver = new ContentObserver(mHandler) {
235 @Override
236 public void onChange(boolean selfChange) {
237 int size = mTabControl.getTabCount();
238 for (int i = 0; i < size; i++) {
239 mTabControl.getTab(i).updateBookmarkedStatus();
240 }
241 }
242
243 };
244 browser.getContentResolver().registerContentObserver(
245 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700246
247 mNetworkHandler = new NetworkStateHandler(mActivity, this);
248 // Start watching the default geolocation permissions
249 mSystemAllowGeolocationOrigins =
250 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
251 mSystemAllowGeolocationOrigins.start();
252
253 retainIconsOnStartup();
254 }
255
Patrick Scott7d50a932011-02-04 09:27:26 -0500256 void start(final Bundle icicle, final Intent intent) {
John Reck847b5322011-04-14 17:02:18 -0700257 if (icicle != null) {
258 mCrashRecoveryHandler.clearState();
259 doStart(icicle, intent);
260 } else {
261 mCrashRecoveryHandler.startRecovery(intent);
262 }
263 }
264
265 void doStart(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700266 // Unless the last browser usage was within 24 hours, destroy any
267 // remaining incognito tabs.
268
269 Calendar lastActiveDate = icicle != null ?
270 (Calendar) icicle.getSerializable("lastActiveDate") : null;
271 Calendar today = Calendar.getInstance();
272 Calendar yesterday = Calendar.getInstance();
273 yesterday.add(Calendar.DATE, -1);
274
Patrick Scott7d50a932011-02-04 09:27:26 -0500275 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700276 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800277 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700278
Patrick Scott7d50a932011-02-04 09:27:26 -0500279 // Find out if we will restore any state and remember the tab.
280 final int currentTab =
281 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000282
Patrick Scott7d50a932011-02-04 09:27:26 -0500283 if (currentTab == -1) {
284 // Not able to restore so we go ahead and clear session cookies. We
285 // must do this before trying to login the user as we don't want to
286 // clear any session cookies set during login.
287 CookieManager.getInstance().removeSessionCookie();
288 }
289
Patrick Scottd43e75a2011-03-14 14:47:23 -0400290 GoogleAccountLogin.startLoginIfNeeded(mActivity,
Patrick Scott7d50a932011-02-04 09:27:26 -0500291 new Runnable() {
292 @Override public void run() {
John Reck847b5322011-04-14 17:02:18 -0700293 onPreloginFinished(icicle, intent, currentTab, restoreIncognitoTabs);
Patrick Scott7d50a932011-02-04 09:27:26 -0500294 }
295 });
296 }
297
John Reck847b5322011-04-14 17:02:18 -0700298 private void onPreloginFinished(Bundle icicle, Intent intent, int currentTab,
Patrick Scott7d50a932011-02-04 09:27:26 -0500299 boolean restoreIncognitoTabs) {
300 if (currentTab == -1) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700301 final Bundle extra = intent.getExtras();
302 // Create an initial tab.
303 // If the intent is ACTION_VIEW and data is not null, the Browser is
304 // invoked to view the content by another application. In this case,
305 // the tab will be close when exit.
306 UrlData urlData = mIntentHandler.getUrlDataFromIntent(intent);
307
308 String action = intent.getAction();
309 final Tab t = mTabControl.createNewTab(
310 (Intent.ACTION_VIEW.equals(action) &&
311 intent.getData() != null)
312 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
313 .equals(action),
314 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
315 urlData.mUrl, false);
316 addTab(t);
317 setActiveTab(t);
318 WebView webView = t.getWebView();
319 if (extra != null) {
320 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
321 if (scale > 0 && scale <= 1000) {
322 webView.setInitialScale(scale);
323 }
324 }
325
326 if (urlData.isEmpty()) {
327 loadUrl(webView, mSettings.getHomePage());
328 } else {
Michael Kolbcd424e92011-02-24 10:26:26 -0800329 // monkey protection against delayed start
330 if (t != null) {
331 loadUrlDataIn(t, urlData);
332 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700333 }
334 } else {
Patrick Scott7d50a932011-02-04 09:27:26 -0500335 mTabControl.restoreState(icicle, currentTab, restoreIncognitoTabs,
336 mUi.needsRestoreAllTabs());
Michael Kolb1bf23132010-11-19 12:55:12 -0800337 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700338 // TabControl.restoreState() will create a new tab even if
339 // restoring the state fails.
340 setActiveTab(mTabControl.getCurrentTab());
341 }
342 // clear up the thumbnail directory, which is no longer used;
343 // ideally this should only be run once after an upgrade from
344 // a previous version of the browser
345 new ClearThumbnails().execute(mTabControl.getThumbnailDir()
346 .listFiles());
347 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700348 String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb8233fac2010-10-26 16:08:53 -0700349 if (jsFlags.trim().length() != 0) {
350 getCurrentWebView().setJsFlags(jsFlags);
351 }
John Reck439c9a52010-12-14 10:04:39 -0800352 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
353 bookmarksOrHistoryPicker(false);
354 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700355 }
356
357 void setWebViewFactory(WebViewFactory factory) {
358 mFactory = factory;
359 }
360
Michael Kolb1514bb72010-11-22 09:11:48 -0800361 @Override
362 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700363 return mFactory;
364 }
365
366 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800367 public void onSetWebView(Tab tab, WebView view) {
368 mUi.onSetWebView(tab, view);
369 }
370
371 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800372 public void createSubWindow(Tab tab) {
373 endActionMode();
374 WebView mainView = tab.getWebView();
375 WebView subView = mFactory.createWebView((mainView == null)
376 ? false
377 : mainView.isPrivateBrowsingEnabled());
378 mUi.createSubWindow(tab, subView);
379 }
380
381 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700382 public Activity getActivity() {
383 return mActivity;
384 }
385
386 void setUi(UI ui) {
387 mUi = ui;
388 }
389
390 BrowserSettings getSettings() {
391 return mSettings;
392 }
393
394 IntentHandler getIntentHandler() {
395 return mIntentHandler;
396 }
397
398 @Override
399 public UI getUi() {
400 return mUi;
401 }
402
403 int getMaxTabs() {
404 return mActivity.getResources().getInteger(R.integer.max_tabs);
405 }
406
407 @Override
408 public TabControl getTabControl() {
409 return mTabControl;
410 }
411
Michael Kolb1bf23132010-11-19 12:55:12 -0800412 @Override
413 public List<Tab> getTabs() {
414 return mTabControl.getTabs();
415 }
416
Michael Kolb8233fac2010-10-26 16:08:53 -0700417 // Open the icon database and retain all the icons for visited sites.
Ben Murdoch9446b932010-11-25 16:20:14 +0000418 // This is done on a background thread so as not to stall startup.
Michael Kolb8233fac2010-10-26 16:08:53 -0700419 private void retainIconsOnStartup() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000420 // WebIconDatabase needs to be retrieved on the UI thread so that if
421 // it has not been created successfully yet the Handler is started on the
422 // UI thread.
423 new RetainIconsOnStartupTask(WebIconDatabase.getInstance()).execute();
424 }
425
426 private class RetainIconsOnStartupTask extends AsyncTask<Void, Void, Void> {
427 private WebIconDatabase mDb;
428
429 public RetainIconsOnStartupTask(WebIconDatabase db) {
430 mDb = db;
431 }
432
John Recka00cbbd2010-12-16 12:38:19 -0800433 @Override
Ben Murdoch9446b932010-11-25 16:20:14 +0000434 protected Void doInBackground(Void... unused) {
435 mDb.open(mActivity.getDir("icons", 0).getPath());
436 Cursor c = null;
437 try {
438 c = Browser.getAllBookmarks(mActivity.getContentResolver());
439 if (c.moveToFirst()) {
440 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
441 do {
442 String url = c.getString(urlIndex);
443 mDb.retainIconForPageUrl(url);
444 } while (c.moveToNext());
445 }
446 } catch (IllegalStateException e) {
447 Log.e(LOGTAG, "retainIconsOnStartup", e);
448 } finally {
449 if (c != null) c.close();
Michael Kolb8233fac2010-10-26 16:08:53 -0700450 }
Ben Murdoch9446b932010-11-25 16:20:14 +0000451
452 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700453 }
454 }
455
456 private void startHandler() {
457 mHandler = new Handler() {
458
459 @Override
460 public void handleMessage(Message msg) {
461 switch (msg.what) {
462 case OPEN_BOOKMARKS:
463 bookmarksOrHistoryPicker(false);
464 break;
465 case FOCUS_NODE_HREF:
466 {
467 String url = (String) msg.getData().get("url");
468 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500469 String src = (String) msg.getData().get("src");
470 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700471 if (TextUtils.isEmpty(url)) {
472 break;
473 }
474 HashMap focusNodeMap = (HashMap) msg.obj;
475 WebView view = (WebView) focusNodeMap.get("webview");
476 // Only apply the action if the top window did not change.
477 if (getCurrentTopWebView() != view) {
478 break;
479 }
480 switch (msg.arg1) {
481 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -0700482 loadUrlFromContext(getCurrentTopWebView(), url);
483 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500484 case R.id.view_image_context_menu_id:
485 loadUrlFromContext(getCurrentTopWebView(), src);
486 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500487 case R.id.open_newtab_context_menu_id:
488 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -0800489 final Tab newTab = openTab(parent, url, false);
Leon Scroggins026f2542010-11-22 13:26:12 -0500490 if (newTab != null && newTab != parent) {
491 parent.addChildTab(newTab);
492 }
493 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700494 case R.id.copy_link_context_menu_id:
495 copy(url);
496 break;
497 case R.id.save_link_context_menu_id:
498 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500499 DownloadHandler.onDownloadStartNoStream(
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000500 mActivity, url, null, null, null,
501 view.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -0700502 break;
503 }
504 break;
505 }
506
507 case LOAD_URL:
508 loadUrlFromContext(getCurrentTopWebView(), (String) msg.obj);
509 break;
510
511 case STOP_LOAD:
512 stopLoading();
513 break;
514
515 case RELEASE_WAKELOCK:
516 if (mWakeLock.isHeld()) {
517 mWakeLock.release();
518 // if we reach here, Browser should be still in the
519 // background loading after WAKELOCK_TIMEOUT (5-min).
520 // To avoid burning the battery, stop loading.
521 mTabControl.stopAllLoading();
522 }
523 break;
524
525 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800526 Tab tab = (Tab) msg.obj;
527 if (tab != null) {
528 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700529 }
530 break;
531 }
532 }
533 };
534
535 }
536
Michael Kolbba99c5d2010-11-29 14:57:41 -0800537 @Override
538 public void shareCurrentPage() {
539 shareCurrentPage(mTabControl.getCurrentTab());
540 }
541
542 private void shareCurrentPage(Tab tab) {
543 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800544 sharePage(mActivity, tab.getTitle(),
545 tab.getUrl(), tab.getFavicon(),
546 createScreenshot(tab.getWebView(),
547 getDesiredThumbnailWidth(mActivity),
548 getDesiredThumbnailHeight(mActivity)));
549 }
550 }
551
Michael Kolb8233fac2010-10-26 16:08:53 -0700552 /**
553 * Share a page, providing the title, url, favicon, and a screenshot. Uses
554 * an {@link Intent} to launch the Activity chooser.
555 * @param c Context used to launch a new Activity.
556 * @param title Title of the page. Stored in the Intent with
557 * {@link Intent#EXTRA_SUBJECT}
558 * @param url URL of the page. Stored in the Intent with
559 * {@link Intent#EXTRA_TEXT}
560 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
561 * with {@link Browser#EXTRA_SHARE_FAVICON}
562 * @param screenshot Bitmap of a screenshot of the page. Stored in the
563 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
564 */
565 static final void sharePage(Context c, String title, String url,
566 Bitmap favicon, Bitmap screenshot) {
567 Intent send = new Intent(Intent.ACTION_SEND);
568 send.setType("text/plain");
569 send.putExtra(Intent.EXTRA_TEXT, url);
570 send.putExtra(Intent.EXTRA_SUBJECT, title);
571 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
572 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
573 try {
574 c.startActivity(Intent.createChooser(send, c.getString(
575 R.string.choosertitle_sharevia)));
576 } catch(android.content.ActivityNotFoundException ex) {
577 // if no app handles it, do nothing
578 }
579 }
580
581 private void copy(CharSequence text) {
582 ClipboardManager cm = (ClipboardManager) mActivity
583 .getSystemService(Context.CLIPBOARD_SERVICE);
584 cm.setText(text);
585 }
586
587 // lifecycle
588
589 protected void onConfgurationChanged(Configuration config) {
590 mConfigChanged = true;
591 if (mPageDialogsHandler != null) {
592 mPageDialogsHandler.onConfigurationChanged(config);
593 }
594 mUi.onConfigurationChanged(config);
595 }
596
597 @Override
598 public void handleNewIntent(Intent intent) {
599 mIntentHandler.onNewIntent(intent);
600 }
601
602 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800603 if (mUi.isCustomViewShowing()) {
604 hideCustomView();
605 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700606 if (mActivityPaused) {
607 Log.e(LOGTAG, "BrowserActivity is already paused.");
608 return;
609 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700610 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800611 Tab tab = mTabControl.getCurrentTab();
612 if (tab != null) {
613 tab.pause();
614 if (!pauseWebViewTimers(tab)) {
615 mWakeLock.acquire();
616 mHandler.sendMessageDelayed(mHandler
617 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
618 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700619 }
620 mUi.onPause();
621 mNetworkHandler.onPause();
622
623 WebView.disablePlatformNotifications();
John Reck847b5322011-04-14 17:02:18 -0700624 mCrashRecoveryHandler.clearState();
Michael Kolb8233fac2010-10-26 16:08:53 -0700625 }
626
627 void onSaveInstanceState(Bundle outState) {
628 // the default implementation requires each view to have an id. As the
629 // browser handles the state itself and it doesn't use id for the views,
630 // don't call the default implementation. Otherwise it will trigger the
631 // warning like this, "couldn't save which view has focus because the
632 // focused view XXX has no id".
633
634 // Save all the tabs
635 mTabControl.saveState(outState);
636 // Save time so that we know how old incognito tabs (if any) are.
637 outState.putSerializable("lastActiveDate", Calendar.getInstance());
638 }
639
640 void onResume() {
641 if (!mActivityPaused) {
642 Log.e(LOGTAG, "BrowserActivity is already resumed.");
643 return;
644 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700645 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800646 Tab current = mTabControl.getCurrentTab();
647 if (current != null) {
648 current.resume();
649 resumeWebViewTimers(current);
650 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700651 if (mWakeLock.isHeld()) {
652 mHandler.removeMessages(RELEASE_WAKELOCK);
653 mWakeLock.release();
654 }
655 mUi.onResume();
656 mNetworkHandler.onResume();
657 WebView.enablePlatformNotifications();
658 }
659
Michael Kolb70976932010-11-30 11:34:01 -0800660 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800661 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800662 * @param tab guaranteed non-null
663 */
664 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700665 boolean inLoad = tab.inPageLoad();
666 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
667 CookieSyncManager.getInstance().startSync();
668 WebView w = tab.getWebView();
669 if (w != null) {
670 w.resumeTimers();
671 }
672 }
673 }
674
Michael Kolb70976932010-11-30 11:34:01 -0800675 /**
676 * Pause all WebView timers using the WebView of the given tab
677 * @param tab
678 * @return true if the timers are paused or tab is null
679 */
680 private boolean pauseWebViewTimers(Tab tab) {
681 if (tab == null) {
682 return true;
683 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700684 CookieSyncManager.getInstance().stopSync();
685 WebView w = getCurrentWebView();
686 if (w != null) {
687 w.pauseTimers();
688 }
689 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700690 }
Michael Kolb70976932010-11-30 11:34:01 -0800691 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700692 }
693
694 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800695 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700696 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
697 mUploadHandler = null;
698 }
699 if (mTabControl == null) return;
700 mUi.onDestroy();
701 // Remove the current tab and sub window
702 Tab t = mTabControl.getCurrentTab();
703 if (t != null) {
704 dismissSubWindow(t);
705 removeTab(t);
706 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500707 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700708 // Destroy all the tabs
709 mTabControl.destroy();
710 WebIconDatabase.getInstance().close();
711 // Stop watching the default geolocation permissions
712 mSystemAllowGeolocationOrigins.stop();
713 mSystemAllowGeolocationOrigins = null;
714 }
715
716 protected boolean isActivityPaused() {
717 return mActivityPaused;
718 }
719
720 protected void onLowMemory() {
721 mTabControl.freeMemory();
722 }
723
724 @Override
725 public boolean shouldShowErrorConsole() {
726 return mShouldShowErrorConsole;
727 }
728
729 protected void setShouldShowErrorConsole(boolean show) {
730 if (show == mShouldShowErrorConsole) {
731 // Nothing to do.
732 return;
733 }
734 mShouldShowErrorConsole = show;
735 Tab t = mTabControl.getCurrentTab();
736 if (t == null) {
737 // There is no current tab so we cannot toggle the error console
738 return;
739 }
740 mUi.setShouldShowErrorConsole(t, show);
741 }
742
743 @Override
744 public void stopLoading() {
745 mLoadStopped = true;
746 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700747 WebView w = getCurrentTopWebView();
748 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700749 mUi.onPageStopped(tab);
750 }
751
752 boolean didUserStopLoading() {
753 return mLoadStopped;
754 }
755
756 // WebViewController
757
758 @Override
John Reck324d4402011-01-11 16:56:42 -0800759 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700760
761 // We've started to load a new page. If there was a pending message
762 // to save a screenshot then we will now take the new page and save
763 // an incorrect screenshot. Therefore, remove any pending thumbnail
764 // messages from the queue.
765 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800766 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700767
768 // reset sync timer to avoid sync starts during loading a page
769 CookieSyncManager.getInstance().resetSync();
770
771 if (!mNetworkHandler.isNetworkUp()) {
772 view.setNetworkAvailable(false);
773 }
774
775 // when BrowserActivity just starts, onPageStarted may be called before
776 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
777 // to start the timer. As we won't switch tabs while an activity is in
778 // pause state, we can ensure calling resume and pause in pair.
779 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800780 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700781 }
782 mLoadStopped = false;
783 if (!mNetworkHandler.isNetworkUp()) {
784 mNetworkHandler.createAndShowNetworkDialog();
785 }
786 endActionMode();
787
John Reck30c714c2010-12-16 17:30:34 -0800788 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700789
John Reck324d4402011-01-11 16:56:42 -0800790 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700791 // update the bookmark database for favicon
792 maybeUpdateFavicon(tab, null, url, favicon);
793
794 Performance.tracePageStart(url);
795
796 // Performance probe
797 if (false) {
798 Performance.onPageStarted();
799 }
800
801 }
802
803 @Override
John Reck324d4402011-01-11 16:56:42 -0800804 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800805 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800806 if (!tab.isPrivateBrowsingEnabled()
807 && !TextUtils.isEmpty(tab.getUrl())) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700808 if (tab.inForeground() && !didUserStopLoading()
809 || !tab.inForeground()) {
810 // Only update the bookmark screenshot if the user did not
811 // cancel the load early.
812 mHandler.sendMessageDelayed(mHandler.obtainMessage(
John Reck34ef2672011-02-10 11:30:55 -0800813 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
Michael Kolb8233fac2010-10-26 16:08:53 -0700814 500);
815 }
816 }
817 // pause the WebView timer and release the wake lock if it is finished
818 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800819 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700820 if (mWakeLock.isHeld()) {
821 mHandler.removeMessages(RELEASE_WAKELOCK);
822 mWakeLock.release();
823 }
824 }
825 // Performance probe
826 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800827 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700828 }
829
830 Performance.tracePageFinished();
831 }
832
833 @Override
John Reck30c714c2010-12-16 17:30:34 -0800834 public void onProgressChanged(Tab tab) {
835 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700836
837 if (newProgress == 100) {
838 CookieSyncManager.getInstance().sync();
839 // onProgressChanged() may continue to be called after the main
840 // frame has finished loading, as any remaining sub frames continue
841 // to load. We'll only get called once though with newProgress as
842 // 100 when everything is loaded. (onPageFinished is called once
843 // when the main frame completes loading regardless of the state of
844 // any sub frames so calls to onProgressChanges may continue after
845 // onPageFinished has executed)
846 if (mInLoad) {
847 mInLoad = false;
848 updateInLoadMenuItems(mCachedMenu);
849 }
850 } else {
851 if (!mInLoad) {
852 // onPageFinished may have already been called but a subframe is
853 // still loading and updating the progress. Reset mInLoad and
854 // update the menu items.
855 mInLoad = true;
856 updateInLoadMenuItems(mCachedMenu);
857 }
858 }
John Reck30c714c2010-12-16 17:30:34 -0800859 mUi.onProgressChanged(tab);
860 }
861
862 @Override
863 public void onUpdatedLockIcon(Tab tab) {
864 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700865 }
866
867 @Override
868 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800869 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -0800870 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -0800871 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700872 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
873 return;
874 }
875 // Update the title in the history database if not in private browsing mode
876 if (!tab.isPrivateBrowsingEnabled()) {
John Reck0ebd3ac2010-12-09 11:14:04 -0800877 mDataController.updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700878 }
879 }
880
881 @Override
882 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800883 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700884 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
885 }
886
887 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800888 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
889 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700890 }
891
892 @Override
893 public boolean shouldOverrideKeyEvent(KeyEvent event) {
894 if (mMenuIsDown) {
895 // only check shortcut key when MENU is held
896 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
897 event);
898 } else {
899 return false;
900 }
901 }
902
903 @Override
904 public void onUnhandledKeyEvent(KeyEvent event) {
905 if (!isActivityPaused()) {
906 if (event.getAction() == KeyEvent.ACTION_DOWN) {
907 mActivity.onKeyDown(event.getKeyCode(), event);
908 } else {
909 mActivity.onKeyUp(event.getKeyCode(), event);
910 }
911 }
912 }
913
914 @Override
John Reck324d4402011-01-11 16:56:42 -0800915 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700916 // Don't save anything in private browsing mode
917 if (tab.isPrivateBrowsingEnabled()) return;
John Reck49a603c2011-03-03 09:33:05 -0800918 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700919
John Reck324d4402011-01-11 16:56:42 -0800920 if (TextUtils.isEmpty(url)
921 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700922 return;
923 }
John Reck0ebd3ac2010-12-09 11:14:04 -0800924 mDataController.updateVisitedHistory(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700925 WebIconDatabase.getInstance().retainIconForPageUrl(url);
John Reck847b5322011-04-14 17:02:18 -0700926 if (!mActivityPaused) {
927 // Since we clear the state in onPause, don't backup the current
928 // state if we are already paused
929 mCrashRecoveryHandler.backupState();
930 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700931 }
932
933 @Override
934 public void getVisitedHistory(final ValueCallback<String[]> callback) {
935 AsyncTask<Void, Void, String[]> task =
936 new AsyncTask<Void, Void, String[]>() {
937 @Override
938 public String[] doInBackground(Void... unused) {
939 return Browser.getVisitedHistory(mActivity.getContentResolver());
940 }
941 @Override
942 public void onPostExecute(String[] result) {
943 callback.onReceiveValue(result);
944 }
945 };
946 task.execute();
947 }
948
949 @Override
950 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
951 final HttpAuthHandler handler, final String host,
952 final String realm) {
953 String username = null;
954 String password = null;
955
956 boolean reuseHttpAuthUsernamePassword
957 = handler.useHttpAuthUsernamePassword();
958
959 if (reuseHttpAuthUsernamePassword && view != null) {
960 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
961 if (credentials != null && credentials.length == 2) {
962 username = credentials[0];
963 password = credentials[1];
964 }
965 }
966
967 if (username != null && password != null) {
968 handler.proceed(username, password);
969 } else {
970 if (tab.inForeground()) {
971 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
972 } else {
973 handler.cancel();
974 }
975 }
976 }
977
978 @Override
979 public void onDownloadStart(Tab tab, String url, String userAgent,
980 String contentDisposition, String mimetype, long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000981 WebView w = tab.getWebView();
Leon Scroggins63c02662010-11-18 15:16:27 -0500982 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000983 contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
984 if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700985 // This Tab was opened for the sole purpose of downloading a
986 // file. Remove it.
987 if (tab == mTabControl.getCurrentTab()) {
988 // In this case, the Tab is still on top.
989 goBackOnePageOrQuit();
990 } else {
991 // In this case, it is not.
992 closeTab(tab);
993 }
994 }
995 }
996
997 @Override
998 public Bitmap getDefaultVideoPoster() {
999 return mUi.getDefaultVideoPoster();
1000 }
1001
1002 @Override
1003 public View getVideoLoadingProgressView() {
1004 return mUi.getVideoLoadingProgressView();
1005 }
1006
1007 @Override
1008 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1009 SslError error) {
1010 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1011 }
1012
Patrick Scott92066772011-03-10 08:46:27 -05001013 @Override
1014 public void showAutoLogin(Tab tab) {
1015 assert tab.inForeground();
1016 // Update the title bar to show the auto-login request.
1017 mUi.showAutoLogin(tab);
1018 }
1019
1020 @Override
1021 public void hideAutoLogin(Tab tab) {
1022 assert tab.inForeground();
1023 mUi.hideAutoLogin(tab);
1024 }
1025
Michael Kolb8233fac2010-10-26 16:08:53 -07001026 // helper method
1027
1028 /*
1029 * Update the favorites icon if the private browsing isn't enabled and the
1030 * icon is valid.
1031 */
1032 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1033 final String url, Bitmap favicon) {
1034 if (favicon == null) {
1035 return;
1036 }
1037 if (!tab.isPrivateBrowsingEnabled()) {
1038 Bookmarks.updateFavicon(mActivity
1039 .getContentResolver(), originalUrl, url, favicon);
1040 }
1041 }
1042
Leon Scroggins4cd97792010-12-03 15:31:56 -05001043 @Override
1044 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001045 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001046 mUi.bookmarkedStatusHasChanged(tab);
1047 }
1048
Michael Kolb8233fac2010-10-26 16:08:53 -07001049 // end WebViewController
1050
1051 protected void pageUp() {
1052 getCurrentTopWebView().pageUp(false);
1053 }
1054
1055 protected void pageDown() {
1056 getCurrentTopWebView().pageDown(false);
1057 }
1058
1059 // callback from phone title bar
1060 public void editUrl() {
1061 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001062 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001063 }
1064
Michael Kolbcfa3af52010-12-14 10:36:11 -08001065 public void startVoiceSearch() {
1066 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1067 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1068 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1069 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1070 mActivity.getComponentName().flattenToString());
1071 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001072 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001073 mActivity.startActivity(intent);
1074 }
1075
Michael Kolb11d19782011-03-20 10:17:40 -07001076 @Override
1077 public void activateVoiceSearchMode(String title, List<String> results) {
1078 mUi.showVoiceTitleBar(title, results);
Michael Kolb8233fac2010-10-26 16:08:53 -07001079 }
1080
1081 public void revertVoiceSearchMode(Tab tab) {
1082 mUi.revertVoiceTitleBar(tab);
1083 }
1084
Michael Kolb736990c2011-03-20 10:01:20 -07001085 public boolean supportsVoiceSearch() {
John Reck35e9dd62011-04-25 09:01:54 -07001086 SearchEngine searchEngine = getSettings().getSearchEngine();
Michael Kolb736990c2011-03-20 10:01:20 -07001087 return (searchEngine != null && searchEngine.supportsVoiceSearch());
1088 }
1089
Michael Kolb8233fac2010-10-26 16:08:53 -07001090 public void showCustomView(Tab tab, View view,
1091 WebChromeClient.CustomViewCallback callback) {
1092 if (tab.inForeground()) {
1093 if (mUi.isCustomViewShowing()) {
1094 callback.onCustomViewHidden();
1095 return;
1096 }
1097 mUi.showCustomView(view, callback);
1098 // Save the menu state and set it to empty while the custom
1099 // view is showing.
1100 mOldMenuState = mMenuState;
1101 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001102 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001103 }
1104 }
1105
1106 @Override
1107 public void hideCustomView() {
1108 if (mUi.isCustomViewShowing()) {
1109 mUi.onHideCustomView();
1110 // Reset the old menu state.
1111 mMenuState = mOldMenuState;
1112 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001113 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001114 }
1115 }
1116
1117 protected void onActivityResult(int requestCode, int resultCode,
1118 Intent intent) {
1119 if (getCurrentTopWebView() == null) return;
1120 switch (requestCode) {
1121 case PREFERENCES_PAGE:
1122 if (resultCode == Activity.RESULT_OK && intent != null) {
1123 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001124 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001125 mTabControl.removeParentChildRelationShips();
1126 }
1127 }
1128 break;
1129 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001130 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001131 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001132 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001133 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001134 case AUTOFILL_SETUP:
1135 // Determine whether a profile was actually set up or not
1136 // and if so, send the message back to the WebTextView to
1137 // fill the form with the new profile.
1138 if (getSettings().getAutoFillProfile() != null) {
1139 mAutoFillSetupMessage.sendToTarget();
1140 mAutoFillSetupMessage = null;
1141 }
1142 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001143 default:
1144 break;
1145 }
1146 getCurrentTopWebView().requestFocus();
1147 }
1148
1149 /**
1150 * Open the Go page.
1151 * @param startWithHistory If true, open starting on the history tab.
1152 * Otherwise, start with the bookmarks tab.
1153 */
1154 @Override
1155 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1156 if (mTabControl.getCurrentWebView() == null) {
1157 return;
1158 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001159 // clear action mode
1160 if (isInCustomActionMode()) {
1161 endActionMode();
1162 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001163 Bundle extras = new Bundle();
1164 // Disable opening in a new window if we have maxed out the windows
1165 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1166 !mTabControl.canCreateNewTab());
1167 mUi.showComboView(startWithHistory, extras);
1168 }
1169
1170 // combo view callbacks
1171
1172 /**
1173 * callback from ComboPage when clear history is requested
1174 */
1175 public void onRemoveParentChildRelationships() {
1176 mTabControl.removeParentChildRelationShips();
1177 }
1178
1179 /**
1180 * callback from ComboPage when bookmark/history selection
1181 */
1182 @Override
1183 public void onUrlSelected(String url, boolean newTab) {
1184 removeComboView();
1185 if (!TextUtils.isEmpty(url)) {
1186 if (newTab) {
Michael Kolb18eb3772010-12-10 14:29:51 -08001187 openTab(mTabControl.getCurrentTab(), url, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001188 } else {
1189 final Tab currentTab = mTabControl.getCurrentTab();
1190 dismissSubWindow(currentTab);
1191 loadUrl(getCurrentTopWebView(), url);
1192 }
1193 }
1194 }
1195
1196 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07001197 * dismiss the ComboPage
1198 */
1199 @Override
1200 public void removeComboView() {
1201 mUi.hideComboView();
1202 }
1203
1204 // active tabs page handling
1205
1206 protected void showActiveTabsPage() {
1207 mMenuState = EMPTY_MENU;
1208 mUi.showActiveTabsPage();
1209 }
1210
1211 /**
1212 * Remove the active tabs page.
1213 * @param needToAttach If true, the active tabs page did not attach a tab
1214 * to the content view, so we need to do that here.
1215 */
1216 @Override
1217 public void removeActiveTabsPage(boolean needToAttach) {
1218 mMenuState = R.id.MAIN_MENU;
1219 mUi.removeActiveTabsPage();
1220 if (needToAttach) {
1221 setActiveTab(mTabControl.getCurrentTab());
1222 }
1223 getCurrentTopWebView().requestFocus();
1224 }
1225
1226 // key handling
1227 protected void onBackKey() {
1228 if (!mUi.onBackKey()) {
1229 WebView subwindow = mTabControl.getCurrentSubWindow();
1230 if (subwindow != null) {
1231 if (subwindow.canGoBack()) {
1232 subwindow.goBack();
1233 } else {
1234 dismissSubWindow(mTabControl.getCurrentTab());
1235 }
1236 } else {
1237 goBackOnePageOrQuit();
1238 }
1239 }
1240 }
1241
1242 // menu handling and state
1243 // TODO: maybe put into separate handler
1244
1245 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckb3417f02011-01-14 11:01:05 -08001246 if (mOptionsMenuHandler != null) {
1247 return mOptionsMenuHandler.onCreateOptionsMenu(menu);
1248 }
1249
John Reckd73c5a22010-12-22 10:22:50 -08001250 if (mMenuState == EMPTY_MENU) {
1251 return false;
1252 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001253 MenuInflater inflater = mActivity.getMenuInflater();
1254 inflater.inflate(R.menu.browser, menu);
1255 updateInLoadMenuItems(menu);
1256 // hold on to the menu reference here; it is used by the page callbacks
1257 // to update the menu based on loading state
1258 mCachedMenu = menu;
1259 return true;
1260 }
1261
1262 protected void onCreateContextMenu(ContextMenu menu, View v,
1263 ContextMenuInfo menuInfo) {
1264 if (v instanceof TitleBarBase) {
1265 return;
1266 }
1267 if (!(v instanceof WebView)) {
1268 return;
1269 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001270 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001271 WebView.HitTestResult result = webview.getHitTestResult();
1272 if (result == null) {
1273 return;
1274 }
1275
1276 int type = result.getType();
1277 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1278 Log.w(LOGTAG,
1279 "We should not show context menu when nothing is touched");
1280 return;
1281 }
1282 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1283 // let TextView handles context menu
1284 return;
1285 }
1286
1287 // Note, http://b/issue?id=1106666 is requesting that
1288 // an inflated menu can be used again. This is not available
1289 // yet, so inflate each time (yuk!)
1290 MenuInflater inflater = mActivity.getMenuInflater();
1291 inflater.inflate(R.menu.browsercontext, menu);
1292
1293 // Show the correct menu group
1294 final String extra = result.getExtra();
1295 menu.setGroupVisible(R.id.PHONE_MENU,
1296 type == WebView.HitTestResult.PHONE_TYPE);
1297 menu.setGroupVisible(R.id.EMAIL_MENU,
1298 type == WebView.HitTestResult.EMAIL_TYPE);
1299 menu.setGroupVisible(R.id.GEO_MENU,
1300 type == WebView.HitTestResult.GEO_TYPE);
1301 menu.setGroupVisible(R.id.IMAGE_MENU,
1302 type == WebView.HitTestResult.IMAGE_TYPE
1303 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1304 menu.setGroupVisible(R.id.ANCHOR_MENU,
1305 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1306 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001307 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1308 || type == WebView.HitTestResult.PHONE_TYPE
1309 || type == WebView.HitTestResult.EMAIL_TYPE
1310 || type == WebView.HitTestResult.GEO_TYPE;
1311 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1312 if (hitText) {
1313 menu.findItem(R.id.select_text_menu_id)
1314 .setOnMenuItemClickListener(new SelectText(webview));
1315 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001316 // Setup custom handling depending on the type
1317 switch (type) {
1318 case WebView.HitTestResult.PHONE_TYPE:
1319 menu.setHeaderTitle(Uri.decode(extra));
1320 menu.findItem(R.id.dial_context_menu_id).setIntent(
1321 new Intent(Intent.ACTION_VIEW, Uri
1322 .parse(WebView.SCHEME_TEL + extra)));
1323 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1324 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1325 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1326 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1327 addIntent);
1328 menu.findItem(R.id.copy_phone_context_menu_id)
1329 .setOnMenuItemClickListener(
1330 new Copy(extra));
1331 break;
1332
1333 case WebView.HitTestResult.EMAIL_TYPE:
1334 menu.setHeaderTitle(extra);
1335 menu.findItem(R.id.email_context_menu_id).setIntent(
1336 new Intent(Intent.ACTION_VIEW, Uri
1337 .parse(WebView.SCHEME_MAILTO + extra)));
1338 menu.findItem(R.id.copy_mail_context_menu_id)
1339 .setOnMenuItemClickListener(
1340 new Copy(extra));
1341 break;
1342
1343 case WebView.HitTestResult.GEO_TYPE:
1344 menu.setHeaderTitle(extra);
1345 menu.findItem(R.id.map_context_menu_id).setIntent(
1346 new Intent(Intent.ACTION_VIEW, Uri
1347 .parse(WebView.SCHEME_GEO
1348 + URLEncoder.encode(extra))));
1349 menu.findItem(R.id.copy_geo_context_menu_id)
1350 .setOnMenuItemClickListener(
1351 new Copy(extra));
1352 break;
1353
1354 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1355 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001356 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001357 // decide whether to show the open link in new tab option
1358 boolean showNewTab = mTabControl.canCreateNewTab();
1359 MenuItem newTabItem
1360 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001361 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001362 ? R.string.contextmenu_openlink_newwindow_background
1363 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001364 newTabItem.setVisible(showNewTab);
1365 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001366 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1367 newTabItem.setOnMenuItemClickListener(
1368 new MenuItem.OnMenuItemClickListener() {
1369 @Override
1370 public boolean onMenuItemClick(MenuItem item) {
1371 final HashMap<String, WebView> hrefMap =
1372 new HashMap<String, WebView>();
1373 hrefMap.put("webview", webview);
1374 final Message msg = mHandler.obtainMessage(
1375 FOCUS_NODE_HREF,
1376 R.id.open_newtab_context_menu_id,
1377 0, hrefMap);
1378 webview.requestFocusNodeHref(msg);
1379 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001380 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001381 });
1382 } else {
1383 newTabItem.setOnMenuItemClickListener(
1384 new MenuItem.OnMenuItemClickListener() {
1385 @Override
1386 public boolean onMenuItemClick(MenuItem item) {
1387 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -08001388 final Tab newTab = openTab(parent,
1389 extra, false);
Leon Scroggins026f2542010-11-22 13:26:12 -05001390 if (newTab != parent) {
1391 parent.addChildTab(newTab);
1392 }
1393 return true;
1394 }
1395 });
1396 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001397 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001398 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1399 break;
1400 }
1401 // otherwise fall through to handle image part
1402 case WebView.HitTestResult.IMAGE_TYPE:
1403 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1404 menu.setHeaderTitle(extra);
1405 }
1406 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1407 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1408 menu.findItem(R.id.download_context_menu_id).
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001409 setOnMenuItemClickListener(
1410 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
John Reck3527dd12011-02-22 10:35:29 -08001411 menu.findItem(R.id.set_wallpaper_context_menu_id).
1412 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1413 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001414 break;
1415
1416 default:
1417 Log.w(LOGTAG, "We should not get here.");
1418 break;
1419 }
1420 //update the ui
1421 mUi.onContextMenuCreated(menu);
1422 }
1423
1424 /**
1425 * As the menu can be open when loading state changes
1426 * we must manually update the state of the stop/reload menu
1427 * item
1428 */
1429 private void updateInLoadMenuItems(Menu menu) {
1430 if (menu == null) {
1431 return;
1432 }
1433 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1434 MenuItem src = mInLoad ?
1435 menu.findItem(R.id.stop_menu_id):
1436 menu.findItem(R.id.reload_menu_id);
1437 if (src != null) {
1438 dest.setIcon(src.getIcon());
1439 dest.setTitle(src.getTitle());
1440 }
1441 }
1442
John Reckb3417f02011-01-14 11:01:05 -08001443 boolean onPrepareOptionsMenu(Menu menu) {
1444 if (mOptionsMenuHandler != null) {
1445 return mOptionsMenuHandler.onPrepareOptionsMenu(menu);
1446 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001447 // Note: setVisible will decide whether an item is visible; while
1448 // setEnabled() will decide whether an item is enabled, which also means
1449 // whether the matching shortcut key will function.
1450 switch (mMenuState) {
1451 case EMPTY_MENU:
1452 if (mCurrentMenuState != mMenuState) {
1453 menu.setGroupVisible(R.id.MAIN_MENU, false);
1454 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1455 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1456 }
1457 break;
1458 default:
1459 if (mCurrentMenuState != mMenuState) {
1460 menu.setGroupVisible(R.id.MAIN_MENU, true);
1461 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1462 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1463 }
1464 final WebView w = getCurrentTopWebView();
1465 boolean canGoBack = false;
1466 boolean canGoForward = false;
1467 boolean isHome = false;
1468 if (w != null) {
1469 canGoBack = w.canGoBack();
1470 canGoForward = w.canGoForward();
1471 isHome = mSettings.getHomePage().equals(w.getUrl());
1472 }
1473 final MenuItem back = menu.findItem(R.id.back_menu_id);
1474 back.setEnabled(canGoBack);
1475
1476 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1477 home.setEnabled(!isHome);
1478
1479 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1480 forward.setEnabled(canGoForward);
1481
1482 // decide whether to show the share link option
1483 PackageManager pm = mActivity.getPackageManager();
1484 Intent send = new Intent(Intent.ACTION_SEND);
1485 send.setType("text/plain");
1486 ResolveInfo ri = pm.resolveActivity(send,
1487 PackageManager.MATCH_DEFAULT_ONLY);
1488 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1489
John Reck35e9dd62011-04-25 09:01:54 -07001490 boolean isNavDump = mSettings.enableNavDump();
Michael Kolb8233fac2010-10-26 16:08:53 -07001491 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1492 nav.setVisible(isNavDump);
1493 nav.setEnabled(isNavDump);
1494
John Reck35e9dd62011-04-25 09:01:54 -07001495 boolean showDebugSettings = mSettings.isDebugEnabled();
Michael Kolb8233fac2010-10-26 16:08:53 -07001496 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1497 counter.setVisible(showDebugSettings);
1498 counter.setEnabled(showDebugSettings);
1499
John Reckb3417f02011-01-14 11:01:05 -08001500 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1501 newtab.setEnabled(getTabControl().canCreateNewTab());
Michael Kolb8233fac2010-10-26 16:08:53 -07001502
Leon Scroggins81983762011-02-11 15:17:36 -05001503 MenuItem archive = menu.findItem(R.id.save_webarchive_menu_id);
John Reck51d8bad2011-02-28 15:47:47 -08001504 Tab tab = getTabControl().getCurrentTab();
1505 String url = tab != null ? tab.getUrl() : null;
1506 archive.setVisible(!TextUtils.isEmpty(url)
1507 && !url.endsWith(".webarchivexml"));
Michael Kolb8233fac2010-10-26 16:08:53 -07001508 break;
1509 }
1510 mCurrentMenuState = mMenuState;
Michael Kolb1acef692011-03-08 14:12:06 -08001511 return mUi.onPrepareOptionsMenu(menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001512 }
1513
1514 public boolean onOptionsItemSelected(MenuItem item) {
John Reckb3417f02011-01-14 11:01:05 -08001515 if (mOptionsMenuHandler != null &&
1516 mOptionsMenuHandler.onOptionsItemSelected(item)) {
1517 return true;
1518 }
1519
Michael Kolb8233fac2010-10-26 16:08:53 -07001520 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1521 // menu remains active, so ensure comboview is dismissed
1522 // if main menu option is selected
1523 removeComboView();
1524 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001525 if (null == getCurrentTopWebView()) {
1526 return false;
1527 }
1528 if (mMenuIsDown) {
1529 // The shortcut action consumes the MENU. Even if it is still down,
1530 // it won't trigger the next shortcut action. In the case of the
1531 // shortcut action triggering a new activity, like Bookmarks, we
1532 // won't get onKeyUp for MENU. So it is important to reset it here.
1533 mMenuIsDown = false;
1534 }
1535 switch (item.getItemId()) {
1536 // -- Main menu
1537 case R.id.new_tab_menu_id:
1538 openTabToHomePage();
1539 break;
1540
1541 case R.id.incognito_menu_id:
1542 openIncognitoTab();
1543 break;
1544
1545 case R.id.goto_menu_id:
1546 editUrl();
1547 break;
1548
1549 case R.id.bookmarks_menu_id:
1550 bookmarksOrHistoryPicker(false);
1551 break;
1552
1553 case R.id.active_tabs_menu_id:
1554 showActiveTabsPage();
1555 break;
1556
1557 case R.id.add_bookmark_menu_id:
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001558 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001559 break;
1560
1561 case R.id.stop_reload_menu_id:
1562 if (mInLoad) {
1563 stopLoading();
1564 } else {
1565 getCurrentTopWebView().reload();
1566 }
1567 break;
1568
1569 case R.id.back_menu_id:
1570 getCurrentTopWebView().goBack();
1571 break;
1572
1573 case R.id.forward_menu_id:
1574 getCurrentTopWebView().goForward();
1575 break;
1576
1577 case R.id.close_menu_id:
1578 // Close the subwindow if it exists.
1579 if (mTabControl.getCurrentSubWindow() != null) {
1580 dismissSubWindow(mTabControl.getCurrentTab());
1581 break;
1582 }
1583 closeCurrentTab();
1584 break;
1585
1586 case R.id.homepage_menu_id:
1587 Tab current = mTabControl.getCurrentTab();
1588 if (current != null) {
1589 dismissSubWindow(current);
1590 loadUrl(current.getWebView(), mSettings.getHomePage());
1591 }
1592 break;
1593
1594 case R.id.preferences_menu_id:
1595 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1596 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1597 getCurrentTopWebView().getUrl());
1598 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1599 break;
1600
1601 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001602 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001603 break;
1604
Leon Scrogginsac993842011-02-02 12:54:07 -05001605 case R.id.save_webarchive_menu_id:
1606 String state = Environment.getExternalStorageState();
1607 if (!Environment.MEDIA_MOUNTED.equals(state)) {
1608 Log.e(LOGTAG, "External storage not mounted");
1609 Toast.makeText(mActivity, R.string.webarchive_failed,
1610 Toast.LENGTH_SHORT).show();
1611 break;
1612 }
1613 final String directory = Environment.getExternalStoragePublicDirectory(
1614 Environment.DIRECTORY_DOWNLOADS) + File.separator;
1615 File dir = new File(directory);
1616 if (!dir.exists() && !dir.mkdirs()) {
1617 Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
1618 Toast.makeText(mActivity, R.string.webarchive_failed,
1619 Toast.LENGTH_SHORT).show();
1620 break;
1621 }
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001622 final WebView topWebView = getCurrentTopWebView();
Leon Scrogginsac993842011-02-02 12:54:07 -05001623 final String title = topWebView.getTitle();
John Reck51d8bad2011-02-28 15:47:47 -08001624 final String url = topWebView.getUrl();
Leon Scrogginsac993842011-02-02 12:54:07 -05001625 topWebView.saveWebArchive(directory, true,
1626 new ValueCallback<String>() {
1627 @Override
1628 public void onReceiveValue(final String value) {
1629 if (value != null) {
1630 File file = new File(value);
1631 final long length = file.length();
1632 if (file.exists() && length > 0) {
Leon Scroggins1cb96552011-02-11 14:22:57 -05001633 Toast.makeText(mActivity, R.string.webarchive_saved,
1634 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001635 final DownloadManager manager = (DownloadManager) mActivity
1636 .getSystemService(Context.DOWNLOAD_SERVICE);
1637 new Thread("Add WebArchive to download manager") {
1638 @Override
1639 public void run() {
Vasu Noria9e30a72011-03-07 11:37:34 -08001640 manager.addCompletedDownload(
1641 null == title ? value : title,
Leon Scrogginsac993842011-02-02 12:54:07 -05001642 value, true, "application/x-webarchive-xml",
1643 value, length, true);
1644 }
1645 }.start();
1646 return;
1647 }
1648 }
John Reck51d8bad2011-02-28 15:47:47 -08001649 DownloadHandler.onDownloadStartNoStream(mActivity,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001650 url, null, null, null, topWebView.isPrivateBrowsingEnabled());
Leon Scrogginsac993842011-02-02 12:54:07 -05001651 }
1652 });
1653 break;
1654
Michael Kolb8233fac2010-10-26 16:08:53 -07001655 case R.id.page_info_menu_id:
1656 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1657 false);
1658 break;
1659
1660 case R.id.classic_history_menu_id:
1661 bookmarksOrHistoryPicker(true);
1662 break;
1663
1664 case R.id.title_bar_share_page_url:
1665 case R.id.share_page_menu_id:
1666 Tab currentTab = mTabControl.getCurrentTab();
1667 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001668 return false;
1669 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001670 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001671 break;
1672
1673 case R.id.dump_nav_menu_id:
1674 getCurrentTopWebView().debugDump();
1675 break;
1676
1677 case R.id.dump_counters_menu_id:
1678 getCurrentTopWebView().dumpV8Counters();
1679 break;
1680
1681 case R.id.zoom_in_menu_id:
1682 getCurrentTopWebView().zoomIn();
1683 break;
1684
1685 case R.id.zoom_out_menu_id:
1686 getCurrentTopWebView().zoomOut();
1687 break;
1688
1689 case R.id.view_downloads_menu_id:
1690 viewDownloads();
1691 break;
1692
1693 case R.id.window_one_menu_id:
1694 case R.id.window_two_menu_id:
1695 case R.id.window_three_menu_id:
1696 case R.id.window_four_menu_id:
1697 case R.id.window_five_menu_id:
1698 case R.id.window_six_menu_id:
1699 case R.id.window_seven_menu_id:
1700 case R.id.window_eight_menu_id:
1701 {
1702 int menuid = item.getItemId();
1703 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1704 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1705 Tab desiredTab = mTabControl.getTab(id);
1706 if (desiredTab != null &&
1707 desiredTab != mTabControl.getCurrentTab()) {
1708 switchToTab(id);
1709 }
1710 break;
1711 }
1712 }
1713 }
1714 break;
1715
1716 default:
1717 return false;
1718 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001719 return true;
1720 }
1721
1722 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001723 // Let the History and Bookmark fragments handle menus they created.
1724 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1725 return false;
1726 }
1727
Michael Kolb8233fac2010-10-26 16:08:53 -07001728 int id = item.getItemId();
1729 boolean result = true;
1730 switch (id) {
1731 // For the context menu from the title bar
1732 case R.id.title_bar_copy_page_url:
1733 Tab currentTab = mTabControl.getCurrentTab();
1734 if (null == currentTab) {
1735 result = false;
1736 break;
1737 }
1738 WebView mainView = currentTab.getWebView();
1739 if (null == mainView) {
1740 result = false;
1741 break;
1742 }
1743 copy(mainView.getUrl());
1744 break;
1745 // -- Browser context menu
1746 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001747 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001748 case R.id.copy_link_context_menu_id:
1749 final WebView webView = getCurrentTopWebView();
1750 if (null == webView) {
1751 result = false;
1752 break;
1753 }
1754 final HashMap<String, WebView> hrefMap =
1755 new HashMap<String, WebView>();
1756 hrefMap.put("webview", webView);
1757 final Message msg = mHandler.obtainMessage(
1758 FOCUS_NODE_HREF, id, 0, hrefMap);
1759 webView.requestFocusNodeHref(msg);
1760 break;
1761
1762 default:
1763 // For other context menus
1764 result = onOptionsItemSelected(item);
1765 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001766 return result;
1767 }
1768
1769 /**
1770 * support programmatically opening the context menu
1771 */
1772 public void openContextMenu(View view) {
1773 mActivity.openContextMenu(view);
1774 }
1775
1776 /**
1777 * programmatically open the options menu
1778 */
1779 public void openOptionsMenu() {
1780 mActivity.openOptionsMenu();
1781 }
1782
1783 public boolean onMenuOpened(int featureId, Menu menu) {
1784 if (mOptionsMenuOpen) {
1785 if (mConfigChanged) {
1786 // We do not need to make any changes to the state of the
1787 // title bar, since the only thing that happened was a
1788 // change in orientation
1789 mConfigChanged = false;
1790 } else {
1791 if (!mExtendedMenuOpen) {
1792 mExtendedMenuOpen = true;
1793 mUi.onExtendedMenuOpened();
1794 } else {
1795 // Switching the menu back to icon view, so show the
1796 // title bar once again.
1797 mExtendedMenuOpen = false;
1798 mUi.onExtendedMenuClosed(mInLoad);
Michael Kolb8233fac2010-10-26 16:08:53 -07001799 }
1800 }
1801 } else {
1802 // The options menu is closed, so open it, and show the title
1803 mOptionsMenuOpen = true;
1804 mConfigChanged = false;
1805 mExtendedMenuOpen = false;
1806 mUi.onOptionsMenuOpened();
1807 }
1808 return true;
1809 }
1810
1811 public void onOptionsMenuClosed(Menu menu) {
1812 mOptionsMenuOpen = false;
1813 mUi.onOptionsMenuClosed(mInLoad);
1814 }
1815
1816 public void onContextMenuClosed(Menu menu) {
1817 mUi.onContextMenuClosed(menu, mInLoad);
1818 }
1819
1820 // Helper method for getting the top window.
1821 @Override
1822 public WebView getCurrentTopWebView() {
1823 return mTabControl.getCurrentTopWebView();
1824 }
1825
1826 @Override
1827 public WebView getCurrentWebView() {
1828 return mTabControl.getCurrentWebView();
1829 }
1830
1831 /*
1832 * This method is called as a result of the user selecting the options
1833 * menu to see the download window. It shows the download window on top of
1834 * the current window.
1835 */
1836 void viewDownloads() {
1837 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1838 mActivity.startActivity(intent);
1839 }
1840
1841 // action mode
1842
1843 void onActionModeStarted(ActionMode mode) {
1844 mUi.onActionModeStarted(mode);
1845 mActionMode = mode;
1846 }
1847
1848 /*
1849 * True if a custom ActionMode (i.e. find or select) is in use.
1850 */
1851 @Override
1852 public boolean isInCustomActionMode() {
1853 return mActionMode != null;
1854 }
1855
1856 /*
1857 * End the current ActionMode.
1858 */
1859 @Override
1860 public void endActionMode() {
1861 if (mActionMode != null) {
1862 mActionMode.finish();
1863 }
1864 }
1865
1866 /*
1867 * Called by find and select when they are finished. Replace title bars
1868 * as necessary.
1869 */
1870 public void onActionModeFinished(ActionMode mode) {
1871 if (!isInCustomActionMode()) return;
1872 mUi.onActionModeFinished(mInLoad);
1873 mActionMode = null;
1874 }
1875
1876 boolean isInLoad() {
1877 return mInLoad;
1878 }
1879
1880 // bookmark handling
1881
1882 /**
1883 * add the current page as a bookmark to the given folder id
1884 * @param folderId use -1 for the default folder
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001885 * @param canBeAnEdit If true, check to see whether the site is already
1886 * bookmarked, and if it is, edit that bookmark. If false, and
1887 * the site is already bookmarked, do not attempt to edit the
1888 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001889 */
1890 @Override
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001891 public void bookmarkCurrentPage(long folderId, boolean canBeAnEdit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001892 Intent i = new Intent(mActivity,
1893 AddBookmarkPage.class);
1894 WebView w = getCurrentTopWebView();
1895 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1896 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1897 String touchIconUrl = w.getTouchIconUrl();
1898 if (touchIconUrl != null) {
1899 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1900 WebSettings settings = w.getSettings();
1901 if (settings != null) {
1902 i.putExtra(AddBookmarkPage.USER_AGENT,
1903 settings.getUserAgentString());
1904 }
1905 }
1906 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1907 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1908 getDesiredThumbnailHeight(mActivity)));
1909 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1910 i.putExtra(BrowserContract.Bookmarks.PARENT,
1911 folderId);
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001912 if (canBeAnEdit) {
1913 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1914 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001915 // Put the dialog at the upper right of the screen, covering the
1916 // star on the title bar.
1917 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1918 mActivity.startActivity(i);
1919 }
1920
1921 // file chooser
1922 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1923 mUploadHandler = new UploadHandler(this);
1924 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1925 }
1926
1927 // thumbnails
1928
1929 /**
1930 * Return the desired width for thumbnail screenshots, which are stored in
1931 * the database, and used on the bookmarks screen.
1932 * @param context Context for finding out the density of the screen.
1933 * @return desired width for thumbnail screenshot.
1934 */
1935 static int getDesiredThumbnailWidth(Context context) {
1936 return context.getResources().getDimensionPixelOffset(
1937 R.dimen.bookmarkThumbnailWidth);
1938 }
1939
1940 /**
1941 * Return the desired height 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 height for thumbnail screenshot.
1945 */
1946 static int getDesiredThumbnailHeight(Context context) {
1947 return context.getResources().getDimensionPixelOffset(
1948 R.dimen.bookmarkThumbnailHeight);
1949 }
1950
Michael Kolb1acef692011-03-08 14:12:06 -08001951 static Bitmap createScreenshot(Tab tab, int width, int height) {
1952 if ((tab != null) && (tab.getWebView() != null)) {
1953 return createScreenshot(tab.getWebView(), width, height);
1954 }
1955 return null;
1956 }
1957
Michael Kolb8233fac2010-10-26 16:08:53 -07001958 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001959 // We render to a bitmap 2x the desired size so that we can then
1960 // re-scale it with filtering since canvas.scale doesn't filter
1961 // This helps reduce aliasing at the cost of being slightly blurry
1962 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001963 Picture thumbnail = view.capturePicture();
1964 if (thumbnail == null) {
1965 return null;
1966 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001967 width *= filter_scale;
1968 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001969 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1970 Canvas canvas = new Canvas(bm);
1971 // May need to tweak these values to determine what is the
1972 // best scale factor
1973 int thumbnailWidth = thumbnail.getWidth();
1974 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001975 float scaleFactor = 1.0f;
Michael Kolbeb95db42011-03-03 10:38:40 -08001976 if (thumbnailWidth > 0 && thumbnailHeight > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001977 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001978 } else {
1979 return null;
1980 }
John Reckfe49ab42010-11-16 17:09:37 -08001981
Michael Kolbeb95db42011-03-03 10:38:40 -08001982 float scaleFactorY = (float) height / (float)thumbnailHeight;
1983 if (scaleFactorY > scaleFactor) {
1984 // The picture is narrower than the requested AR
1985 // Center the thumnail and crop the sides
1986 scaleFactor = scaleFactorY;
John Reckfe49ab42010-11-16 17:09:37 -08001987 float wx = (thumbnailWidth * scaleFactor) - width;
1988 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001989 }
1990
John Reckfe49ab42010-11-16 17:09:37 -08001991 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001992
1993 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001994 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
1995 height / filter_scale, true);
1996 bm.recycle();
1997 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001998 }
1999
John Reck34ef2672011-02-10 11:30:55 -08002000 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002001 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07002002 // FIXME: Would like to make sure there is actually something to
2003 // draw, but the API for that (WebViewCore.pictureReady()) is not
2004 // currently accessible here.
2005
John Reck34ef2672011-02-10 11:30:55 -08002006 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08002007 if (view == null) {
2008 // Tab was destroyed
2009 return;
2010 }
John Reck34ef2672011-02-10 11:30:55 -08002011 final String url = tab.getUrl();
2012 final String originalUrl = view.getOriginalUrl();
2013
2014 if (TextUtils.isEmpty(url)) {
2015 return;
2016 }
2017
2018 // Only update thumbnails for web urls (http(s)://), not for
2019 // about:, javascript:, data:, etc...
2020 // Unless it is a bookmarked site, then always update
2021 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2022 return;
2023 }
2024
Michael Kolb8233fac2010-10-26 16:08:53 -07002025 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
2026 getDesiredThumbnailHeight(mActivity));
2027 if (bm == null) {
2028 return;
2029 }
2030
2031 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002032 new AsyncTask<Void, Void, Void>() {
2033 @Override
2034 protected Void doInBackground(Void... unused) {
2035 Cursor cursor = null;
2036 try {
2037 // TODO: Clean this up
2038 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2039 if (cursor != null && cursor.moveToFirst()) {
2040 final ByteArrayOutputStream os =
2041 new ByteArrayOutputStream();
2042 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002043
John Reck34ef2672011-02-10 11:30:55 -08002044 ContentValues values = new ContentValues();
2045 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002046
John Reck34ef2672011-02-10 11:30:55 -08002047 do {
John Reck617fd832011-02-16 14:35:59 -08002048 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002049 cr.update(Images.CONTENT_URI, values, null, null);
2050 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002051 }
John Reck34ef2672011-02-10 11:30:55 -08002052 } catch (IllegalStateException e) {
2053 // Ignore
2054 } finally {
2055 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002056 }
John Reck34ef2672011-02-10 11:30:55 -08002057 return null;
2058 }
2059 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002060 }
2061
2062 private class Copy implements OnMenuItemClickListener {
2063 private CharSequence mText;
2064
2065 public boolean onMenuItemClick(MenuItem item) {
2066 copy(mText);
2067 return true;
2068 }
2069
2070 public Copy(CharSequence toCopy) {
2071 mText = toCopy;
2072 }
2073 }
2074
Leon Scroggins63c02662010-11-18 15:16:27 -05002075 private static class Download implements OnMenuItemClickListener {
2076 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002077 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002078 private boolean mPrivateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002079
2080 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002081 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002082 null, null, mPrivateBrowsing);
Michael Kolb8233fac2010-10-26 16:08:53 -07002083 return true;
2084 }
2085
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002086 public Download(Activity activity, String toDownload, boolean privateBrowsing) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002087 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002088 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002089 mPrivateBrowsing = privateBrowsing;
Michael Kolb8233fac2010-10-26 16:08:53 -07002090 }
2091 }
2092
Cary Clark8974d282010-11-22 10:46:05 -05002093 private static class SelectText implements OnMenuItemClickListener {
2094 private WebView mWebView;
2095
2096 public boolean onMenuItemClick(MenuItem item) {
2097 if (mWebView != null) {
2098 return mWebView.selectText();
2099 }
2100 return false;
2101 }
2102
2103 public SelectText(WebView webView) {
2104 mWebView = webView;
2105 }
2106
2107 }
2108
Michael Kolb8233fac2010-10-26 16:08:53 -07002109 /********************** TODO: UI stuff *****************************/
2110
2111 // these methods have been copied, they still need to be cleaned up
2112
2113 /****************** tabs ***************************************************/
2114
2115 // basic tab interactions:
2116
2117 // it is assumed that tabcontrol already knows about the tab
2118 protected void addTab(Tab tab) {
2119 mUi.addTab(tab);
2120 }
2121
2122 protected void removeTab(Tab tab) {
2123 mUi.removeTab(tab);
2124 mTabControl.removeTab(tab);
2125 }
2126
Michael Kolbf2055602011-04-09 17:20:03 -07002127 @Override
2128 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002129 // monkey protection against delayed start
2130 if (tab != null) {
2131 mTabControl.setCurrentTab(tab);
2132 // the tab is guaranteed to have a webview after setCurrentTab
2133 mUi.setActiveTab(tab);
2134 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002135 }
2136
2137 protected void closeEmptyChildTab() {
2138 Tab current = mTabControl.getCurrentTab();
2139 if (current != null
2140 && current.getWebView().copyBackForwardList().getSize() == 0) {
2141 Tab parent = current.getParentTab();
2142 if (parent != null) {
2143 switchToTab(mTabControl.getTabIndex(parent));
2144 closeTab(current);
2145 }
2146 }
2147 }
2148
2149 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002150 // Dismiss the subwindow if applicable.
2151 dismissSubWindow(appTab);
2152 // Since we might kill the WebView, remove it from the
2153 // content view first.
2154 mUi.detachTab(appTab);
2155 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002156 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002157 // TODO: analyze why the remove and add are necessary
2158 mUi.attachTab(appTab);
2159 if (mTabControl.getCurrentTab() != appTab) {
2160 switchToTab(mTabControl.getTabIndex(appTab));
John Reck30c714c2010-12-16 17:30:34 -08002161 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002162 } else {
2163 // If the tab was the current tab, we have to attach
2164 // it to the view system again.
2165 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002166 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002167 }
2168 }
2169
2170 // Remove the sub window if it exists. Also called by TabControl when the
2171 // user clicks the 'X' to dismiss a sub window.
2172 public void dismissSubWindow(Tab tab) {
2173 removeSubWindow(tab);
2174 // dismiss the subwindow. This will destroy the WebView.
2175 tab.dismissSubWindow();
2176 getCurrentTopWebView().requestFocus();
2177 }
2178
2179 @Override
2180 public void removeSubWindow(Tab t) {
2181 if (t.getSubWebView() != null) {
2182 mUi.removeSubWindow(t.getSubViewContainer());
2183 }
2184 }
2185
2186 @Override
2187 public void attachSubWindow(Tab tab) {
2188 if (tab.getSubWebView() != null) {
2189 mUi.attachSubWindow(tab.getSubViewContainer());
2190 getCurrentTopWebView().requestFocus();
2191 }
2192 }
2193
Michael Kolb843510f2010-12-09 10:51:49 -08002194 @Override
2195 public Tab openTabToHomePage() {
2196 // check for max tabs
2197 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002198 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2199 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002200 } else {
2201 mUi.showMaxTabsWarning();
2202 return null;
2203 }
2204 }
2205
Michael Kolb18eb3772010-12-10 14:29:51 -08002206 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2207 if (mSettings.openInBackground() && !forceForeground) {
2208 Tab tab = mTabControl.createNewTab(false, null, null,
2209 (parent != null) && parent.isPrivateBrowsingEnabled());
2210 if (tab != null) {
2211 addTab(tab);
2212 WebView view = tab.getWebView();
2213 loadUrl(view, url);
2214 }
2215 return tab;
2216 } else {
2217 return openTabAndShow(parent, new UrlData(url), false, null);
2218 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002219 }
2220
Michael Kolb18eb3772010-12-10 14:29:51 -08002221
Michael Kolb8233fac2010-10-26 16:08:53 -07002222 // This method does a ton of stuff. It will attempt to create a new tab
2223 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2224 // url isn't null, it will load the given url.
Patrick Scottcd135082011-01-31 18:21:58 -05002225 public Tab openTabAndShow(Tab parent, final UrlData urlData,
2226 boolean closeOnExit, String appId) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002227 final Tab currentTab = mTabControl.getCurrentTab();
2228 if (mTabControl.canCreateNewTab()) {
2229 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Michael Kolb18eb3772010-12-10 14:29:51 -08002230 urlData.mUrl,
2231 (parent != null) && parent.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -07002232 WebView webview = tab.getWebView();
2233 // We must set the new tab as the current tab to reflect the old
2234 // animation behavior.
2235 addTab(tab);
2236 setActiveTab(tab);
Patrick Scottd43e75a2011-03-14 14:47:23 -04002237 if (!urlData.isEmpty()) {
2238 loadUrlDataIn(tab, urlData);
2239 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002240 return tab;
2241 } else {
2242 // Get rid of the subwindow if it exists
2243 dismissSubWindow(currentTab);
2244 if (!urlData.isEmpty()) {
2245 // Load the given url.
2246 loadUrlDataIn(currentTab, urlData);
2247 }
2248 return currentTab;
2249 }
2250 }
2251
Michael Kolb8233fac2010-10-26 16:08:53 -07002252 @Override
2253 public Tab openIncognitoTab() {
2254 if (mTabControl.canCreateNewTab()) {
2255 Tab currentTab = mTabControl.getCurrentTab();
Michael Kolb8e7178d2011-01-26 19:13:36 -08002256 Tab tab = mTabControl.createNewTab(false, null,
John Reck4bfc0db2011-01-27 17:47:12 -08002257 null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07002258 addTab(tab);
2259 setActiveTab(tab);
John Reck4bfc0db2011-01-27 17:47:12 -08002260 loadUrlDataIn(tab, new UrlData("browser:incognito"));
Michael Kolb8233fac2010-10-26 16:08:53 -07002261 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002262 } else {
2263 mUi.showMaxTabsWarning();
2264 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002265 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002266 }
2267
2268 /**
2269 * @param index Index of the tab to change to, as defined by
2270 * mTabControl.getTabIndex(Tab t).
2271 * @return boolean True if we successfully switched to a different tab. If
2272 * the indexth tab is null, or if that tab is the same as
2273 * the current one, return false.
2274 */
2275 @Override
2276 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002277 // hide combo view if open
2278 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002279 Tab tab = mTabControl.getTab(index);
2280 Tab currentTab = mTabControl.getCurrentTab();
2281 if (tab == null || tab == currentTab) {
2282 return false;
2283 }
2284 setActiveTab(tab);
2285 return true;
2286 }
2287
2288 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002289 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002290 // hide combo view if open
2291 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002292 final Tab current = mTabControl.getCurrentTab();
2293 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002294 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002295 return;
2296 }
2297 final Tab parent = current.getParentTab();
2298 int indexToShow = -1;
2299 if (parent != null) {
2300 indexToShow = mTabControl.getTabIndex(parent);
2301 } else {
2302 final int currentIndex = mTabControl.getCurrentIndex();
2303 // Try to move to the tab to the right
2304 indexToShow = currentIndex + 1;
2305 if (indexToShow > mTabControl.getTabCount() - 1) {
2306 // Try to move to the tab to the left
2307 indexToShow = currentIndex - 1;
2308 }
2309 }
2310 if (switchToTab(indexToShow)) {
2311 // Close window
2312 closeTab(current);
2313 }
2314 }
2315
2316 /**
2317 * Close the tab, remove its associated title bar, and adjust mTabControl's
2318 * current tab to a valid value.
2319 */
2320 @Override
2321 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002322 // hide combo view if open
2323 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002324 int currentIndex = mTabControl.getCurrentIndex();
2325 int removeIndex = mTabControl.getTabIndex(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002326 Tab newtab = mTabControl.getTab(currentIndex);
2327 setActiveTab(newtab);
Michael Kolb2d59c322011-01-25 13:18:55 -08002328 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002329 }
2330
2331 /**************** TODO: Url loading clean up *******************************/
2332
2333 // Called when loading from context menu or LOAD_URL message
2334 protected void loadUrlFromContext(WebView view, String url) {
2335 // In case the user enters nothing.
2336 if (url != null && url.length() != 0 && view != null) {
2337 url = UrlUtils.smartUrlFilter(url);
2338 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2339 loadUrl(view, url);
2340 }
2341 }
2342 }
2343
2344 /**
2345 * Load the URL into the given WebView and update the title bar
2346 * to reflect the new load. Call this instead of WebView.loadUrl
2347 * directly.
2348 * @param view The WebView used to load url.
2349 * @param url The URL to load.
2350 */
2351 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002352 view.loadUrl(url);
2353 }
2354
2355 /**
2356 * Load UrlData into a Tab and update the title bar to reflect the new
2357 * load. Call this instead of UrlData.loadIn directly.
2358 * @param t The Tab used to load.
2359 * @param data The UrlData being loaded.
2360 */
2361 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002362 data.loadIn(t);
2363 }
2364
John Reck30c714c2010-12-16 17:30:34 -08002365 @Override
2366 public void onUserCanceledSsl(Tab tab) {
2367 WebView web = tab.getWebView();
2368 // TODO: Figure out the "right" behavior
2369 if (web.canGoBack()) {
2370 web.goBack();
2371 } else {
2372 web.loadUrl(mSettings.getHomePage());
2373 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002374 }
2375
2376 void goBackOnePageOrQuit() {
2377 Tab current = mTabControl.getCurrentTab();
2378 if (current == null) {
2379 /*
2380 * Instead of finishing the activity, simply push this to the back
2381 * of the stack and let ActivityManager to choose the foreground
2382 * activity. As BrowserActivity is singleTask, it will be always the
2383 * root of the task. So we can use either true or false for
2384 * moveTaskToBack().
2385 */
2386 mActivity.moveTaskToBack(true);
2387 return;
2388 }
2389 WebView w = current.getWebView();
2390 if (w.canGoBack()) {
2391 w.goBack();
2392 } else {
2393 // Check to see if we are closing a window that was created by
2394 // another window. If so, we switch back to that window.
2395 Tab parent = current.getParentTab();
2396 if (parent != null) {
2397 switchToTab(mTabControl.getTabIndex(parent));
2398 // Now we close the other tab
2399 closeTab(current);
2400 } else {
2401 if (current.closeOnExit()) {
Patrick Scottfc1518a2011-02-28 13:57:03 -05002402 // This will finish the activity if there is only one tab
2403 // open or it will switch to the next available tab if
2404 // available.
Michael Kolb96683f72011-02-15 14:24:35 -08002405 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002406 }
2407 /*
2408 * Instead of finishing the activity, simply push this to the back
2409 * of the stack and let ActivityManager to choose the foreground
2410 * activity. As BrowserActivity is singleTask, it will be always the
2411 * root of the task. So we can use either true or false for
2412 * moveTaskToBack().
2413 */
2414 mActivity.moveTaskToBack(true);
2415 }
2416 }
2417 }
2418
2419 /**
2420 * Feed the previously stored results strings to the BrowserProvider so that
2421 * the SearchDialog will show them instead of the standard searches.
2422 * @param result String to show on the editable line of the SearchDialog.
2423 */
2424 @Override
2425 public void showVoiceSearchResults(String result) {
2426 ContentProviderClient client = mActivity.getContentResolver()
2427 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2428 ContentProvider prov = client.getLocalContentProvider();
2429 BrowserProvider bp = (BrowserProvider) prov;
2430 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2431 client.release();
2432
2433 Bundle bundle = createGoogleSearchSourceBundle(
2434 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2435 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2436 startSearch(result, false, bundle, false);
2437 }
2438
2439 private void startSearch(String initialQuery, boolean selectInitialQuery,
2440 Bundle appSearchData, boolean globalSearch) {
2441 if (appSearchData == null) {
2442 appSearchData = createGoogleSearchSourceBundle(
2443 GOOGLE_SEARCH_SOURCE_TYPE);
2444 }
2445
2446 SearchEngine searchEngine = mSettings.getSearchEngine();
2447 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2448 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2449 }
2450 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2451 globalSearch);
2452 }
2453
2454 private Bundle createGoogleSearchSourceBundle(String source) {
2455 Bundle bundle = new Bundle();
2456 bundle.putString(Search.SOURCE, source);
2457 return bundle;
2458 }
2459
2460 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07002461 * helper method for key handler
2462 * returns the current tab if it can't advance
2463 */
2464 private int getNextTabIndex() {
2465 return Math.min(mTabControl.getTabCount() - 1,
2466 mTabControl.getCurrentIndex() + 1);
2467 }
2468
2469 /**
2470 * helper method for key handler
2471 * returns the current tab if it can't advance
2472 */
2473 private int getPrevTabIndex() {
2474 return Math.max(0, mTabControl.getCurrentIndex() - 1);
2475 }
2476
2477 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002478 * handle key events in browser
2479 *
2480 * @param keyCode
2481 * @param event
2482 * @return true if handled, false to pass to super
2483 */
2484 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002485 boolean noModifiers = event.hasNoModifiers();
2486
Michael Kolb8233fac2010-10-26 16:08:53 -07002487 // Even if MENU is already held down, we need to call to super to open
2488 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002489 if (!noModifiers
2490 && ((KeyEvent.KEYCODE_MENU == keyCode)
2491 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2492 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002493 mMenuIsDown = true;
2494 return false;
2495 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002496
Cary Clark8ff8c662010-12-29 15:03:05 -05002497 WebView webView = getCurrentTopWebView();
2498 if (webView == null) return false;
2499
Cary Clark160bbb92011-01-10 11:17:07 -05002500 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2501 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002502
Michael Kolb8233fac2010-10-26 16:08:53 -07002503 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07002504 case KeyEvent.KEYCODE_TAB:
2505 if (event.isCtrlPressed()) {
2506 if (event.isShiftPressed()) {
2507 // prev tab
2508 switchToTab(getPrevTabIndex());
2509 } else {
2510 // next tab
2511 switchToTab(getNextTabIndex());
2512 }
2513 return true;
2514 }
2515 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002516 case KeyEvent.KEYCODE_SPACE:
2517 // WebView/WebTextView handle the keys in the KeyDown. As
2518 // the Activity's shortcut keys are only handled when WebView
2519 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002520 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002521 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002522 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002523 pageDown();
2524 }
2525 return true;
2526 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002527 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002528 event.startTracking();
2529 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002530 case KeyEvent.KEYCODE_DPAD_LEFT:
2531 if (ctrl) {
2532 webView.goBack();
2533 return true;
2534 }
2535 break;
2536 case KeyEvent.KEYCODE_DPAD_RIGHT:
2537 if (ctrl) {
2538 webView.goForward();
2539 return true;
2540 }
2541 break;
2542 case KeyEvent.KEYCODE_A:
2543 if (ctrl) {
2544 webView.selectAll();
2545 return true;
2546 }
2547 break;
Michael Kolba4183062011-01-16 10:43:21 -08002548// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002549 case KeyEvent.KEYCODE_C:
2550 if (ctrl) {
2551 webView.copySelection();
2552 return true;
2553 }
2554 break;
Michael Kolba4183062011-01-16 10:43:21 -08002555// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002556// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002557// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002558// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002559// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002560// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002561// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002562// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002563// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002564// case KeyEvent.KEYCODE_M: // unused
2565// case KeyEvent.KEYCODE_N: // in Chrome: new window
2566// case KeyEvent.KEYCODE_O: // in Chrome: open file
2567// case KeyEvent.KEYCODE_P: // in Chrome: print page
2568// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002569// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002570// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2571 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002572 // we can't use the ctrl/shift flags, they check for
2573 // exclusive use of a modifier
2574 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002575 if (event.isShiftPressed()) {
2576 openIncognitoTab();
2577 } else {
2578 openTabToHomePage();
2579 }
2580 return true;
2581 }
2582 break;
2583// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2584// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb1a2eba42011-03-16 16:42:49 -07002585 case KeyEvent.KEYCODE_W: // in Chrome: close tab
2586 if (ctrl) {
2587 closeCurrentTab();
2588 return true;
2589 }
2590 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002591// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2592// case KeyEvent.KEYCODE_Y: // unused
2593// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002594 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002595 // it is a regular key and webview is not null
2596 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002597 }
2598
John Recke6bf4ab2011-02-24 15:48:05 -08002599 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2600 switch(keyCode) {
2601 case KeyEvent.KEYCODE_BACK:
2602 if (mUi.showsWeb()) {
2603 bookmarksOrHistoryPicker(true);
2604 return true;
2605 }
2606 break;
2607 }
2608 return false;
2609 }
2610
Michael Kolb8233fac2010-10-26 16:08:53 -07002611 boolean onKeyUp(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002612 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002613 switch(keyCode) {
2614 case KeyEvent.KEYCODE_MENU:
2615 mMenuIsDown = false;
2616 break;
2617 case KeyEvent.KEYCODE_BACK:
2618 if (event.isTracking() && !event.isCanceled()) {
2619 onBackKey();
2620 return true;
2621 }
2622 break;
2623 }
2624 return false;
2625 }
2626
2627 public boolean isMenuDown() {
2628 return mMenuIsDown;
2629 }
2630
Ben Murdoch8029a772010-11-16 11:58:21 +00002631 public void setupAutoFill(Message message) {
2632 // Open the settings activity at the AutoFill profile fragment so that
2633 // the user can create a new profile. When they return, we will dispatch
2634 // the message so that we can autofill the form using their new profile.
2635 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2636 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2637 AutoFillSettingsFragment.class.getName());
2638 mAutoFillSetupMessage = message;
2639 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2640 }
John Reckb3417f02011-01-14 11:01:05 -08002641
2642 @Override
2643 public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
2644 mOptionsMenuHandler = handler;
2645 }
2646
2647 @Override
2648 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
2649 if (mOptionsMenuHandler == handler) {
2650 mOptionsMenuHandler = null;
2651 }
2652 }
2653
Narayan Kamath5119edd2011-02-23 15:49:17 +00002654 @Override
2655 public void registerDropdownChangeListener(DropdownChangeListener d) {
2656 mUi.registerDropdownChangeListener(d);
2657 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002658}