blob: 5b655c4a4ebc08a9167be26d3e8a9d91256ec315 [file] [log] [blame]
Michael Kolb8233fac2010-10-26 16:08:53 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
19import com.android.browser.IntentHandler.UrlData;
Narayan Kamath5119edd2011-02-23 15:49:17 +000020import com.android.browser.UI.DropdownChangeListener;
Michael Kolb8233fac2010-10-26 16:08:53 -070021import com.android.browser.search.SearchEngine;
22import com.android.common.Search;
23
24import android.app.Activity;
25import android.app.DownloadManager;
26import android.app.SearchManager;
27import android.content.ClipboardManager;
28import android.content.ContentProvider;
29import android.content.ContentProviderClient;
30import android.content.ContentResolver;
31import android.content.ContentValues;
32import android.content.Context;
33import android.content.Intent;
34import android.content.pm.PackageManager;
35import android.content.pm.ResolveInfo;
36import android.content.res.Configuration;
Leon Scroggins1961ed22010-12-07 15:22:21 -050037import android.database.ContentObserver;
Michael Kolb8233fac2010-10-26 16:08:53 -070038import android.database.Cursor;
39import android.database.sqlite.SQLiteDatabase;
Michael Kolb8233fac2010-10-26 16:08:53 -070040import android.graphics.Bitmap;
41import android.graphics.Canvas;
42import android.graphics.Picture;
43import android.net.Uri;
44import android.net.http.SslError;
45import android.os.AsyncTask;
46import android.os.Bundle;
Leon Scrogginsac993842011-02-02 12:54:07 -050047import android.os.Environment;
Michael Kolb8233fac2010-10-26 16:08:53 -070048import android.os.Handler;
49import android.os.Message;
50import android.os.PowerManager;
51import android.os.PowerManager.WakeLock;
Ben Murdoch8029a772010-11-16 11:58:21 +000052import android.preference.PreferenceActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -070053import android.provider.Browser;
54import android.provider.BrowserContract;
Michael Kolb8233fac2010-10-26 16:08:53 -070055import android.provider.BrowserContract.Images;
56import android.provider.ContactsContract;
57import android.provider.ContactsContract.Intents.Insert;
Michael Kolbcfa3af52010-12-14 10:36:11 -080058import android.speech.RecognizerIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070059import android.speech.RecognizerResultsIntent;
60import android.text.TextUtils;
61import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080062import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070063import android.view.ActionMode;
64import android.view.ContextMenu;
65import android.view.ContextMenu.ContextMenuInfo;
66import android.view.Gravity;
67import android.view.KeyEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070068import android.view.Menu;
69import android.view.MenuInflater;
70import android.view.MenuItem;
71import android.view.MenuItem.OnMenuItemClickListener;
72import android.view.View;
73import android.webkit.CookieManager;
74import android.webkit.CookieSyncManager;
75import android.webkit.HttpAuthHandler;
76import android.webkit.SslErrorHandler;
77import android.webkit.ValueCallback;
78import android.webkit.WebChromeClient;
79import android.webkit.WebIconDatabase;
80import android.webkit.WebSettings;
81import android.webkit.WebView;
Leon Scrogginsac993842011-02-02 12:54:07 -050082import android.widget.Toast;
Michael Kolb8233fac2010-10-26 16:08:53 -070083
84import java.io.ByteArrayOutputStream;
85import java.io.File;
86import java.net.URLEncoder;
87import java.util.Calendar;
88import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -080089import java.util.List;
Michael Kolb8233fac2010-10-26 16:08:53 -070090
91/**
92 * Controller for browser
93 */
94public class Controller
95 implements WebViewController, UiController {
96
97 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -080098 private static final String SEND_APP_ID_EXTRA =
99 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
100
Michael Kolb8233fac2010-10-26 16:08:53 -0700101
102 // public message ids
103 public final static int LOAD_URL = 1001;
104 public final static int STOP_LOAD = 1002;
105
106 // Message Ids
107 private static final int FOCUS_NODE_HREF = 102;
108 private static final int RELEASE_WAKELOCK = 107;
109
110 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
111
112 private static final int OPEN_BOOKMARKS = 201;
113
114 private static final int EMPTY_MENU = -1;
115
Michael Kolb8233fac2010-10-26 16:08:53 -0700116 // activity requestCode
117 final static int PREFERENCES_PAGE = 3;
118 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000119 final static int AUTOFILL_SETUP = 5;
120
Michael Kolb8233fac2010-10-26 16:08:53 -0700121 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
122
123 // As the ids are dynamically created, we can't guarantee that they will
124 // be in sequence, so this static array maps ids to a window number.
125 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
126 { R.id.window_one_menu_id, R.id.window_two_menu_id,
127 R.id.window_three_menu_id, R.id.window_four_menu_id,
128 R.id.window_five_menu_id, R.id.window_six_menu_id,
129 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
130
131 // "source" parameter for Google search through search key
132 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
133 // "source" parameter for Google search through simplily type
134 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
135
136 private Activity mActivity;
137 private UI mUi;
138 private TabControl mTabControl;
139 private BrowserSettings mSettings;
140 private WebViewFactory mFactory;
John Reckb3417f02011-01-14 11:01:05 -0800141 private OptionsMenuHandler mOptionsMenuHandler = null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700142
143 private WakeLock mWakeLock;
144
145 private UrlHandler mUrlHandler;
146 private UploadHandler mUploadHandler;
147 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700148 private PageDialogsHandler mPageDialogsHandler;
149 private NetworkStateHandler mNetworkHandler;
150
Ben Murdoch8029a772010-11-16 11:58:21 +0000151 private Message mAutoFillSetupMessage;
152
Michael Kolb8233fac2010-10-26 16:08:53 -0700153 private boolean mShouldShowErrorConsole;
154
155 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
156
157 // FIXME, temp address onPrepareMenu performance problem.
158 // When we move everything out of view, we should rewrite this.
159 private int mCurrentMenuState = 0;
160 private int mMenuState = R.id.MAIN_MENU;
161 private int mOldMenuState = EMPTY_MENU;
162 private Menu mCachedMenu;
163
164 // Used to prevent chording to result in firing two shortcuts immediately
165 // one after another. Fixes bug 1211714.
166 boolean mCanChord;
167 private boolean mMenuIsDown;
168
169 // For select and find, we keep track of the ActionMode so that
170 // finish() can be called as desired.
171 private ActionMode mActionMode;
172
173 /**
174 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
175 * of whether the configuration has changed. The first onMenuOpened call
176 * after a configuration change is simply a reopening of the same menu
177 * (i.e. mIconView did not change).
178 */
179 private boolean mConfigChanged;
180
181 /**
182 * Keeps track of whether the options menu is open. This is important in
183 * determining whether to show or hide the title bar overlay
184 */
185 private boolean mOptionsMenuOpen;
186
187 /**
188 * Whether or not the options menu is in its bigger, popup menu form. When
189 * true, we want the title bar overlay to be gone. When false, we do not.
190 * Only meaningful if mOptionsMenuOpen is true.
191 */
192 private boolean mExtendedMenuOpen;
193
194 private boolean mInLoad;
195
196 private boolean mActivityPaused = true;
197 private boolean mLoadStopped;
198
199 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500200 // Checks to see when the bookmarks database has changed, and updates the
201 // Tabs' notion of whether they represent bookmarked sites.
202 private ContentObserver mBookmarksObserver;
John Reck0ebd3ac2010-12-09 11:14:04 -0800203 private DataController mDataController;
Michael Kolb8233fac2010-10-26 16:08:53 -0700204
205 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
206 @Override
207 public Void doInBackground(File... files) {
208 if (files != null) {
209 for (File f : files) {
210 if (!f.delete()) {
211 Log.e(LOGTAG, f.getPath() + " was not deleted");
212 }
213 }
214 }
215 return null;
216 }
217 }
218
219 public Controller(Activity browser) {
220 mActivity = browser;
221 mSettings = BrowserSettings.getInstance();
John Reck0ebd3ac2010-12-09 11:14:04 -0800222 mDataController = DataController.getInstance(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700223 mTabControl = new TabControl(this);
224 mSettings.setController(this);
225
226 mUrlHandler = new UrlHandler(this);
227 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700228 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
229
230 PowerManager pm = (PowerManager) mActivity
231 .getSystemService(Context.POWER_SERVICE);
232 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
233
234 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500235 mBookmarksObserver = new ContentObserver(mHandler) {
236 @Override
237 public void onChange(boolean selfChange) {
238 int size = mTabControl.getTabCount();
239 for (int i = 0; i < size; i++) {
240 mTabControl.getTab(i).updateBookmarkedStatus();
241 }
242 }
243
244 };
245 browser.getContentResolver().registerContentObserver(
246 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700247
248 mNetworkHandler = new NetworkStateHandler(mActivity, this);
249 // Start watching the default geolocation permissions
250 mSystemAllowGeolocationOrigins =
251 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
252 mSystemAllowGeolocationOrigins.start();
253
254 retainIconsOnStartup();
255 }
256
Patrick Scott7d50a932011-02-04 09:27:26 -0500257 void start(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700258 // Unless the last browser usage was within 24 hours, destroy any
259 // remaining incognito tabs.
260
261 Calendar lastActiveDate = icicle != null ?
262 (Calendar) icicle.getSerializable("lastActiveDate") : null;
263 Calendar today = Calendar.getInstance();
264 Calendar yesterday = Calendar.getInstance();
265 yesterday.add(Calendar.DATE, -1);
266
Patrick Scott7d50a932011-02-04 09:27:26 -0500267 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700268 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800269 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700270
Patrick Scott7d50a932011-02-04 09:27:26 -0500271 // Find out if we will restore any state and remember the tab.
272 final int currentTab =
273 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000274
Patrick Scott7d50a932011-02-04 09:27:26 -0500275 if (currentTab == -1) {
276 // Not able to restore so we go ahead and clear session cookies. We
277 // must do this before trying to login the user as we don't want to
278 // clear any session cookies set during login.
279 CookieManager.getInstance().removeSessionCookie();
280 }
281
282 GoogleAccountLogin.startLoginIfNeeded(mActivity, mSettings,
283 new Runnable() {
284 @Override public void run() {
285 start(icicle, intent, currentTab, restoreIncognitoTabs);
286 }
287 });
288 }
289
290 private void start(Bundle icicle, Intent intent, int currentTab,
291 boolean restoreIncognitoTabs) {
292 if (currentTab == -1) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700293 final Bundle extra = intent.getExtras();
294 // Create an initial tab.
295 // If the intent is ACTION_VIEW and data is not null, the Browser is
296 // invoked to view the content by another application. In this case,
297 // the tab will be close when exit.
298 UrlData urlData = mIntentHandler.getUrlDataFromIntent(intent);
299
300 String action = intent.getAction();
301 final Tab t = mTabControl.createNewTab(
302 (Intent.ACTION_VIEW.equals(action) &&
303 intent.getData() != null)
304 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
305 .equals(action),
306 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
307 urlData.mUrl, false);
308 addTab(t);
309 setActiveTab(t);
310 WebView webView = t.getWebView();
311 if (extra != null) {
312 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
313 if (scale > 0 && scale <= 1000) {
314 webView.setInitialScale(scale);
315 }
316 }
317
318 if (urlData.isEmpty()) {
319 loadUrl(webView, mSettings.getHomePage());
320 } else {
Michael Kolbcd424e92011-02-24 10:26:26 -0800321 // monkey protection against delayed start
322 if (t != null) {
323 loadUrlDataIn(t, urlData);
324 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700325 }
326 } else {
Patrick Scott7d50a932011-02-04 09:27:26 -0500327 mTabControl.restoreState(icicle, currentTab, restoreIncognitoTabs,
328 mUi.needsRestoreAllTabs());
Michael Kolb1bf23132010-11-19 12:55:12 -0800329 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700330 // TabControl.restoreState() will create a new tab even if
331 // restoring the state fails.
332 setActiveTab(mTabControl.getCurrentTab());
333 }
334 // clear up the thumbnail directory, which is no longer used;
335 // ideally this should only be run once after an upgrade from
336 // a previous version of the browser
337 new ClearThumbnails().execute(mTabControl.getThumbnailDir()
338 .listFiles());
339 // Read JavaScript flags if it exists.
340 String jsFlags = getSettings().getJsFlags();
341 if (jsFlags.trim().length() != 0) {
342 getCurrentWebView().setJsFlags(jsFlags);
343 }
John Reck439c9a52010-12-14 10:04:39 -0800344 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
345 bookmarksOrHistoryPicker(false);
346 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700347 }
348
349 void setWebViewFactory(WebViewFactory factory) {
350 mFactory = factory;
351 }
352
Michael Kolb1514bb72010-11-22 09:11:48 -0800353 @Override
354 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700355 return mFactory;
356 }
357
358 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800359 public void onSetWebView(Tab tab, WebView view) {
360 mUi.onSetWebView(tab, view);
361 }
362
363 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800364 public void createSubWindow(Tab tab) {
365 endActionMode();
366 WebView mainView = tab.getWebView();
367 WebView subView = mFactory.createWebView((mainView == null)
368 ? false
369 : mainView.isPrivateBrowsingEnabled());
370 mUi.createSubWindow(tab, subView);
371 }
372
373 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700374 public Activity getActivity() {
375 return mActivity;
376 }
377
378 void setUi(UI ui) {
379 mUi = ui;
380 }
381
382 BrowserSettings getSettings() {
383 return mSettings;
384 }
385
386 IntentHandler getIntentHandler() {
387 return mIntentHandler;
388 }
389
390 @Override
391 public UI getUi() {
392 return mUi;
393 }
394
395 int getMaxTabs() {
396 return mActivity.getResources().getInteger(R.integer.max_tabs);
397 }
398
399 @Override
400 public TabControl getTabControl() {
401 return mTabControl;
402 }
403
Michael Kolb1bf23132010-11-19 12:55:12 -0800404 @Override
405 public List<Tab> getTabs() {
406 return mTabControl.getTabs();
407 }
408
Michael Kolb8233fac2010-10-26 16:08:53 -0700409 // Open the icon database and retain all the icons for visited sites.
Ben Murdoch9446b932010-11-25 16:20:14 +0000410 // This is done on a background thread so as not to stall startup.
Michael Kolb8233fac2010-10-26 16:08:53 -0700411 private void retainIconsOnStartup() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000412 // WebIconDatabase needs to be retrieved on the UI thread so that if
413 // it has not been created successfully yet the Handler is started on the
414 // UI thread.
415 new RetainIconsOnStartupTask(WebIconDatabase.getInstance()).execute();
416 }
417
418 private class RetainIconsOnStartupTask extends AsyncTask<Void, Void, Void> {
419 private WebIconDatabase mDb;
420
421 public RetainIconsOnStartupTask(WebIconDatabase db) {
422 mDb = db;
423 }
424
John Recka00cbbd2010-12-16 12:38:19 -0800425 @Override
Ben Murdoch9446b932010-11-25 16:20:14 +0000426 protected Void doInBackground(Void... unused) {
427 mDb.open(mActivity.getDir("icons", 0).getPath());
428 Cursor c = null;
429 try {
430 c = Browser.getAllBookmarks(mActivity.getContentResolver());
431 if (c.moveToFirst()) {
432 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
433 do {
434 String url = c.getString(urlIndex);
435 mDb.retainIconForPageUrl(url);
436 } while (c.moveToNext());
437 }
438 } catch (IllegalStateException e) {
439 Log.e(LOGTAG, "retainIconsOnStartup", e);
440 } finally {
441 if (c != null) c.close();
Michael Kolb8233fac2010-10-26 16:08:53 -0700442 }
Ben Murdoch9446b932010-11-25 16:20:14 +0000443
444 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700445 }
446 }
447
448 private void startHandler() {
449 mHandler = new Handler() {
450
451 @Override
452 public void handleMessage(Message msg) {
453 switch (msg.what) {
454 case OPEN_BOOKMARKS:
455 bookmarksOrHistoryPicker(false);
456 break;
457 case FOCUS_NODE_HREF:
458 {
459 String url = (String) msg.getData().get("url");
460 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500461 String src = (String) msg.getData().get("src");
462 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700463 if (TextUtils.isEmpty(url)) {
464 break;
465 }
466 HashMap focusNodeMap = (HashMap) msg.obj;
467 WebView view = (WebView) focusNodeMap.get("webview");
468 // Only apply the action if the top window did not change.
469 if (getCurrentTopWebView() != view) {
470 break;
471 }
472 switch (msg.arg1) {
473 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -0700474 loadUrlFromContext(getCurrentTopWebView(), url);
475 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500476 case R.id.view_image_context_menu_id:
477 loadUrlFromContext(getCurrentTopWebView(), src);
478 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500479 case R.id.open_newtab_context_menu_id:
480 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -0800481 final Tab newTab = openTab(parent, url, false);
Leon Scroggins026f2542010-11-22 13:26:12 -0500482 if (newTab != null && newTab != parent) {
483 parent.addChildTab(newTab);
484 }
485 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700486 case R.id.copy_link_context_menu_id:
487 copy(url);
488 break;
489 case R.id.save_link_context_menu_id:
490 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500491 DownloadHandler.onDownloadStartNoStream(
492 mActivity, url, null, null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -0700493 break;
494 }
495 break;
496 }
497
498 case LOAD_URL:
499 loadUrlFromContext(getCurrentTopWebView(), (String) msg.obj);
500 break;
501
502 case STOP_LOAD:
503 stopLoading();
504 break;
505
506 case RELEASE_WAKELOCK:
507 if (mWakeLock.isHeld()) {
508 mWakeLock.release();
509 // if we reach here, Browser should be still in the
510 // background loading after WAKELOCK_TIMEOUT (5-min).
511 // To avoid burning the battery, stop loading.
512 mTabControl.stopAllLoading();
513 }
514 break;
515
516 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800517 Tab tab = (Tab) msg.obj;
518 if (tab != null) {
519 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700520 }
521 break;
522 }
523 }
524 };
525
526 }
527
Michael Kolbba99c5d2010-11-29 14:57:41 -0800528 @Override
529 public void shareCurrentPage() {
530 shareCurrentPage(mTabControl.getCurrentTab());
531 }
532
533 private void shareCurrentPage(Tab tab) {
534 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800535 sharePage(mActivity, tab.getTitle(),
536 tab.getUrl(), tab.getFavicon(),
537 createScreenshot(tab.getWebView(),
538 getDesiredThumbnailWidth(mActivity),
539 getDesiredThumbnailHeight(mActivity)));
540 }
541 }
542
Michael Kolb8233fac2010-10-26 16:08:53 -0700543 /**
544 * Share a page, providing the title, url, favicon, and a screenshot. Uses
545 * an {@link Intent} to launch the Activity chooser.
546 * @param c Context used to launch a new Activity.
547 * @param title Title of the page. Stored in the Intent with
548 * {@link Intent#EXTRA_SUBJECT}
549 * @param url URL of the page. Stored in the Intent with
550 * {@link Intent#EXTRA_TEXT}
551 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
552 * with {@link Browser#EXTRA_SHARE_FAVICON}
553 * @param screenshot Bitmap of a screenshot of the page. Stored in the
554 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
555 */
556 static final void sharePage(Context c, String title, String url,
557 Bitmap favicon, Bitmap screenshot) {
558 Intent send = new Intent(Intent.ACTION_SEND);
559 send.setType("text/plain");
560 send.putExtra(Intent.EXTRA_TEXT, url);
561 send.putExtra(Intent.EXTRA_SUBJECT, title);
562 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
563 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
564 try {
565 c.startActivity(Intent.createChooser(send, c.getString(
566 R.string.choosertitle_sharevia)));
567 } catch(android.content.ActivityNotFoundException ex) {
568 // if no app handles it, do nothing
569 }
570 }
571
572 private void copy(CharSequence text) {
573 ClipboardManager cm = (ClipboardManager) mActivity
574 .getSystemService(Context.CLIPBOARD_SERVICE);
575 cm.setText(text);
576 }
577
578 // lifecycle
579
580 protected void onConfgurationChanged(Configuration config) {
581 mConfigChanged = true;
582 if (mPageDialogsHandler != null) {
583 mPageDialogsHandler.onConfigurationChanged(config);
584 }
585 mUi.onConfigurationChanged(config);
586 }
587
588 @Override
589 public void handleNewIntent(Intent intent) {
590 mIntentHandler.onNewIntent(intent);
591 }
592
593 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800594 if (mUi.isCustomViewShowing()) {
595 hideCustomView();
596 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700597 if (mActivityPaused) {
598 Log.e(LOGTAG, "BrowserActivity is already paused.");
599 return;
600 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700601 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800602 Tab tab = mTabControl.getCurrentTab();
603 if (tab != null) {
604 tab.pause();
605 if (!pauseWebViewTimers(tab)) {
606 mWakeLock.acquire();
607 mHandler.sendMessageDelayed(mHandler
608 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
609 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700610 }
611 mUi.onPause();
612 mNetworkHandler.onPause();
613
614 WebView.disablePlatformNotifications();
615 }
616
617 void onSaveInstanceState(Bundle outState) {
618 // the default implementation requires each view to have an id. As the
619 // browser handles the state itself and it doesn't use id for the views,
620 // don't call the default implementation. Otherwise it will trigger the
621 // warning like this, "couldn't save which view has focus because the
622 // focused view XXX has no id".
623
624 // Save all the tabs
625 mTabControl.saveState(outState);
626 // Save time so that we know how old incognito tabs (if any) are.
627 outState.putSerializable("lastActiveDate", Calendar.getInstance());
628 }
629
630 void onResume() {
631 if (!mActivityPaused) {
632 Log.e(LOGTAG, "BrowserActivity is already resumed.");
633 return;
634 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700635 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800636 Tab current = mTabControl.getCurrentTab();
637 if (current != null) {
638 current.resume();
639 resumeWebViewTimers(current);
640 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700641 if (mWakeLock.isHeld()) {
642 mHandler.removeMessages(RELEASE_WAKELOCK);
643 mWakeLock.release();
644 }
645 mUi.onResume();
646 mNetworkHandler.onResume();
647 WebView.enablePlatformNotifications();
648 }
649
Michael Kolb70976932010-11-30 11:34:01 -0800650 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800651 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800652 * @param tab guaranteed non-null
653 */
654 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700655 boolean inLoad = tab.inPageLoad();
656 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
657 CookieSyncManager.getInstance().startSync();
658 WebView w = tab.getWebView();
659 if (w != null) {
660 w.resumeTimers();
661 }
662 }
663 }
664
Michael Kolb70976932010-11-30 11:34:01 -0800665 /**
666 * Pause all WebView timers using the WebView of the given tab
667 * @param tab
668 * @return true if the timers are paused or tab is null
669 */
670 private boolean pauseWebViewTimers(Tab tab) {
671 if (tab == null) {
672 return true;
673 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700674 CookieSyncManager.getInstance().stopSync();
675 WebView w = getCurrentWebView();
676 if (w != null) {
677 w.pauseTimers();
678 }
679 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700680 }
Michael Kolb70976932010-11-30 11:34:01 -0800681 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700682 }
683
684 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800685 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700686 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
687 mUploadHandler = null;
688 }
689 if (mTabControl == null) return;
690 mUi.onDestroy();
691 // Remove the current tab and sub window
692 Tab t = mTabControl.getCurrentTab();
693 if (t != null) {
694 dismissSubWindow(t);
695 removeTab(t);
696 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500697 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700698 // Destroy all the tabs
699 mTabControl.destroy();
700 WebIconDatabase.getInstance().close();
701 // Stop watching the default geolocation permissions
702 mSystemAllowGeolocationOrigins.stop();
703 mSystemAllowGeolocationOrigins = null;
704 }
705
706 protected boolean isActivityPaused() {
707 return mActivityPaused;
708 }
709
710 protected void onLowMemory() {
711 mTabControl.freeMemory();
712 }
713
714 @Override
715 public boolean shouldShowErrorConsole() {
716 return mShouldShowErrorConsole;
717 }
718
719 protected void setShouldShowErrorConsole(boolean show) {
720 if (show == mShouldShowErrorConsole) {
721 // Nothing to do.
722 return;
723 }
724 mShouldShowErrorConsole = show;
725 Tab t = mTabControl.getCurrentTab();
726 if (t == null) {
727 // There is no current tab so we cannot toggle the error console
728 return;
729 }
730 mUi.setShouldShowErrorConsole(t, show);
731 }
732
733 @Override
734 public void stopLoading() {
735 mLoadStopped = true;
736 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700737 WebView w = getCurrentTopWebView();
738 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700739 mUi.onPageStopped(tab);
740 }
741
742 boolean didUserStopLoading() {
743 return mLoadStopped;
744 }
745
746 // WebViewController
747
748 @Override
John Reck324d4402011-01-11 16:56:42 -0800749 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700750
751 // We've started to load a new page. If there was a pending message
752 // to save a screenshot then we will now take the new page and save
753 // an incorrect screenshot. Therefore, remove any pending thumbnail
754 // messages from the queue.
755 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800756 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700757
758 // reset sync timer to avoid sync starts during loading a page
759 CookieSyncManager.getInstance().resetSync();
760
761 if (!mNetworkHandler.isNetworkUp()) {
762 view.setNetworkAvailable(false);
763 }
764
765 // when BrowserActivity just starts, onPageStarted may be called before
766 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
767 // to start the timer. As we won't switch tabs while an activity is in
768 // pause state, we can ensure calling resume and pause in pair.
769 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800770 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700771 }
772 mLoadStopped = false;
773 if (!mNetworkHandler.isNetworkUp()) {
774 mNetworkHandler.createAndShowNetworkDialog();
775 }
776 endActionMode();
777
John Reck30c714c2010-12-16 17:30:34 -0800778 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700779
John Reck324d4402011-01-11 16:56:42 -0800780 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700781 // update the bookmark database for favicon
782 maybeUpdateFavicon(tab, null, url, favicon);
783
784 Performance.tracePageStart(url);
785
786 // Performance probe
787 if (false) {
788 Performance.onPageStarted();
789 }
790
791 }
792
793 @Override
John Reck324d4402011-01-11 16:56:42 -0800794 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800795 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800796 if (!tab.isPrivateBrowsingEnabled()
797 && !TextUtils.isEmpty(tab.getUrl())) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700798 if (tab.inForeground() && !didUserStopLoading()
799 || !tab.inForeground()) {
800 // Only update the bookmark screenshot if the user did not
801 // cancel the load early.
802 mHandler.sendMessageDelayed(mHandler.obtainMessage(
John Reck34ef2672011-02-10 11:30:55 -0800803 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
Michael Kolb8233fac2010-10-26 16:08:53 -0700804 500);
805 }
806 }
807 // pause the WebView timer and release the wake lock if it is finished
808 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800809 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700810 if (mWakeLock.isHeld()) {
811 mHandler.removeMessages(RELEASE_WAKELOCK);
812 mWakeLock.release();
813 }
814 }
815 // Performance probe
816 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800817 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700818 }
819
820 Performance.tracePageFinished();
821 }
822
823 @Override
John Reck30c714c2010-12-16 17:30:34 -0800824 public void onProgressChanged(Tab tab) {
825 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700826
827 if (newProgress == 100) {
828 CookieSyncManager.getInstance().sync();
829 // onProgressChanged() may continue to be called after the main
830 // frame has finished loading, as any remaining sub frames continue
831 // to load. We'll only get called once though with newProgress as
832 // 100 when everything is loaded. (onPageFinished is called once
833 // when the main frame completes loading regardless of the state of
834 // any sub frames so calls to onProgressChanges may continue after
835 // onPageFinished has executed)
836 if (mInLoad) {
837 mInLoad = false;
838 updateInLoadMenuItems(mCachedMenu);
839 }
840 } else {
841 if (!mInLoad) {
842 // onPageFinished may have already been called but a subframe is
843 // still loading and updating the progress. Reset mInLoad and
844 // update the menu items.
845 mInLoad = true;
846 updateInLoadMenuItems(mCachedMenu);
847 }
848 }
John Reck30c714c2010-12-16 17:30:34 -0800849 mUi.onProgressChanged(tab);
850 }
851
852 @Override
853 public void onUpdatedLockIcon(Tab tab) {
854 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700855 }
856
857 @Override
858 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800859 mUi.onTabDataChanged(tab);
860 final String pageUrl = tab.getUrl();
John Reck324d4402011-01-11 16:56:42 -0800861 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700862 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
863 return;
864 }
865 // Update the title in the history database if not in private browsing mode
866 if (!tab.isPrivateBrowsingEnabled()) {
John Reck0ebd3ac2010-12-09 11:14:04 -0800867 mDataController.updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700868 }
869 }
870
871 @Override
872 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800873 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700874 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
875 }
876
877 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800878 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
879 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700880 }
881
882 @Override
883 public boolean shouldOverrideKeyEvent(KeyEvent event) {
884 if (mMenuIsDown) {
885 // only check shortcut key when MENU is held
886 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
887 event);
888 } else {
889 return false;
890 }
891 }
892
893 @Override
894 public void onUnhandledKeyEvent(KeyEvent event) {
895 if (!isActivityPaused()) {
896 if (event.getAction() == KeyEvent.ACTION_DOWN) {
897 mActivity.onKeyDown(event.getKeyCode(), event);
898 } else {
899 mActivity.onKeyUp(event.getKeyCode(), event);
900 }
901 }
902 }
903
904 @Override
John Reck324d4402011-01-11 16:56:42 -0800905 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700906 // Don't save anything in private browsing mode
907 if (tab.isPrivateBrowsingEnabled()) return;
John Reck324d4402011-01-11 16:56:42 -0800908 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700909
John Reck324d4402011-01-11 16:56:42 -0800910 if (TextUtils.isEmpty(url)
911 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700912 return;
913 }
John Reck0ebd3ac2010-12-09 11:14:04 -0800914 mDataController.updateVisitedHistory(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700915 WebIconDatabase.getInstance().retainIconForPageUrl(url);
916 }
917
918 @Override
919 public void getVisitedHistory(final ValueCallback<String[]> callback) {
920 AsyncTask<Void, Void, String[]> task =
921 new AsyncTask<Void, Void, String[]>() {
922 @Override
923 public String[] doInBackground(Void... unused) {
924 return Browser.getVisitedHistory(mActivity.getContentResolver());
925 }
926 @Override
927 public void onPostExecute(String[] result) {
928 callback.onReceiveValue(result);
929 }
930 };
931 task.execute();
932 }
933
934 @Override
935 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
936 final HttpAuthHandler handler, final String host,
937 final String realm) {
938 String username = null;
939 String password = null;
940
941 boolean reuseHttpAuthUsernamePassword
942 = handler.useHttpAuthUsernamePassword();
943
944 if (reuseHttpAuthUsernamePassword && view != null) {
945 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
946 if (credentials != null && credentials.length == 2) {
947 username = credentials[0];
948 password = credentials[1];
949 }
950 }
951
952 if (username != null && password != null) {
953 handler.proceed(username, password);
954 } else {
955 if (tab.inForeground()) {
956 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
957 } else {
958 handler.cancel();
959 }
960 }
961 }
962
963 @Override
964 public void onDownloadStart(Tab tab, String url, String userAgent,
965 String contentDisposition, String mimetype, long contentLength) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500966 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
967 contentDisposition, mimetype);
Michael Kolb8233fac2010-10-26 16:08:53 -0700968 if (tab.getWebView().copyBackForwardList().getSize() == 0) {
969 // This Tab was opened for the sole purpose of downloading a
970 // file. Remove it.
971 if (tab == mTabControl.getCurrentTab()) {
972 // In this case, the Tab is still on top.
973 goBackOnePageOrQuit();
974 } else {
975 // In this case, it is not.
976 closeTab(tab);
977 }
978 }
979 }
980
981 @Override
982 public Bitmap getDefaultVideoPoster() {
983 return mUi.getDefaultVideoPoster();
984 }
985
986 @Override
987 public View getVideoLoadingProgressView() {
988 return mUi.getVideoLoadingProgressView();
989 }
990
991 @Override
992 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
993 SslError error) {
994 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
995 }
996
997 // helper method
998
999 /*
1000 * Update the favorites icon if the private browsing isn't enabled and the
1001 * icon is valid.
1002 */
1003 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1004 final String url, Bitmap favicon) {
1005 if (favicon == null) {
1006 return;
1007 }
1008 if (!tab.isPrivateBrowsingEnabled()) {
1009 Bookmarks.updateFavicon(mActivity
1010 .getContentResolver(), originalUrl, url, favicon);
1011 }
1012 }
1013
Leon Scroggins4cd97792010-12-03 15:31:56 -05001014 @Override
1015 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001016 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001017 mUi.bookmarkedStatusHasChanged(tab);
1018 }
1019
Michael Kolb8233fac2010-10-26 16:08:53 -07001020 // end WebViewController
1021
1022 protected void pageUp() {
1023 getCurrentTopWebView().pageUp(false);
1024 }
1025
1026 protected void pageDown() {
1027 getCurrentTopWebView().pageDown(false);
1028 }
1029
1030 // callback from phone title bar
1031 public void editUrl() {
1032 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001033 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001034 }
1035
Michael Kolbcfa3af52010-12-14 10:36:11 -08001036 public void startVoiceSearch() {
1037 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1038 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1039 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1040 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1041 mActivity.getComponentName().flattenToString());
1042 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001043 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001044 mActivity.startActivity(intent);
1045 }
1046
Michael Kolb8233fac2010-10-26 16:08:53 -07001047 public void activateVoiceSearchMode(String title) {
1048 mUi.showVoiceTitleBar(title);
1049 }
1050
1051 public void revertVoiceSearchMode(Tab tab) {
1052 mUi.revertVoiceTitleBar(tab);
1053 }
1054
1055 public void showCustomView(Tab tab, View view,
1056 WebChromeClient.CustomViewCallback callback) {
1057 if (tab.inForeground()) {
1058 if (mUi.isCustomViewShowing()) {
1059 callback.onCustomViewHidden();
1060 return;
1061 }
1062 mUi.showCustomView(view, callback);
1063 // Save the menu state and set it to empty while the custom
1064 // view is showing.
1065 mOldMenuState = mMenuState;
1066 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001067 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001068 }
1069 }
1070
1071 @Override
1072 public void hideCustomView() {
1073 if (mUi.isCustomViewShowing()) {
1074 mUi.onHideCustomView();
1075 // Reset the old menu state.
1076 mMenuState = mOldMenuState;
1077 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001078 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001079 }
1080 }
1081
1082 protected void onActivityResult(int requestCode, int resultCode,
1083 Intent intent) {
1084 if (getCurrentTopWebView() == null) return;
1085 switch (requestCode) {
1086 case PREFERENCES_PAGE:
1087 if (resultCode == Activity.RESULT_OK && intent != null) {
1088 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
1089 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
1090 mTabControl.removeParentChildRelationShips();
1091 }
1092 }
1093 break;
1094 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001095 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001096 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001097 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001098 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001099 case AUTOFILL_SETUP:
1100 // Determine whether a profile was actually set up or not
1101 // and if so, send the message back to the WebTextView to
1102 // fill the form with the new profile.
1103 if (getSettings().getAutoFillProfile() != null) {
1104 mAutoFillSetupMessage.sendToTarget();
1105 mAutoFillSetupMessage = null;
1106 }
1107 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001108 default:
1109 break;
1110 }
1111 getCurrentTopWebView().requestFocus();
1112 }
1113
1114 /**
1115 * Open the Go page.
1116 * @param startWithHistory If true, open starting on the history tab.
1117 * Otherwise, start with the bookmarks tab.
1118 */
1119 @Override
1120 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1121 if (mTabControl.getCurrentWebView() == null) {
1122 return;
1123 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001124 // clear action mode
1125 if (isInCustomActionMode()) {
1126 endActionMode();
1127 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001128 Bundle extras = new Bundle();
1129 // Disable opening in a new window if we have maxed out the windows
1130 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1131 !mTabControl.canCreateNewTab());
1132 mUi.showComboView(startWithHistory, extras);
1133 }
1134
1135 // combo view callbacks
1136
1137 /**
1138 * callback from ComboPage when clear history is requested
1139 */
1140 public void onRemoveParentChildRelationships() {
1141 mTabControl.removeParentChildRelationShips();
1142 }
1143
1144 /**
1145 * callback from ComboPage when bookmark/history selection
1146 */
1147 @Override
1148 public void onUrlSelected(String url, boolean newTab) {
1149 removeComboView();
1150 if (!TextUtils.isEmpty(url)) {
1151 if (newTab) {
Michael Kolb18eb3772010-12-10 14:29:51 -08001152 openTab(mTabControl.getCurrentTab(), url, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001153 } else {
1154 final Tab currentTab = mTabControl.getCurrentTab();
1155 dismissSubWindow(currentTab);
1156 loadUrl(getCurrentTopWebView(), url);
1157 }
1158 }
1159 }
1160
1161 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07001162 * dismiss the ComboPage
1163 */
1164 @Override
1165 public void removeComboView() {
1166 mUi.hideComboView();
1167 }
1168
1169 // active tabs page handling
1170
1171 protected void showActiveTabsPage() {
1172 mMenuState = EMPTY_MENU;
1173 mUi.showActiveTabsPage();
1174 }
1175
1176 /**
1177 * Remove the active tabs page.
1178 * @param needToAttach If true, the active tabs page did not attach a tab
1179 * to the content view, so we need to do that here.
1180 */
1181 @Override
1182 public void removeActiveTabsPage(boolean needToAttach) {
1183 mMenuState = R.id.MAIN_MENU;
1184 mUi.removeActiveTabsPage();
1185 if (needToAttach) {
1186 setActiveTab(mTabControl.getCurrentTab());
1187 }
1188 getCurrentTopWebView().requestFocus();
1189 }
1190
1191 // key handling
1192 protected void onBackKey() {
1193 if (!mUi.onBackKey()) {
1194 WebView subwindow = mTabControl.getCurrentSubWindow();
1195 if (subwindow != null) {
1196 if (subwindow.canGoBack()) {
1197 subwindow.goBack();
1198 } else {
1199 dismissSubWindow(mTabControl.getCurrentTab());
1200 }
1201 } else {
1202 goBackOnePageOrQuit();
1203 }
1204 }
1205 }
1206
1207 // menu handling and state
1208 // TODO: maybe put into separate handler
1209
1210 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckb3417f02011-01-14 11:01:05 -08001211 if (mOptionsMenuHandler != null) {
1212 return mOptionsMenuHandler.onCreateOptionsMenu(menu);
1213 }
1214
John Reckd73c5a22010-12-22 10:22:50 -08001215 if (mMenuState == EMPTY_MENU) {
1216 return false;
1217 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001218 MenuInflater inflater = mActivity.getMenuInflater();
1219 inflater.inflate(R.menu.browser, menu);
1220 updateInLoadMenuItems(menu);
1221 // hold on to the menu reference here; it is used by the page callbacks
1222 // to update the menu based on loading state
1223 mCachedMenu = menu;
1224 return true;
1225 }
1226
1227 protected void onCreateContextMenu(ContextMenu menu, View v,
1228 ContextMenuInfo menuInfo) {
1229 if (v instanceof TitleBarBase) {
1230 return;
1231 }
1232 if (!(v instanceof WebView)) {
1233 return;
1234 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001235 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001236 WebView.HitTestResult result = webview.getHitTestResult();
1237 if (result == null) {
1238 return;
1239 }
1240
1241 int type = result.getType();
1242 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1243 Log.w(LOGTAG,
1244 "We should not show context menu when nothing is touched");
1245 return;
1246 }
1247 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1248 // let TextView handles context menu
1249 return;
1250 }
1251
1252 // Note, http://b/issue?id=1106666 is requesting that
1253 // an inflated menu can be used again. This is not available
1254 // yet, so inflate each time (yuk!)
1255 MenuInflater inflater = mActivity.getMenuInflater();
1256 inflater.inflate(R.menu.browsercontext, menu);
1257
1258 // Show the correct menu group
1259 final String extra = result.getExtra();
1260 menu.setGroupVisible(R.id.PHONE_MENU,
1261 type == WebView.HitTestResult.PHONE_TYPE);
1262 menu.setGroupVisible(R.id.EMAIL_MENU,
1263 type == WebView.HitTestResult.EMAIL_TYPE);
1264 menu.setGroupVisible(R.id.GEO_MENU,
1265 type == WebView.HitTestResult.GEO_TYPE);
1266 menu.setGroupVisible(R.id.IMAGE_MENU,
1267 type == WebView.HitTestResult.IMAGE_TYPE
1268 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1269 menu.setGroupVisible(R.id.ANCHOR_MENU,
1270 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1271 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001272 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1273 || type == WebView.HitTestResult.PHONE_TYPE
1274 || type == WebView.HitTestResult.EMAIL_TYPE
1275 || type == WebView.HitTestResult.GEO_TYPE;
1276 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1277 if (hitText) {
1278 menu.findItem(R.id.select_text_menu_id)
1279 .setOnMenuItemClickListener(new SelectText(webview));
1280 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001281 // Setup custom handling depending on the type
1282 switch (type) {
1283 case WebView.HitTestResult.PHONE_TYPE:
1284 menu.setHeaderTitle(Uri.decode(extra));
1285 menu.findItem(R.id.dial_context_menu_id).setIntent(
1286 new Intent(Intent.ACTION_VIEW, Uri
1287 .parse(WebView.SCHEME_TEL + extra)));
1288 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1289 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1290 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1291 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1292 addIntent);
1293 menu.findItem(R.id.copy_phone_context_menu_id)
1294 .setOnMenuItemClickListener(
1295 new Copy(extra));
1296 break;
1297
1298 case WebView.HitTestResult.EMAIL_TYPE:
1299 menu.setHeaderTitle(extra);
1300 menu.findItem(R.id.email_context_menu_id).setIntent(
1301 new Intent(Intent.ACTION_VIEW, Uri
1302 .parse(WebView.SCHEME_MAILTO + extra)));
1303 menu.findItem(R.id.copy_mail_context_menu_id)
1304 .setOnMenuItemClickListener(
1305 new Copy(extra));
1306 break;
1307
1308 case WebView.HitTestResult.GEO_TYPE:
1309 menu.setHeaderTitle(extra);
1310 menu.findItem(R.id.map_context_menu_id).setIntent(
1311 new Intent(Intent.ACTION_VIEW, Uri
1312 .parse(WebView.SCHEME_GEO
1313 + URLEncoder.encode(extra))));
1314 menu.findItem(R.id.copy_geo_context_menu_id)
1315 .setOnMenuItemClickListener(
1316 new Copy(extra));
1317 break;
1318
1319 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1320 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001321 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001322 // decide whether to show the open link in new tab option
1323 boolean showNewTab = mTabControl.canCreateNewTab();
1324 MenuItem newTabItem
1325 = menu.findItem(R.id.open_newtab_context_menu_id);
Michael Kolb2dd65c82011-01-14 11:07:38 -08001326 newTabItem.setTitle(
1327 BrowserSettings.getInstance().openInBackground()
1328 ? R.string.contextmenu_openlink_newwindow_background
1329 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001330 newTabItem.setVisible(showNewTab);
1331 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001332 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1333 newTabItem.setOnMenuItemClickListener(
1334 new MenuItem.OnMenuItemClickListener() {
1335 @Override
1336 public boolean onMenuItemClick(MenuItem item) {
1337 final HashMap<String, WebView> hrefMap =
1338 new HashMap<String, WebView>();
1339 hrefMap.put("webview", webview);
1340 final Message msg = mHandler.obtainMessage(
1341 FOCUS_NODE_HREF,
1342 R.id.open_newtab_context_menu_id,
1343 0, hrefMap);
1344 webview.requestFocusNodeHref(msg);
1345 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001346 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001347 });
1348 } else {
1349 newTabItem.setOnMenuItemClickListener(
1350 new MenuItem.OnMenuItemClickListener() {
1351 @Override
1352 public boolean onMenuItemClick(MenuItem item) {
1353 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -08001354 final Tab newTab = openTab(parent,
1355 extra, false);
Leon Scroggins026f2542010-11-22 13:26:12 -05001356 if (newTab != parent) {
1357 parent.addChildTab(newTab);
1358 }
1359 return true;
1360 }
1361 });
1362 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001363 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001364 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1365 break;
1366 }
1367 // otherwise fall through to handle image part
1368 case WebView.HitTestResult.IMAGE_TYPE:
1369 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1370 menu.setHeaderTitle(extra);
1371 }
1372 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1373 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1374 menu.findItem(R.id.download_context_menu_id).
Leon Scroggins63c02662010-11-18 15:16:27 -05001375 setOnMenuItemClickListener(new Download(mActivity, extra));
John Reck3527dd12011-02-22 10:35:29 -08001376 menu.findItem(R.id.set_wallpaper_context_menu_id).
1377 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1378 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001379 break;
1380
1381 default:
1382 Log.w(LOGTAG, "We should not get here.");
1383 break;
1384 }
1385 //update the ui
1386 mUi.onContextMenuCreated(menu);
1387 }
1388
1389 /**
1390 * As the menu can be open when loading state changes
1391 * we must manually update the state of the stop/reload menu
1392 * item
1393 */
1394 private void updateInLoadMenuItems(Menu menu) {
1395 if (menu == null) {
1396 return;
1397 }
1398 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1399 MenuItem src = mInLoad ?
1400 menu.findItem(R.id.stop_menu_id):
1401 menu.findItem(R.id.reload_menu_id);
1402 if (src != null) {
1403 dest.setIcon(src.getIcon());
1404 dest.setTitle(src.getTitle());
1405 }
1406 }
1407
John Reckb3417f02011-01-14 11:01:05 -08001408 boolean onPrepareOptionsMenu(Menu menu) {
1409 if (mOptionsMenuHandler != null) {
1410 return mOptionsMenuHandler.onPrepareOptionsMenu(menu);
1411 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001412 // This happens when the user begins to hold down the menu key, so
1413 // allow them to chord to get a shortcut.
1414 mCanChord = true;
1415 // Note: setVisible will decide whether an item is visible; while
1416 // setEnabled() will decide whether an item is enabled, which also means
1417 // whether the matching shortcut key will function.
1418 switch (mMenuState) {
1419 case EMPTY_MENU:
1420 if (mCurrentMenuState != mMenuState) {
1421 menu.setGroupVisible(R.id.MAIN_MENU, false);
1422 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1423 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1424 }
1425 break;
1426 default:
1427 if (mCurrentMenuState != mMenuState) {
1428 menu.setGroupVisible(R.id.MAIN_MENU, true);
1429 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1430 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1431 }
1432 final WebView w = getCurrentTopWebView();
1433 boolean canGoBack = false;
1434 boolean canGoForward = false;
1435 boolean isHome = false;
1436 if (w != null) {
1437 canGoBack = w.canGoBack();
1438 canGoForward = w.canGoForward();
1439 isHome = mSettings.getHomePage().equals(w.getUrl());
1440 }
1441 final MenuItem back = menu.findItem(R.id.back_menu_id);
1442 back.setEnabled(canGoBack);
1443
1444 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1445 home.setEnabled(!isHome);
1446
1447 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1448 forward.setEnabled(canGoForward);
1449
1450 // decide whether to show the share link option
1451 PackageManager pm = mActivity.getPackageManager();
1452 Intent send = new Intent(Intent.ACTION_SEND);
1453 send.setType("text/plain");
1454 ResolveInfo ri = pm.resolveActivity(send,
1455 PackageManager.MATCH_DEFAULT_ONLY);
1456 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1457
1458 boolean isNavDump = mSettings.isNavDump();
1459 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1460 nav.setVisible(isNavDump);
1461 nav.setEnabled(isNavDump);
1462
1463 boolean showDebugSettings = mSettings.showDebugSettings();
1464 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1465 counter.setVisible(showDebugSettings);
1466 counter.setEnabled(showDebugSettings);
1467
John Reckb3417f02011-01-14 11:01:05 -08001468 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1469 newtab.setEnabled(getTabControl().canCreateNewTab());
Michael Kolb8233fac2010-10-26 16:08:53 -07001470
Leon Scroggins81983762011-02-11 15:17:36 -05001471 MenuItem archive = menu.findItem(R.id.save_webarchive_menu_id);
Cary Clarkba860522011-02-16 11:22:42 -05001472 String url = w != null ? w.getUrl() : null;
1473 archive.setVisible(url != null && !url.endsWith(".webarchivexml"));
Michael Kolb8233fac2010-10-26 16:08:53 -07001474 break;
1475 }
1476 mCurrentMenuState = mMenuState;
1477 return true;
1478 }
1479
1480 public boolean onOptionsItemSelected(MenuItem item) {
John Reckb3417f02011-01-14 11:01:05 -08001481 if (mOptionsMenuHandler != null &&
1482 mOptionsMenuHandler.onOptionsItemSelected(item)) {
1483 return true;
1484 }
1485
Michael Kolb8233fac2010-10-26 16:08:53 -07001486 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1487 // menu remains active, so ensure comboview is dismissed
1488 // if main menu option is selected
1489 removeComboView();
1490 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001491 if (!mCanChord) {
1492 // The user has already fired a shortcut with this hold down of the
1493 // menu key.
1494 return false;
1495 }
1496 if (null == getCurrentTopWebView()) {
1497 return false;
1498 }
1499 if (mMenuIsDown) {
1500 // The shortcut action consumes the MENU. Even if it is still down,
1501 // it won't trigger the next shortcut action. In the case of the
1502 // shortcut action triggering a new activity, like Bookmarks, we
1503 // won't get onKeyUp for MENU. So it is important to reset it here.
1504 mMenuIsDown = false;
1505 }
1506 switch (item.getItemId()) {
1507 // -- Main menu
1508 case R.id.new_tab_menu_id:
1509 openTabToHomePage();
1510 break;
1511
1512 case R.id.incognito_menu_id:
1513 openIncognitoTab();
1514 break;
1515
1516 case R.id.goto_menu_id:
1517 editUrl();
1518 break;
1519
1520 case R.id.bookmarks_menu_id:
1521 bookmarksOrHistoryPicker(false);
1522 break;
1523
1524 case R.id.active_tabs_menu_id:
1525 showActiveTabsPage();
1526 break;
1527
1528 case R.id.add_bookmark_menu_id:
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001529 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001530 break;
1531
1532 case R.id.stop_reload_menu_id:
1533 if (mInLoad) {
1534 stopLoading();
1535 } else {
1536 getCurrentTopWebView().reload();
1537 }
1538 break;
1539
1540 case R.id.back_menu_id:
1541 getCurrentTopWebView().goBack();
1542 break;
1543
1544 case R.id.forward_menu_id:
1545 getCurrentTopWebView().goForward();
1546 break;
1547
1548 case R.id.close_menu_id:
1549 // Close the subwindow if it exists.
1550 if (mTabControl.getCurrentSubWindow() != null) {
1551 dismissSubWindow(mTabControl.getCurrentTab());
1552 break;
1553 }
1554 closeCurrentTab();
1555 break;
1556
1557 case R.id.homepage_menu_id:
1558 Tab current = mTabControl.getCurrentTab();
1559 if (current != null) {
1560 dismissSubWindow(current);
1561 loadUrl(current.getWebView(), mSettings.getHomePage());
1562 }
1563 break;
1564
1565 case R.id.preferences_menu_id:
1566 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1567 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1568 getCurrentTopWebView().getUrl());
1569 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1570 break;
1571
1572 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001573 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001574 break;
1575
Leon Scrogginsac993842011-02-02 12:54:07 -05001576 case R.id.save_webarchive_menu_id:
1577 String state = Environment.getExternalStorageState();
1578 if (!Environment.MEDIA_MOUNTED.equals(state)) {
1579 Log.e(LOGTAG, "External storage not mounted");
1580 Toast.makeText(mActivity, R.string.webarchive_failed,
1581 Toast.LENGTH_SHORT).show();
1582 break;
1583 }
1584 final String directory = Environment.getExternalStoragePublicDirectory(
1585 Environment.DIRECTORY_DOWNLOADS) + File.separator;
1586 File dir = new File(directory);
1587 if (!dir.exists() && !dir.mkdirs()) {
1588 Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
1589 Toast.makeText(mActivity, R.string.webarchive_failed,
1590 Toast.LENGTH_SHORT).show();
1591 break;
1592 }
1593 WebView topWebView = getCurrentTopWebView();
1594 final String title = topWebView.getTitle();
1595 topWebView.saveWebArchive(directory, true,
1596 new ValueCallback<String>() {
1597 @Override
1598 public void onReceiveValue(final String value) {
1599 if (value != null) {
1600 File file = new File(value);
1601 final long length = file.length();
1602 if (file.exists() && length > 0) {
Leon Scroggins1cb96552011-02-11 14:22:57 -05001603 Toast.makeText(mActivity, R.string.webarchive_saved,
1604 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001605 final DownloadManager manager = (DownloadManager) mActivity
1606 .getSystemService(Context.DOWNLOAD_SERVICE);
1607 new Thread("Add WebArchive to download manager") {
1608 @Override
1609 public void run() {
1610 manager.completedDownload(null == title ? value : title,
1611 value, true, "application/x-webarchive-xml",
1612 value, length, true);
1613 }
1614 }.start();
1615 return;
1616 }
1617 }
1618 Toast.makeText(mActivity,
1619 R.string.webarchive_failed, Toast.LENGTH_SHORT).show();
1620 }
1621 });
1622 break;
1623
Michael Kolb8233fac2010-10-26 16:08:53 -07001624 case R.id.page_info_menu_id:
1625 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1626 false);
1627 break;
1628
1629 case R.id.classic_history_menu_id:
1630 bookmarksOrHistoryPicker(true);
1631 break;
1632
1633 case R.id.title_bar_share_page_url:
1634 case R.id.share_page_menu_id:
1635 Tab currentTab = mTabControl.getCurrentTab();
1636 if (null == currentTab) {
1637 mCanChord = false;
1638 return false;
1639 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001640 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001641 break;
1642
1643 case R.id.dump_nav_menu_id:
1644 getCurrentTopWebView().debugDump();
1645 break;
1646
1647 case R.id.dump_counters_menu_id:
1648 getCurrentTopWebView().dumpV8Counters();
1649 break;
1650
1651 case R.id.zoom_in_menu_id:
1652 getCurrentTopWebView().zoomIn();
1653 break;
1654
1655 case R.id.zoom_out_menu_id:
1656 getCurrentTopWebView().zoomOut();
1657 break;
1658
1659 case R.id.view_downloads_menu_id:
1660 viewDownloads();
1661 break;
1662
1663 case R.id.window_one_menu_id:
1664 case R.id.window_two_menu_id:
1665 case R.id.window_three_menu_id:
1666 case R.id.window_four_menu_id:
1667 case R.id.window_five_menu_id:
1668 case R.id.window_six_menu_id:
1669 case R.id.window_seven_menu_id:
1670 case R.id.window_eight_menu_id:
1671 {
1672 int menuid = item.getItemId();
1673 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1674 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1675 Tab desiredTab = mTabControl.getTab(id);
1676 if (desiredTab != null &&
1677 desiredTab != mTabControl.getCurrentTab()) {
1678 switchToTab(id);
1679 }
1680 break;
1681 }
1682 }
1683 }
1684 break;
1685
1686 default:
1687 return false;
1688 }
1689 mCanChord = false;
1690 return true;
1691 }
1692
1693 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001694 // Let the History and Bookmark fragments handle menus they created.
1695 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1696 return false;
1697 }
1698
Michael Kolb8233fac2010-10-26 16:08:53 -07001699 // chording is not an issue with context menus, but we use the same
1700 // options selector, so set mCanChord to true so we can access them.
1701 mCanChord = true;
1702 int id = item.getItemId();
1703 boolean result = true;
1704 switch (id) {
1705 // For the context menu from the title bar
1706 case R.id.title_bar_copy_page_url:
1707 Tab currentTab = mTabControl.getCurrentTab();
1708 if (null == currentTab) {
1709 result = false;
1710 break;
1711 }
1712 WebView mainView = currentTab.getWebView();
1713 if (null == mainView) {
1714 result = false;
1715 break;
1716 }
1717 copy(mainView.getUrl());
1718 break;
1719 // -- Browser context menu
1720 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001721 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001722 case R.id.copy_link_context_menu_id:
1723 final WebView webView = getCurrentTopWebView();
1724 if (null == webView) {
1725 result = false;
1726 break;
1727 }
1728 final HashMap<String, WebView> hrefMap =
1729 new HashMap<String, WebView>();
1730 hrefMap.put("webview", webView);
1731 final Message msg = mHandler.obtainMessage(
1732 FOCUS_NODE_HREF, id, 0, hrefMap);
1733 webView.requestFocusNodeHref(msg);
1734 break;
1735
1736 default:
1737 // For other context menus
1738 result = onOptionsItemSelected(item);
1739 }
1740 mCanChord = false;
1741 return result;
1742 }
1743
1744 /**
1745 * support programmatically opening the context menu
1746 */
1747 public void openContextMenu(View view) {
1748 mActivity.openContextMenu(view);
1749 }
1750
1751 /**
1752 * programmatically open the options menu
1753 */
1754 public void openOptionsMenu() {
1755 mActivity.openOptionsMenu();
1756 }
1757
1758 public boolean onMenuOpened(int featureId, Menu menu) {
1759 if (mOptionsMenuOpen) {
1760 if (mConfigChanged) {
1761 // We do not need to make any changes to the state of the
1762 // title bar, since the only thing that happened was a
1763 // change in orientation
1764 mConfigChanged = false;
1765 } else {
1766 if (!mExtendedMenuOpen) {
1767 mExtendedMenuOpen = true;
1768 mUi.onExtendedMenuOpened();
1769 } else {
1770 // Switching the menu back to icon view, so show the
1771 // title bar once again.
1772 mExtendedMenuOpen = false;
1773 mUi.onExtendedMenuClosed(mInLoad);
1774 mUi.onOptionsMenuOpened();
1775 }
1776 }
1777 } else {
1778 // The options menu is closed, so open it, and show the title
1779 mOptionsMenuOpen = true;
1780 mConfigChanged = false;
1781 mExtendedMenuOpen = false;
1782 mUi.onOptionsMenuOpened();
1783 }
1784 return true;
1785 }
1786
1787 public void onOptionsMenuClosed(Menu menu) {
1788 mOptionsMenuOpen = false;
1789 mUi.onOptionsMenuClosed(mInLoad);
1790 }
1791
1792 public void onContextMenuClosed(Menu menu) {
1793 mUi.onContextMenuClosed(menu, mInLoad);
1794 }
1795
1796 // Helper method for getting the top window.
1797 @Override
1798 public WebView getCurrentTopWebView() {
1799 return mTabControl.getCurrentTopWebView();
1800 }
1801
1802 @Override
1803 public WebView getCurrentWebView() {
1804 return mTabControl.getCurrentWebView();
1805 }
1806
1807 /*
1808 * This method is called as a result of the user selecting the options
1809 * menu to see the download window. It shows the download window on top of
1810 * the current window.
1811 */
1812 void viewDownloads() {
1813 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1814 mActivity.startActivity(intent);
1815 }
1816
1817 // action mode
1818
1819 void onActionModeStarted(ActionMode mode) {
1820 mUi.onActionModeStarted(mode);
1821 mActionMode = mode;
1822 }
1823
1824 /*
1825 * True if a custom ActionMode (i.e. find or select) is in use.
1826 */
1827 @Override
1828 public boolean isInCustomActionMode() {
1829 return mActionMode != null;
1830 }
1831
1832 /*
1833 * End the current ActionMode.
1834 */
1835 @Override
1836 public void endActionMode() {
1837 if (mActionMode != null) {
1838 mActionMode.finish();
1839 }
1840 }
1841
1842 /*
1843 * Called by find and select when they are finished. Replace title bars
1844 * as necessary.
1845 */
1846 public void onActionModeFinished(ActionMode mode) {
1847 if (!isInCustomActionMode()) return;
1848 mUi.onActionModeFinished(mInLoad);
1849 mActionMode = null;
1850 }
1851
1852 boolean isInLoad() {
1853 return mInLoad;
1854 }
1855
1856 // bookmark handling
1857
1858 /**
1859 * add the current page as a bookmark to the given folder id
1860 * @param folderId use -1 for the default folder
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001861 * @param canBeAnEdit If true, check to see whether the site is already
1862 * bookmarked, and if it is, edit that bookmark. If false, and
1863 * the site is already bookmarked, do not attempt to edit the
1864 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001865 */
1866 @Override
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001867 public void bookmarkCurrentPage(long folderId, boolean canBeAnEdit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001868 Intent i = new Intent(mActivity,
1869 AddBookmarkPage.class);
1870 WebView w = getCurrentTopWebView();
1871 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1872 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1873 String touchIconUrl = w.getTouchIconUrl();
1874 if (touchIconUrl != null) {
1875 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1876 WebSettings settings = w.getSettings();
1877 if (settings != null) {
1878 i.putExtra(AddBookmarkPage.USER_AGENT,
1879 settings.getUserAgentString());
1880 }
1881 }
1882 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1883 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1884 getDesiredThumbnailHeight(mActivity)));
1885 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1886 i.putExtra(BrowserContract.Bookmarks.PARENT,
1887 folderId);
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001888 if (canBeAnEdit) {
1889 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1890 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001891 // Put the dialog at the upper right of the screen, covering the
1892 // star on the title bar.
1893 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1894 mActivity.startActivity(i);
1895 }
1896
1897 // file chooser
1898 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1899 mUploadHandler = new UploadHandler(this);
1900 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1901 }
1902
1903 // thumbnails
1904
1905 /**
1906 * Return the desired width for thumbnail screenshots, which are stored in
1907 * the database, and used on the bookmarks screen.
1908 * @param context Context for finding out the density of the screen.
1909 * @return desired width for thumbnail screenshot.
1910 */
1911 static int getDesiredThumbnailWidth(Context context) {
1912 return context.getResources().getDimensionPixelOffset(
1913 R.dimen.bookmarkThumbnailWidth);
1914 }
1915
1916 /**
1917 * Return the desired height for thumbnail screenshots, which are stored in
1918 * the database, and used on the bookmarks screen.
1919 * @param context Context for finding out the density of the screen.
1920 * @return desired height for thumbnail screenshot.
1921 */
1922 static int getDesiredThumbnailHeight(Context context) {
1923 return context.getResources().getDimensionPixelOffset(
1924 R.dimen.bookmarkThumbnailHeight);
1925 }
1926
1927 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001928 // We render to a bitmap 2x the desired size so that we can then
1929 // re-scale it with filtering since canvas.scale doesn't filter
1930 // This helps reduce aliasing at the cost of being slightly blurry
1931 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001932 Picture thumbnail = view.capturePicture();
1933 if (thumbnail == null) {
1934 return null;
1935 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001936 width *= filter_scale;
1937 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001938 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1939 Canvas canvas = new Canvas(bm);
1940 // May need to tweak these values to determine what is the
1941 // best scale factor
1942 int thumbnailWidth = thumbnail.getWidth();
1943 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001944 float scaleFactor = 1.0f;
Michael Kolb8233fac2010-10-26 16:08:53 -07001945 if (thumbnailWidth > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001946 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001947 } else {
1948 return null;
1949 }
John Reckfe49ab42010-11-16 17:09:37 -08001950
Michael Kolb8233fac2010-10-26 16:08:53 -07001951 if (view.getWidth() > view.getHeight() &&
1952 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
1953 // If the device is in landscape and the page is shorter
John Reckfe49ab42010-11-16 17:09:37 -08001954 // than the height of the view, center the thumnail and crop the sides
1955 scaleFactor = (float) height / (float)thumbnailHeight;
1956 float wx = (thumbnailWidth * scaleFactor) - width;
1957 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001958 }
1959
John Reckfe49ab42010-11-16 17:09:37 -08001960 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001961
1962 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001963 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
1964 height / filter_scale, true);
1965 bm.recycle();
1966 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001967 }
1968
John Reck34ef2672011-02-10 11:30:55 -08001969 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001970 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07001971 // FIXME: Would like to make sure there is actually something to
1972 // draw, but the API for that (WebViewCore.pictureReady()) is not
1973 // currently accessible here.
1974
John Reck34ef2672011-02-10 11:30:55 -08001975 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08001976 if (view == null) {
1977 // Tab was destroyed
1978 return;
1979 }
John Reck34ef2672011-02-10 11:30:55 -08001980 final String url = tab.getUrl();
1981 final String originalUrl = view.getOriginalUrl();
1982
1983 if (TextUtils.isEmpty(url)) {
1984 return;
1985 }
1986
1987 // Only update thumbnails for web urls (http(s)://), not for
1988 // about:, javascript:, data:, etc...
1989 // Unless it is a bookmarked site, then always update
1990 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
1991 return;
1992 }
1993
Michael Kolb8233fac2010-10-26 16:08:53 -07001994 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1995 getDesiredThumbnailHeight(mActivity));
1996 if (bm == null) {
1997 return;
1998 }
1999
2000 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002001 new AsyncTask<Void, Void, Void>() {
2002 @Override
2003 protected Void doInBackground(Void... unused) {
2004 Cursor cursor = null;
2005 try {
2006 // TODO: Clean this up
2007 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2008 if (cursor != null && cursor.moveToFirst()) {
2009 final ByteArrayOutputStream os =
2010 new ByteArrayOutputStream();
2011 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002012
John Reck34ef2672011-02-10 11:30:55 -08002013 ContentValues values = new ContentValues();
2014 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002015
John Reck34ef2672011-02-10 11:30:55 -08002016 do {
John Reck617fd832011-02-16 14:35:59 -08002017 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002018 cr.update(Images.CONTENT_URI, values, null, null);
2019 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002020 }
John Reck34ef2672011-02-10 11:30:55 -08002021 } catch (IllegalStateException e) {
2022 // Ignore
2023 } finally {
2024 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002025 }
John Reck34ef2672011-02-10 11:30:55 -08002026 return null;
2027 }
2028 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002029 }
2030
2031 private class Copy implements OnMenuItemClickListener {
2032 private CharSequence mText;
2033
2034 public boolean onMenuItemClick(MenuItem item) {
2035 copy(mText);
2036 return true;
2037 }
2038
2039 public Copy(CharSequence toCopy) {
2040 mText = toCopy;
2041 }
2042 }
2043
Leon Scroggins63c02662010-11-18 15:16:27 -05002044 private static class Download implements OnMenuItemClickListener {
2045 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002046 private String mText;
2047
2048 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002049 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
2050 null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07002051 return true;
2052 }
2053
Leon Scroggins63c02662010-11-18 15:16:27 -05002054 public Download(Activity activity, String toDownload) {
2055 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002056 mText = toDownload;
2057 }
2058 }
2059
Cary Clark8974d282010-11-22 10:46:05 -05002060 private static class SelectText implements OnMenuItemClickListener {
2061 private WebView mWebView;
2062
2063 public boolean onMenuItemClick(MenuItem item) {
2064 if (mWebView != null) {
2065 return mWebView.selectText();
2066 }
2067 return false;
2068 }
2069
2070 public SelectText(WebView webView) {
2071 mWebView = webView;
2072 }
2073
2074 }
2075
Michael Kolb8233fac2010-10-26 16:08:53 -07002076 /********************** TODO: UI stuff *****************************/
2077
2078 // these methods have been copied, they still need to be cleaned up
2079
2080 /****************** tabs ***************************************************/
2081
2082 // basic tab interactions:
2083
2084 // it is assumed that tabcontrol already knows about the tab
2085 protected void addTab(Tab tab) {
2086 mUi.addTab(tab);
2087 }
2088
2089 protected void removeTab(Tab tab) {
2090 mUi.removeTab(tab);
2091 mTabControl.removeTab(tab);
2092 }
2093
2094 protected void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002095 // monkey protection against delayed start
2096 if (tab != null) {
2097 mTabControl.setCurrentTab(tab);
2098 // the tab is guaranteed to have a webview after setCurrentTab
2099 mUi.setActiveTab(tab);
2100 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002101 }
2102
2103 protected void closeEmptyChildTab() {
2104 Tab current = mTabControl.getCurrentTab();
2105 if (current != null
2106 && current.getWebView().copyBackForwardList().getSize() == 0) {
2107 Tab parent = current.getParentTab();
2108 if (parent != null) {
2109 switchToTab(mTabControl.getTabIndex(parent));
2110 closeTab(current);
2111 }
2112 }
2113 }
2114
2115 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002116 // Dismiss the subwindow if applicable.
2117 dismissSubWindow(appTab);
2118 // Since we might kill the WebView, remove it from the
2119 // content view first.
2120 mUi.detachTab(appTab);
2121 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002122 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002123 // TODO: analyze why the remove and add are necessary
2124 mUi.attachTab(appTab);
2125 if (mTabControl.getCurrentTab() != appTab) {
2126 switchToTab(mTabControl.getTabIndex(appTab));
John Reck30c714c2010-12-16 17:30:34 -08002127 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002128 } else {
2129 // If the tab was the current tab, we have to attach
2130 // it to the view system again.
2131 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002132 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002133 }
2134 }
2135
2136 // Remove the sub window if it exists. Also called by TabControl when the
2137 // user clicks the 'X' to dismiss a sub window.
2138 public void dismissSubWindow(Tab tab) {
2139 removeSubWindow(tab);
2140 // dismiss the subwindow. This will destroy the WebView.
2141 tab.dismissSubWindow();
2142 getCurrentTopWebView().requestFocus();
2143 }
2144
2145 @Override
2146 public void removeSubWindow(Tab t) {
2147 if (t.getSubWebView() != null) {
2148 mUi.removeSubWindow(t.getSubViewContainer());
2149 }
2150 }
2151
2152 @Override
2153 public void attachSubWindow(Tab tab) {
2154 if (tab.getSubWebView() != null) {
2155 mUi.attachSubWindow(tab.getSubViewContainer());
2156 getCurrentTopWebView().requestFocus();
2157 }
2158 }
2159
Michael Kolb843510f2010-12-09 10:51:49 -08002160 @Override
2161 public Tab openTabToHomePage() {
2162 // check for max tabs
2163 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002164 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2165 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002166 } else {
2167 mUi.showMaxTabsWarning();
2168 return null;
2169 }
2170 }
2171
Michael Kolb18eb3772010-12-10 14:29:51 -08002172 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2173 if (mSettings.openInBackground() && !forceForeground) {
2174 Tab tab = mTabControl.createNewTab(false, null, null,
2175 (parent != null) && parent.isPrivateBrowsingEnabled());
2176 if (tab != null) {
2177 addTab(tab);
2178 WebView view = tab.getWebView();
2179 loadUrl(view, url);
2180 }
2181 return tab;
2182 } else {
2183 return openTabAndShow(parent, new UrlData(url), false, null);
2184 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002185 }
2186
Michael Kolb18eb3772010-12-10 14:29:51 -08002187
Michael Kolb8233fac2010-10-26 16:08:53 -07002188 // This method does a ton of stuff. It will attempt to create a new tab
2189 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2190 // url isn't null, it will load the given url.
Patrick Scottcd135082011-01-31 18:21:58 -05002191 public Tab openTabAndShow(Tab parent, final UrlData urlData,
2192 boolean closeOnExit, String appId) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002193 final Tab currentTab = mTabControl.getCurrentTab();
2194 if (mTabControl.canCreateNewTab()) {
2195 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Michael Kolb18eb3772010-12-10 14:29:51 -08002196 urlData.mUrl,
2197 (parent != null) && parent.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -07002198 WebView webview = tab.getWebView();
2199 // We must set the new tab as the current tab to reflect the old
2200 // animation behavior.
2201 addTab(tab);
2202 setActiveTab(tab);
Patrick Scottcd135082011-01-31 18:21:58 -05002203
2204 // Callback to load the url data.
2205 final Runnable load = new Runnable() {
2206 @Override public void run() {
2207 if (!urlData.isEmpty()) {
2208 loadUrlDataIn(tab, urlData);
2209 }
2210 }
2211 };
2212
2213 GoogleAccountLogin.startLoginIfNeeded(mActivity, mSettings, load);
Michael Kolb8233fac2010-10-26 16:08:53 -07002214 return tab;
2215 } else {
2216 // Get rid of the subwindow if it exists
2217 dismissSubWindow(currentTab);
2218 if (!urlData.isEmpty()) {
2219 // Load the given url.
2220 loadUrlDataIn(currentTab, urlData);
2221 }
2222 return currentTab;
2223 }
2224 }
2225
Michael Kolb8233fac2010-10-26 16:08:53 -07002226 @Override
2227 public Tab openIncognitoTab() {
2228 if (mTabControl.canCreateNewTab()) {
2229 Tab currentTab = mTabControl.getCurrentTab();
Michael Kolb8e7178d2011-01-26 19:13:36 -08002230 Tab tab = mTabControl.createNewTab(false, null,
John Reck4bfc0db2011-01-27 17:47:12 -08002231 null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07002232 addTab(tab);
2233 setActiveTab(tab);
John Reck4bfc0db2011-01-27 17:47:12 -08002234 loadUrlDataIn(tab, new UrlData("browser:incognito"));
Michael Kolb8233fac2010-10-26 16:08:53 -07002235 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002236 } else {
2237 mUi.showMaxTabsWarning();
2238 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002239 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002240 }
2241
2242 /**
2243 * @param index Index of the tab to change to, as defined by
2244 * mTabControl.getTabIndex(Tab t).
2245 * @return boolean True if we successfully switched to a different tab. If
2246 * the indexth tab is null, or if that tab is the same as
2247 * the current one, return false.
2248 */
2249 @Override
2250 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002251 // hide combo view if open
2252 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002253 Tab tab = mTabControl.getTab(index);
2254 Tab currentTab = mTabControl.getCurrentTab();
2255 if (tab == null || tab == currentTab) {
2256 return false;
2257 }
2258 setActiveTab(tab);
2259 return true;
2260 }
2261
2262 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002263 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002264 // hide combo view if open
2265 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002266 final Tab current = mTabControl.getCurrentTab();
2267 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002268 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002269 return;
2270 }
2271 final Tab parent = current.getParentTab();
2272 int indexToShow = -1;
2273 if (parent != null) {
2274 indexToShow = mTabControl.getTabIndex(parent);
2275 } else {
2276 final int currentIndex = mTabControl.getCurrentIndex();
2277 // Try to move to the tab to the right
2278 indexToShow = currentIndex + 1;
2279 if (indexToShow > mTabControl.getTabCount() - 1) {
2280 // Try to move to the tab to the left
2281 indexToShow = currentIndex - 1;
2282 }
2283 }
2284 if (switchToTab(indexToShow)) {
2285 // Close window
2286 closeTab(current);
2287 }
2288 }
2289
2290 /**
2291 * Close the tab, remove its associated title bar, and adjust mTabControl's
2292 * current tab to a valid value.
2293 */
2294 @Override
2295 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002296 // hide combo view if open
2297 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002298 int currentIndex = mTabControl.getCurrentIndex();
2299 int removeIndex = mTabControl.getTabIndex(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002300 Tab newtab = mTabControl.getTab(currentIndex);
2301 setActiveTab(newtab);
Michael Kolb2d59c322011-01-25 13:18:55 -08002302 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002303 }
2304
2305 /**************** TODO: Url loading clean up *******************************/
2306
2307 // Called when loading from context menu or LOAD_URL message
2308 protected void loadUrlFromContext(WebView view, String url) {
2309 // In case the user enters nothing.
2310 if (url != null && url.length() != 0 && view != null) {
2311 url = UrlUtils.smartUrlFilter(url);
2312 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2313 loadUrl(view, url);
2314 }
2315 }
2316 }
2317
2318 /**
2319 * Load the URL into the given WebView and update the title bar
2320 * to reflect the new load. Call this instead of WebView.loadUrl
2321 * directly.
2322 * @param view The WebView used to load url.
2323 * @param url The URL to load.
2324 */
2325 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002326 view.loadUrl(url);
2327 }
2328
2329 /**
2330 * Load UrlData into a Tab and update the title bar to reflect the new
2331 * load. Call this instead of UrlData.loadIn directly.
2332 * @param t The Tab used to load.
2333 * @param data The UrlData being loaded.
2334 */
2335 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002336 data.loadIn(t);
2337 }
2338
John Reck30c714c2010-12-16 17:30:34 -08002339 @Override
2340 public void onUserCanceledSsl(Tab tab) {
2341 WebView web = tab.getWebView();
2342 // TODO: Figure out the "right" behavior
2343 if (web.canGoBack()) {
2344 web.goBack();
2345 } else {
2346 web.loadUrl(mSettings.getHomePage());
2347 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002348 }
2349
2350 void goBackOnePageOrQuit() {
2351 Tab current = mTabControl.getCurrentTab();
2352 if (current == null) {
2353 /*
2354 * Instead of finishing the activity, simply push this to the back
2355 * of the stack and let ActivityManager to choose the foreground
2356 * activity. As BrowserActivity is singleTask, it will be always the
2357 * root of the task. So we can use either true or false for
2358 * moveTaskToBack().
2359 */
2360 mActivity.moveTaskToBack(true);
2361 return;
2362 }
2363 WebView w = current.getWebView();
2364 if (w.canGoBack()) {
2365 w.goBack();
2366 } else {
2367 // Check to see if we are closing a window that was created by
2368 // another window. If so, we switch back to that window.
2369 Tab parent = current.getParentTab();
2370 if (parent != null) {
2371 switchToTab(mTabControl.getTabIndex(parent));
2372 // Now we close the other tab
2373 closeTab(current);
2374 } else {
2375 if (current.closeOnExit()) {
Patrick Scottfc1518a2011-02-28 13:57:03 -05002376 // This will finish the activity if there is only one tab
2377 // open or it will switch to the next available tab if
2378 // available.
Michael Kolb96683f72011-02-15 14:24:35 -08002379 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002380 }
2381 /*
2382 * Instead of finishing the activity, simply push this to the back
2383 * of the stack and let ActivityManager to choose the foreground
2384 * activity. As BrowserActivity is singleTask, it will be always the
2385 * root of the task. So we can use either true or false for
2386 * moveTaskToBack().
2387 */
2388 mActivity.moveTaskToBack(true);
2389 }
2390 }
2391 }
2392
2393 /**
2394 * Feed the previously stored results strings to the BrowserProvider so that
2395 * the SearchDialog will show them instead of the standard searches.
2396 * @param result String to show on the editable line of the SearchDialog.
2397 */
2398 @Override
2399 public void showVoiceSearchResults(String result) {
2400 ContentProviderClient client = mActivity.getContentResolver()
2401 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2402 ContentProvider prov = client.getLocalContentProvider();
2403 BrowserProvider bp = (BrowserProvider) prov;
2404 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2405 client.release();
2406
2407 Bundle bundle = createGoogleSearchSourceBundle(
2408 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2409 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2410 startSearch(result, false, bundle, false);
2411 }
2412
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002413 @Override
2414 public void startSearch(String url) {
2415 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
2416 null, false);
2417 }
2418
Michael Kolb8233fac2010-10-26 16:08:53 -07002419 private void startSearch(String initialQuery, boolean selectInitialQuery,
2420 Bundle appSearchData, boolean globalSearch) {
2421 if (appSearchData == null) {
2422 appSearchData = createGoogleSearchSourceBundle(
2423 GOOGLE_SEARCH_SOURCE_TYPE);
2424 }
2425
2426 SearchEngine searchEngine = mSettings.getSearchEngine();
2427 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2428 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2429 }
2430 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2431 globalSearch);
2432 }
2433
2434 private Bundle createGoogleSearchSourceBundle(String source) {
2435 Bundle bundle = new Bundle();
2436 bundle.putString(Search.SOURCE, source);
2437 return bundle;
2438 }
2439
2440 /**
2441 * handle key events in browser
2442 *
2443 * @param keyCode
2444 * @param event
2445 * @return true if handled, false to pass to super
2446 */
2447 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002448 boolean noModifiers = event.hasNoModifiers();
2449
Michael Kolb8233fac2010-10-26 16:08:53 -07002450 // Even if MENU is already held down, we need to call to super to open
2451 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002452 if (!noModifiers
2453 && ((KeyEvent.KEYCODE_MENU == keyCode)
2454 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2455 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002456 mMenuIsDown = true;
2457 return false;
2458 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002459
Cary Clark8ff8c662010-12-29 15:03:05 -05002460 WebView webView = getCurrentTopWebView();
2461 if (webView == null) return false;
2462
Cary Clark160bbb92011-01-10 11:17:07 -05002463 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2464 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002465
Michael Kolb8233fac2010-10-26 16:08:53 -07002466 switch(keyCode) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002467 case KeyEvent.KEYCODE_ESCAPE:
Cary Clark160bbb92011-01-10 11:17:07 -05002468 if (!noModifiers) break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002469 stopLoading();
2470 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07002471 case KeyEvent.KEYCODE_SPACE:
2472 // WebView/WebTextView handle the keys in the KeyDown. As
2473 // the Activity's shortcut keys are only handled when WebView
2474 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002475 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002476 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002477 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002478 pageDown();
2479 }
2480 return true;
2481 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002482 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002483 event.startTracking();
2484 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002485 case KeyEvent.KEYCODE_DPAD_LEFT:
2486 if (ctrl) {
2487 webView.goBack();
2488 return true;
2489 }
2490 break;
2491 case KeyEvent.KEYCODE_DPAD_RIGHT:
2492 if (ctrl) {
2493 webView.goForward();
2494 return true;
2495 }
2496 break;
2497 case KeyEvent.KEYCODE_A:
2498 if (ctrl) {
2499 webView.selectAll();
2500 return true;
2501 }
2502 break;
Michael Kolba4183062011-01-16 10:43:21 -08002503// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002504 case KeyEvent.KEYCODE_C:
2505 if (ctrl) {
2506 webView.copySelection();
2507 return true;
2508 }
2509 break;
Michael Kolba4183062011-01-16 10:43:21 -08002510// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002511// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002512// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002513// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002514// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002515// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002516// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002517// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002518// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002519// case KeyEvent.KEYCODE_M: // unused
2520// case KeyEvent.KEYCODE_N: // in Chrome: new window
2521// case KeyEvent.KEYCODE_O: // in Chrome: open file
2522// case KeyEvent.KEYCODE_P: // in Chrome: print page
2523// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002524// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002525// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2526 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002527 // we can't use the ctrl/shift flags, they check for
2528 // exclusive use of a modifier
2529 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002530 if (event.isShiftPressed()) {
2531 openIncognitoTab();
2532 } else {
2533 openTabToHomePage();
2534 }
2535 return true;
2536 }
2537 break;
2538// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2539// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolba4183062011-01-16 10:43:21 -08002540// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002541// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2542// case KeyEvent.KEYCODE_Y: // unused
2543// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002544 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002545 // it is a regular key and webview is not null
2546 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002547 }
2548
John Recke6bf4ab2011-02-24 15:48:05 -08002549 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2550 switch(keyCode) {
2551 case KeyEvent.KEYCODE_BACK:
2552 if (mUi.showsWeb()) {
2553 bookmarksOrHistoryPicker(true);
2554 return true;
2555 }
2556 break;
2557 }
2558 return false;
2559 }
2560
Michael Kolb8233fac2010-10-26 16:08:53 -07002561 boolean onKeyUp(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002562 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002563 switch(keyCode) {
2564 case KeyEvent.KEYCODE_MENU:
2565 mMenuIsDown = false;
2566 break;
2567 case KeyEvent.KEYCODE_BACK:
2568 if (event.isTracking() && !event.isCanceled()) {
2569 onBackKey();
2570 return true;
2571 }
2572 break;
2573 }
2574 return false;
2575 }
2576
2577 public boolean isMenuDown() {
2578 return mMenuIsDown;
2579 }
2580
Ben Murdoch8029a772010-11-16 11:58:21 +00002581 public void setupAutoFill(Message message) {
2582 // Open the settings activity at the AutoFill profile fragment so that
2583 // the user can create a new profile. When they return, we will dispatch
2584 // the message so that we can autofill the form using their new profile.
2585 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2586 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2587 AutoFillSettingsFragment.class.getName());
2588 mAutoFillSetupMessage = message;
2589 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2590 }
John Reckb3417f02011-01-14 11:01:05 -08002591
2592 @Override
2593 public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
2594 mOptionsMenuHandler = handler;
2595 }
2596
2597 @Override
2598 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
2599 if (mOptionsMenuHandler == handler) {
2600 mOptionsMenuHandler = null;
2601 }
2602 }
2603
Narayan Kamath5119edd2011-02-23 15:49:17 +00002604 @Override
2605 public void registerDropdownChangeListener(DropdownChangeListener d) {
2606 mUi.registerDropdownChangeListener(d);
2607 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002608}