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