blob: 4f67e40c379315bc1165af4257724505cd8ea6e3 [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;
20import com.android.browser.search.SearchEngine;
21import com.android.common.Search;
22
23import android.app.Activity;
24import android.app.DownloadManager;
25import android.app.SearchManager;
26import android.content.ClipboardManager;
27import android.content.ContentProvider;
28import android.content.ContentProviderClient;
29import android.content.ContentResolver;
30import android.content.ContentValues;
31import android.content.Context;
32import android.content.Intent;
33import android.content.pm.PackageManager;
34import android.content.pm.ResolveInfo;
35import android.content.res.Configuration;
Leon Scroggins1961ed22010-12-07 15:22:21 -050036import android.database.ContentObserver;
Michael Kolb8233fac2010-10-26 16:08:53 -070037import android.database.Cursor;
38import android.database.sqlite.SQLiteDatabase;
Michael Kolb8233fac2010-10-26 16:08:53 -070039import android.graphics.Bitmap;
40import android.graphics.Canvas;
41import android.graphics.Picture;
42import android.net.Uri;
43import android.net.http.SslError;
44import android.os.AsyncTask;
45import android.os.Bundle;
Leon Scrogginsac993842011-02-02 12:54:07 -050046import android.os.Environment;
Michael Kolb8233fac2010-10-26 16:08:53 -070047import android.os.Handler;
48import android.os.Message;
49import android.os.PowerManager;
50import android.os.PowerManager.WakeLock;
Ben Murdoch8029a772010-11-16 11:58:21 +000051import android.preference.PreferenceActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -070052import android.provider.Browser;
53import android.provider.BrowserContract;
Michael Kolb8233fac2010-10-26 16:08:53 -070054import android.provider.BrowserContract.Images;
55import android.provider.ContactsContract;
56import android.provider.ContactsContract.Intents.Insert;
Michael Kolbcfa3af52010-12-14 10:36:11 -080057import android.speech.RecognizerIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070058import android.speech.RecognizerResultsIntent;
59import android.text.TextUtils;
60import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080061import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070062import android.view.ActionMode;
63import android.view.ContextMenu;
64import android.view.ContextMenu.ContextMenuInfo;
65import android.view.Gravity;
66import android.view.KeyEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070067import android.view.Menu;
68import android.view.MenuInflater;
69import android.view.MenuItem;
70import android.view.MenuItem.OnMenuItemClickListener;
71import android.view.View;
72import android.webkit.CookieManager;
73import android.webkit.CookieSyncManager;
74import android.webkit.HttpAuthHandler;
75import android.webkit.SslErrorHandler;
76import android.webkit.ValueCallback;
77import android.webkit.WebChromeClient;
78import android.webkit.WebIconDatabase;
79import android.webkit.WebSettings;
80import android.webkit.WebView;
Leon Scrogginsac993842011-02-02 12:54:07 -050081import android.widget.Toast;
Michael Kolb8233fac2010-10-26 16:08:53 -070082
83import java.io.ByteArrayOutputStream;
84import java.io.File;
85import java.net.URLEncoder;
86import java.util.Calendar;
87import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -080088import java.util.List;
Michael Kolb8233fac2010-10-26 16:08:53 -070089
90/**
91 * Controller for browser
92 */
93public class Controller
94 implements WebViewController, UiController {
95
96 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -080097 private static final String SEND_APP_ID_EXTRA =
98 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
99
Michael Kolb8233fac2010-10-26 16:08:53 -0700100
101 // public message ids
102 public final static int LOAD_URL = 1001;
103 public final static int STOP_LOAD = 1002;
104
105 // Message Ids
106 private static final int FOCUS_NODE_HREF = 102;
107 private static final int RELEASE_WAKELOCK = 107;
108
109 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
110
111 private static final int OPEN_BOOKMARKS = 201;
112
113 private static final int EMPTY_MENU = -1;
114
Michael Kolb8233fac2010-10-26 16:08:53 -0700115 // activity requestCode
116 final static int PREFERENCES_PAGE = 3;
117 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000118 final static int AUTOFILL_SETUP = 5;
119
Michael Kolb8233fac2010-10-26 16:08:53 -0700120 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
121
122 // As the ids are dynamically created, we can't guarantee that they will
123 // be in sequence, so this static array maps ids to a window number.
124 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
125 { R.id.window_one_menu_id, R.id.window_two_menu_id,
126 R.id.window_three_menu_id, R.id.window_four_menu_id,
127 R.id.window_five_menu_id, R.id.window_six_menu_id,
128 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
129
130 // "source" parameter for Google search through search key
131 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
132 // "source" parameter for Google search through simplily type
133 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
134
135 private Activity mActivity;
136 private UI mUi;
137 private TabControl mTabControl;
138 private BrowserSettings mSettings;
139 private WebViewFactory mFactory;
John Reckb3417f02011-01-14 11:01:05 -0800140 private OptionsMenuHandler mOptionsMenuHandler = null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700141
142 private WakeLock mWakeLock;
143
144 private UrlHandler mUrlHandler;
145 private UploadHandler mUploadHandler;
146 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700147 private PageDialogsHandler mPageDialogsHandler;
148 private NetworkStateHandler mNetworkHandler;
149
Ben Murdoch8029a772010-11-16 11:58:21 +0000150 private Message mAutoFillSetupMessage;
151
Michael Kolb8233fac2010-10-26 16:08:53 -0700152 private boolean mShouldShowErrorConsole;
153
154 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
155
156 // FIXME, temp address onPrepareMenu performance problem.
157 // When we move everything out of view, we should rewrite this.
158 private int mCurrentMenuState = 0;
159 private int mMenuState = R.id.MAIN_MENU;
160 private int mOldMenuState = EMPTY_MENU;
161 private Menu mCachedMenu;
162
163 // Used to prevent chording to result in firing two shortcuts immediately
164 // one after another. Fixes bug 1211714.
165 boolean mCanChord;
166 private boolean mMenuIsDown;
167
168 // For select and find, we keep track of the ActionMode so that
169 // finish() can be called as desired.
170 private ActionMode mActionMode;
171
172 /**
173 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
174 * of whether the configuration has changed. The first onMenuOpened call
175 * after a configuration change is simply a reopening of the same menu
176 * (i.e. mIconView did not change).
177 */
178 private boolean mConfigChanged;
179
180 /**
181 * Keeps track of whether the options menu is open. This is important in
182 * determining whether to show or hide the title bar overlay
183 */
184 private boolean mOptionsMenuOpen;
185
186 /**
187 * Whether or not the options menu is in its bigger, popup menu form. When
188 * true, we want the title bar overlay to be gone. When false, we do not.
189 * Only meaningful if mOptionsMenuOpen is true.
190 */
191 private boolean mExtendedMenuOpen;
192
193 private boolean mInLoad;
194
195 private boolean mActivityPaused = true;
196 private boolean mLoadStopped;
197
198 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500199 // Checks to see when the bookmarks database has changed, and updates the
200 // Tabs' notion of whether they represent bookmarked sites.
201 private ContentObserver mBookmarksObserver;
John Reck0ebd3ac2010-12-09 11:14:04 -0800202 private DataController mDataController;
Michael Kolb8233fac2010-10-26 16:08:53 -0700203
204 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
205 @Override
206 public Void doInBackground(File... files) {
207 if (files != null) {
208 for (File f : files) {
209 if (!f.delete()) {
210 Log.e(LOGTAG, f.getPath() + " was not deleted");
211 }
212 }
213 }
214 return null;
215 }
216 }
217
218 public Controller(Activity browser) {
219 mActivity = browser;
220 mSettings = BrowserSettings.getInstance();
John Reck0ebd3ac2010-12-09 11:14:04 -0800221 mDataController = DataController.getInstance(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700222 mTabControl = new TabControl(this);
223 mSettings.setController(this);
224
225 mUrlHandler = new UrlHandler(this);
226 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700227 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
228
229 PowerManager pm = (PowerManager) mActivity
230 .getSystemService(Context.POWER_SERVICE);
231 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
232
233 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500234 mBookmarksObserver = new ContentObserver(mHandler) {
235 @Override
236 public void onChange(boolean selfChange) {
237 int size = mTabControl.getTabCount();
238 for (int i = 0; i < size; i++) {
239 mTabControl.getTab(i).updateBookmarkedStatus();
240 }
241 }
242
243 };
244 browser.getContentResolver().registerContentObserver(
245 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700246
247 mNetworkHandler = new NetworkStateHandler(mActivity, this);
248 // Start watching the default geolocation permissions
249 mSystemAllowGeolocationOrigins =
250 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
251 mSystemAllowGeolocationOrigins.start();
252
253 retainIconsOnStartup();
254 }
255
Patrick Scott7d50a932011-02-04 09:27:26 -0500256 void start(final Bundle icicle, final Intent intent) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700257 // Unless the last browser usage was within 24 hours, destroy any
258 // remaining incognito tabs.
259
260 Calendar lastActiveDate = icicle != null ?
261 (Calendar) icicle.getSerializable("lastActiveDate") : null;
262 Calendar today = Calendar.getInstance();
263 Calendar yesterday = Calendar.getInstance();
264 yesterday.add(Calendar.DATE, -1);
265
Patrick Scott7d50a932011-02-04 09:27:26 -0500266 final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700267 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800268 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700269
Patrick Scott7d50a932011-02-04 09:27:26 -0500270 // Find out if we will restore any state and remember the tab.
271 final int currentTab =
272 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000273
Patrick Scott7d50a932011-02-04 09:27:26 -0500274 if (currentTab == -1) {
275 // Not able to restore so we go ahead and clear session cookies. We
276 // must do this before trying to login the user as we don't want to
277 // clear any session cookies set during login.
278 CookieManager.getInstance().removeSessionCookie();
279 }
280
281 GoogleAccountLogin.startLoginIfNeeded(mActivity, mSettings,
282 new Runnable() {
283 @Override public void run() {
284 start(icicle, intent, currentTab, restoreIncognitoTabs);
285 }
286 });
287 }
288
289 private void start(Bundle icicle, Intent intent, int currentTab,
290 boolean restoreIncognitoTabs) {
291 if (currentTab == -1) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700292 final Bundle extra = intent.getExtras();
293 // Create an initial tab.
294 // If the intent is ACTION_VIEW and data is not null, the Browser is
295 // invoked to view the content by another application. In this case,
296 // the tab will be close when exit.
297 UrlData urlData = mIntentHandler.getUrlDataFromIntent(intent);
298
299 String action = intent.getAction();
300 final Tab t = mTabControl.createNewTab(
301 (Intent.ACTION_VIEW.equals(action) &&
302 intent.getData() != null)
303 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
304 .equals(action),
305 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
306 urlData.mUrl, false);
307 addTab(t);
308 setActiveTab(t);
309 WebView webView = t.getWebView();
310 if (extra != null) {
311 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
312 if (scale > 0 && scale <= 1000) {
313 webView.setInitialScale(scale);
314 }
315 }
316
317 if (urlData.isEmpty()) {
318 loadUrl(webView, mSettings.getHomePage());
319 } else {
320 loadUrlDataIn(t, urlData);
321 }
322 } else {
Patrick Scott7d50a932011-02-04 09:27:26 -0500323 mTabControl.restoreState(icicle, currentTab, restoreIncognitoTabs,
324 mUi.needsRestoreAllTabs());
Michael Kolb1bf23132010-11-19 12:55:12 -0800325 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700326 // TabControl.restoreState() will create a new tab even if
327 // restoring the state fails.
328 setActiveTab(mTabControl.getCurrentTab());
329 }
330 // clear up the thumbnail directory, which is no longer used;
331 // ideally this should only be run once after an upgrade from
332 // a previous version of the browser
333 new ClearThumbnails().execute(mTabControl.getThumbnailDir()
334 .listFiles());
335 // Read JavaScript flags if it exists.
336 String jsFlags = getSettings().getJsFlags();
337 if (jsFlags.trim().length() != 0) {
338 getCurrentWebView().setJsFlags(jsFlags);
339 }
John Reck439c9a52010-12-14 10:04:39 -0800340 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
341 bookmarksOrHistoryPicker(false);
342 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700343 }
344
345 void setWebViewFactory(WebViewFactory factory) {
346 mFactory = factory;
347 }
348
Michael Kolb1514bb72010-11-22 09:11:48 -0800349 @Override
350 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700351 return mFactory;
352 }
353
354 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800355 public void onSetWebView(Tab tab, WebView view) {
356 mUi.onSetWebView(tab, view);
357 }
358
359 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800360 public void createSubWindow(Tab tab) {
361 endActionMode();
362 WebView mainView = tab.getWebView();
363 WebView subView = mFactory.createWebView((mainView == null)
364 ? false
365 : mainView.isPrivateBrowsingEnabled());
366 mUi.createSubWindow(tab, subView);
367 }
368
369 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700370 public Activity getActivity() {
371 return mActivity;
372 }
373
374 void setUi(UI ui) {
375 mUi = ui;
376 }
377
378 BrowserSettings getSettings() {
379 return mSettings;
380 }
381
382 IntentHandler getIntentHandler() {
383 return mIntentHandler;
384 }
385
386 @Override
387 public UI getUi() {
388 return mUi;
389 }
390
391 int getMaxTabs() {
392 return mActivity.getResources().getInteger(R.integer.max_tabs);
393 }
394
395 @Override
396 public TabControl getTabControl() {
397 return mTabControl;
398 }
399
Michael Kolb1bf23132010-11-19 12:55:12 -0800400 @Override
401 public List<Tab> getTabs() {
402 return mTabControl.getTabs();
403 }
404
Michael Kolb8233fac2010-10-26 16:08:53 -0700405 // Open the icon database and retain all the icons for visited sites.
Ben Murdoch9446b932010-11-25 16:20:14 +0000406 // This is done on a background thread so as not to stall startup.
Michael Kolb8233fac2010-10-26 16:08:53 -0700407 private void retainIconsOnStartup() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000408 // WebIconDatabase needs to be retrieved on the UI thread so that if
409 // it has not been created successfully yet the Handler is started on the
410 // UI thread.
411 new RetainIconsOnStartupTask(WebIconDatabase.getInstance()).execute();
412 }
413
414 private class RetainIconsOnStartupTask extends AsyncTask<Void, Void, Void> {
415 private WebIconDatabase mDb;
416
417 public RetainIconsOnStartupTask(WebIconDatabase db) {
418 mDb = db;
419 }
420
John Recka00cbbd2010-12-16 12:38:19 -0800421 @Override
Ben Murdoch9446b932010-11-25 16:20:14 +0000422 protected Void doInBackground(Void... unused) {
423 mDb.open(mActivity.getDir("icons", 0).getPath());
424 Cursor c = null;
425 try {
426 c = Browser.getAllBookmarks(mActivity.getContentResolver());
427 if (c.moveToFirst()) {
428 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
429 do {
430 String url = c.getString(urlIndex);
431 mDb.retainIconForPageUrl(url);
432 } while (c.moveToNext());
433 }
434 } catch (IllegalStateException e) {
435 Log.e(LOGTAG, "retainIconsOnStartup", e);
436 } finally {
437 if (c != null) c.close();
Michael Kolb8233fac2010-10-26 16:08:53 -0700438 }
Ben Murdoch9446b932010-11-25 16:20:14 +0000439
440 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700441 }
442 }
443
444 private void startHandler() {
445 mHandler = new Handler() {
446
447 @Override
448 public void handleMessage(Message msg) {
449 switch (msg.what) {
450 case OPEN_BOOKMARKS:
451 bookmarksOrHistoryPicker(false);
452 break;
453 case FOCUS_NODE_HREF:
454 {
455 String url = (String) msg.getData().get("url");
456 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500457 String src = (String) msg.getData().get("src");
458 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700459 if (TextUtils.isEmpty(url)) {
460 break;
461 }
462 HashMap focusNodeMap = (HashMap) msg.obj;
463 WebView view = (WebView) focusNodeMap.get("webview");
464 // Only apply the action if the top window did not change.
465 if (getCurrentTopWebView() != view) {
466 break;
467 }
468 switch (msg.arg1) {
469 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -0700470 loadUrlFromContext(getCurrentTopWebView(), url);
471 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500472 case R.id.view_image_context_menu_id:
473 loadUrlFromContext(getCurrentTopWebView(), src);
474 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500475 case R.id.open_newtab_context_menu_id:
476 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -0800477 final Tab newTab = openTab(parent, url, false);
Leon Scroggins026f2542010-11-22 13:26:12 -0500478 if (newTab != null && newTab != parent) {
479 parent.addChildTab(newTab);
480 }
481 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700482 case R.id.copy_link_context_menu_id:
483 copy(url);
484 break;
485 case R.id.save_link_context_menu_id:
486 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500487 DownloadHandler.onDownloadStartNoStream(
488 mActivity, url, null, null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -0700489 break;
490 }
491 break;
492 }
493
494 case LOAD_URL:
495 loadUrlFromContext(getCurrentTopWebView(), (String) msg.obj);
496 break;
497
498 case STOP_LOAD:
499 stopLoading();
500 break;
501
502 case RELEASE_WAKELOCK:
503 if (mWakeLock.isHeld()) {
504 mWakeLock.release();
505 // if we reach here, Browser should be still in the
506 // background loading after WAKELOCK_TIMEOUT (5-min).
507 // To avoid burning the battery, stop loading.
508 mTabControl.stopAllLoading();
509 }
510 break;
511
512 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800513 Tab tab = (Tab) msg.obj;
514 if (tab != null) {
515 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700516 }
517 break;
518 }
519 }
520 };
521
522 }
523
Michael Kolbba99c5d2010-11-29 14:57:41 -0800524 @Override
525 public void shareCurrentPage() {
526 shareCurrentPage(mTabControl.getCurrentTab());
527 }
528
529 private void shareCurrentPage(Tab tab) {
530 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800531 sharePage(mActivity, tab.getTitle(),
532 tab.getUrl(), tab.getFavicon(),
533 createScreenshot(tab.getWebView(),
534 getDesiredThumbnailWidth(mActivity),
535 getDesiredThumbnailHeight(mActivity)));
536 }
537 }
538
Michael Kolb8233fac2010-10-26 16:08:53 -0700539 /**
540 * Share a page, providing the title, url, favicon, and a screenshot. Uses
541 * an {@link Intent} to launch the Activity chooser.
542 * @param c Context used to launch a new Activity.
543 * @param title Title of the page. Stored in the Intent with
544 * {@link Intent#EXTRA_SUBJECT}
545 * @param url URL of the page. Stored in the Intent with
546 * {@link Intent#EXTRA_TEXT}
547 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
548 * with {@link Browser#EXTRA_SHARE_FAVICON}
549 * @param screenshot Bitmap of a screenshot of the page. Stored in the
550 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
551 */
552 static final void sharePage(Context c, String title, String url,
553 Bitmap favicon, Bitmap screenshot) {
554 Intent send = new Intent(Intent.ACTION_SEND);
555 send.setType("text/plain");
556 send.putExtra(Intent.EXTRA_TEXT, url);
557 send.putExtra(Intent.EXTRA_SUBJECT, title);
558 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
559 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
560 try {
561 c.startActivity(Intent.createChooser(send, c.getString(
562 R.string.choosertitle_sharevia)));
563 } catch(android.content.ActivityNotFoundException ex) {
564 // if no app handles it, do nothing
565 }
566 }
567
568 private void copy(CharSequence text) {
569 ClipboardManager cm = (ClipboardManager) mActivity
570 .getSystemService(Context.CLIPBOARD_SERVICE);
571 cm.setText(text);
572 }
573
574 // lifecycle
575
576 protected void onConfgurationChanged(Configuration config) {
577 mConfigChanged = true;
578 if (mPageDialogsHandler != null) {
579 mPageDialogsHandler.onConfigurationChanged(config);
580 }
581 mUi.onConfigurationChanged(config);
582 }
583
584 @Override
585 public void handleNewIntent(Intent intent) {
586 mIntentHandler.onNewIntent(intent);
587 }
588
589 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800590 if (mUi.isCustomViewShowing()) {
591 hideCustomView();
592 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700593 if (mActivityPaused) {
594 Log.e(LOGTAG, "BrowserActivity is already paused.");
595 return;
596 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700597 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800598 Tab tab = mTabControl.getCurrentTab();
599 if (tab != null) {
600 tab.pause();
601 if (!pauseWebViewTimers(tab)) {
602 mWakeLock.acquire();
603 mHandler.sendMessageDelayed(mHandler
604 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
605 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700606 }
607 mUi.onPause();
608 mNetworkHandler.onPause();
609
610 WebView.disablePlatformNotifications();
611 }
612
613 void onSaveInstanceState(Bundle outState) {
614 // the default implementation requires each view to have an id. As the
615 // browser handles the state itself and it doesn't use id for the views,
616 // don't call the default implementation. Otherwise it will trigger the
617 // warning like this, "couldn't save which view has focus because the
618 // focused view XXX has no id".
619
620 // Save all the tabs
621 mTabControl.saveState(outState);
622 // Save time so that we know how old incognito tabs (if any) are.
623 outState.putSerializable("lastActiveDate", Calendar.getInstance());
624 }
625
626 void onResume() {
627 if (!mActivityPaused) {
628 Log.e(LOGTAG, "BrowserActivity is already resumed.");
629 return;
630 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700631 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800632 Tab current = mTabControl.getCurrentTab();
633 if (current != null) {
634 current.resume();
635 resumeWebViewTimers(current);
636 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700637 if (mWakeLock.isHeld()) {
638 mHandler.removeMessages(RELEASE_WAKELOCK);
639 mWakeLock.release();
640 }
641 mUi.onResume();
642 mNetworkHandler.onResume();
643 WebView.enablePlatformNotifications();
644 }
645
Michael Kolb70976932010-11-30 11:34:01 -0800646 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800647 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800648 * @param tab guaranteed non-null
649 */
650 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700651 boolean inLoad = tab.inPageLoad();
652 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
653 CookieSyncManager.getInstance().startSync();
654 WebView w = tab.getWebView();
655 if (w != null) {
656 w.resumeTimers();
657 }
658 }
659 }
660
Michael Kolb70976932010-11-30 11:34:01 -0800661 /**
662 * Pause all WebView timers using the WebView of the given tab
663 * @param tab
664 * @return true if the timers are paused or tab is null
665 */
666 private boolean pauseWebViewTimers(Tab tab) {
667 if (tab == null) {
668 return true;
669 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700670 CookieSyncManager.getInstance().stopSync();
671 WebView w = getCurrentWebView();
672 if (w != null) {
673 w.pauseTimers();
674 }
675 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700676 }
Michael Kolb70976932010-11-30 11:34:01 -0800677 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700678 }
679
680 void onDestroy() {
Ben Murdoch51f6a2f2011-02-21 12:27:07 +0000681 if (!mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700682 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
683 mUploadHandler = null;
684 }
685 if (mTabControl == null) return;
686 mUi.onDestroy();
687 // Remove the current tab and sub window
688 Tab t = mTabControl.getCurrentTab();
689 if (t != null) {
690 dismissSubWindow(t);
691 removeTab(t);
692 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500693 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700694 // Destroy all the tabs
695 mTabControl.destroy();
696 WebIconDatabase.getInstance().close();
697 // Stop watching the default geolocation permissions
698 mSystemAllowGeolocationOrigins.stop();
699 mSystemAllowGeolocationOrigins = null;
700 }
701
702 protected boolean isActivityPaused() {
703 return mActivityPaused;
704 }
705
706 protected void onLowMemory() {
707 mTabControl.freeMemory();
708 }
709
710 @Override
711 public boolean shouldShowErrorConsole() {
712 return mShouldShowErrorConsole;
713 }
714
715 protected void setShouldShowErrorConsole(boolean show) {
716 if (show == mShouldShowErrorConsole) {
717 // Nothing to do.
718 return;
719 }
720 mShouldShowErrorConsole = show;
721 Tab t = mTabControl.getCurrentTab();
722 if (t == null) {
723 // There is no current tab so we cannot toggle the error console
724 return;
725 }
726 mUi.setShouldShowErrorConsole(t, show);
727 }
728
729 @Override
730 public void stopLoading() {
731 mLoadStopped = true;
732 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700733 WebView w = getCurrentTopWebView();
734 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700735 mUi.onPageStopped(tab);
736 }
737
738 boolean didUserStopLoading() {
739 return mLoadStopped;
740 }
741
742 // WebViewController
743
744 @Override
John Reck324d4402011-01-11 16:56:42 -0800745 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700746
747 // We've started to load a new page. If there was a pending message
748 // to save a screenshot then we will now take the new page and save
749 // an incorrect screenshot. Therefore, remove any pending thumbnail
750 // messages from the queue.
751 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800752 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700753
754 // reset sync timer to avoid sync starts during loading a page
755 CookieSyncManager.getInstance().resetSync();
756
757 if (!mNetworkHandler.isNetworkUp()) {
758 view.setNetworkAvailable(false);
759 }
760
761 // when BrowserActivity just starts, onPageStarted may be called before
762 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
763 // to start the timer. As we won't switch tabs while an activity is in
764 // pause state, we can ensure calling resume and pause in pair.
765 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800766 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700767 }
768 mLoadStopped = false;
769 if (!mNetworkHandler.isNetworkUp()) {
770 mNetworkHandler.createAndShowNetworkDialog();
771 }
772 endActionMode();
773
John Reck30c714c2010-12-16 17:30:34 -0800774 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700775
John Reck324d4402011-01-11 16:56:42 -0800776 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700777 // update the bookmark database for favicon
778 maybeUpdateFavicon(tab, null, url, favicon);
779
780 Performance.tracePageStart(url);
781
782 // Performance probe
783 if (false) {
784 Performance.onPageStarted();
785 }
786
787 }
788
789 @Override
John Reck324d4402011-01-11 16:56:42 -0800790 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800791 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800792 if (!tab.isPrivateBrowsingEnabled()
793 && !TextUtils.isEmpty(tab.getUrl())) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700794 if (tab.inForeground() && !didUserStopLoading()
795 || !tab.inForeground()) {
796 // Only update the bookmark screenshot if the user did not
797 // cancel the load early.
798 mHandler.sendMessageDelayed(mHandler.obtainMessage(
John Reck34ef2672011-02-10 11:30:55 -0800799 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
Michael Kolb8233fac2010-10-26 16:08:53 -0700800 500);
801 }
802 }
803 // pause the WebView timer and release the wake lock if it is finished
804 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800805 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700806 if (mWakeLock.isHeld()) {
807 mHandler.removeMessages(RELEASE_WAKELOCK);
808 mWakeLock.release();
809 }
810 }
811 // Performance probe
812 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800813 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700814 }
815
816 Performance.tracePageFinished();
817 }
818
819 @Override
John Reck30c714c2010-12-16 17:30:34 -0800820 public void onProgressChanged(Tab tab) {
821 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700822
823 if (newProgress == 100) {
824 CookieSyncManager.getInstance().sync();
825 // onProgressChanged() may continue to be called after the main
826 // frame has finished loading, as any remaining sub frames continue
827 // to load. We'll only get called once though with newProgress as
828 // 100 when everything is loaded. (onPageFinished is called once
829 // when the main frame completes loading regardless of the state of
830 // any sub frames so calls to onProgressChanges may continue after
831 // onPageFinished has executed)
832 if (mInLoad) {
833 mInLoad = false;
834 updateInLoadMenuItems(mCachedMenu);
835 }
836 } else {
837 if (!mInLoad) {
838 // onPageFinished may have already been called but a subframe is
839 // still loading and updating the progress. Reset mInLoad and
840 // update the menu items.
841 mInLoad = true;
842 updateInLoadMenuItems(mCachedMenu);
843 }
844 }
John Reck30c714c2010-12-16 17:30:34 -0800845 mUi.onProgressChanged(tab);
846 }
847
848 @Override
849 public void onUpdatedLockIcon(Tab tab) {
850 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700851 }
852
853 @Override
854 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800855 mUi.onTabDataChanged(tab);
856 final String pageUrl = tab.getUrl();
John Reck324d4402011-01-11 16:56:42 -0800857 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700858 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
859 return;
860 }
861 // Update the title in the history database if not in private browsing mode
862 if (!tab.isPrivateBrowsingEnabled()) {
John Reck0ebd3ac2010-12-09 11:14:04 -0800863 mDataController.updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700864 }
865 }
866
867 @Override
868 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800869 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700870 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
871 }
872
873 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800874 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
875 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700876 }
877
878 @Override
879 public boolean shouldOverrideKeyEvent(KeyEvent event) {
880 if (mMenuIsDown) {
881 // only check shortcut key when MENU is held
882 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
883 event);
884 } else {
885 return false;
886 }
887 }
888
889 @Override
890 public void onUnhandledKeyEvent(KeyEvent event) {
891 if (!isActivityPaused()) {
892 if (event.getAction() == KeyEvent.ACTION_DOWN) {
893 mActivity.onKeyDown(event.getKeyCode(), event);
894 } else {
895 mActivity.onKeyUp(event.getKeyCode(), event);
896 }
897 }
898 }
899
900 @Override
John Reck324d4402011-01-11 16:56:42 -0800901 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700902 // Don't save anything in private browsing mode
903 if (tab.isPrivateBrowsingEnabled()) return;
John Reck324d4402011-01-11 16:56:42 -0800904 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700905
John Reck324d4402011-01-11 16:56:42 -0800906 if (TextUtils.isEmpty(url)
907 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700908 return;
909 }
John Reck0ebd3ac2010-12-09 11:14:04 -0800910 mDataController.updateVisitedHistory(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700911 WebIconDatabase.getInstance().retainIconForPageUrl(url);
912 }
913
914 @Override
915 public void getVisitedHistory(final ValueCallback<String[]> callback) {
916 AsyncTask<Void, Void, String[]> task =
917 new AsyncTask<Void, Void, String[]>() {
918 @Override
919 public String[] doInBackground(Void... unused) {
920 return Browser.getVisitedHistory(mActivity.getContentResolver());
921 }
922 @Override
923 public void onPostExecute(String[] result) {
924 callback.onReceiveValue(result);
925 }
926 };
927 task.execute();
928 }
929
930 @Override
931 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
932 final HttpAuthHandler handler, final String host,
933 final String realm) {
934 String username = null;
935 String password = null;
936
937 boolean reuseHttpAuthUsernamePassword
938 = handler.useHttpAuthUsernamePassword();
939
940 if (reuseHttpAuthUsernamePassword && view != null) {
941 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
942 if (credentials != null && credentials.length == 2) {
943 username = credentials[0];
944 password = credentials[1];
945 }
946 }
947
948 if (username != null && password != null) {
949 handler.proceed(username, password);
950 } else {
951 if (tab.inForeground()) {
952 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
953 } else {
954 handler.cancel();
955 }
956 }
957 }
958
959 @Override
960 public void onDownloadStart(Tab tab, String url, String userAgent,
961 String contentDisposition, String mimetype, long contentLength) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500962 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
963 contentDisposition, mimetype);
Michael Kolb8233fac2010-10-26 16:08:53 -0700964 if (tab.getWebView().copyBackForwardList().getSize() == 0) {
965 // This Tab was opened for the sole purpose of downloading a
966 // file. Remove it.
967 if (tab == mTabControl.getCurrentTab()) {
968 // In this case, the Tab is still on top.
969 goBackOnePageOrQuit();
970 } else {
971 // In this case, it is not.
972 closeTab(tab);
973 }
974 }
975 }
976
977 @Override
978 public Bitmap getDefaultVideoPoster() {
979 return mUi.getDefaultVideoPoster();
980 }
981
982 @Override
983 public View getVideoLoadingProgressView() {
984 return mUi.getVideoLoadingProgressView();
985 }
986
987 @Override
988 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
989 SslError error) {
990 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
991 }
992
993 // helper method
994
995 /*
996 * Update the favorites icon if the private browsing isn't enabled and the
997 * icon is valid.
998 */
999 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1000 final String url, Bitmap favicon) {
1001 if (favicon == null) {
1002 return;
1003 }
1004 if (!tab.isPrivateBrowsingEnabled()) {
1005 Bookmarks.updateFavicon(mActivity
1006 .getContentResolver(), originalUrl, url, favicon);
1007 }
1008 }
1009
Leon Scroggins4cd97792010-12-03 15:31:56 -05001010 @Override
1011 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001012 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001013 mUi.bookmarkedStatusHasChanged(tab);
1014 }
1015
Michael Kolb8233fac2010-10-26 16:08:53 -07001016 // end WebViewController
1017
1018 protected void pageUp() {
1019 getCurrentTopWebView().pageUp(false);
1020 }
1021
1022 protected void pageDown() {
1023 getCurrentTopWebView().pageDown(false);
1024 }
1025
1026 // callback from phone title bar
1027 public void editUrl() {
1028 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001029 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001030 }
1031
Michael Kolbcfa3af52010-12-14 10:36:11 -08001032 public void startVoiceSearch() {
1033 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1034 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1035 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1036 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1037 mActivity.getComponentName().flattenToString());
1038 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001039 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001040 mActivity.startActivity(intent);
1041 }
1042
Michael Kolb8233fac2010-10-26 16:08:53 -07001043 public void activateVoiceSearchMode(String title) {
1044 mUi.showVoiceTitleBar(title);
1045 }
1046
1047 public void revertVoiceSearchMode(Tab tab) {
1048 mUi.revertVoiceTitleBar(tab);
1049 }
1050
1051 public void showCustomView(Tab tab, View view,
1052 WebChromeClient.CustomViewCallback callback) {
1053 if (tab.inForeground()) {
1054 if (mUi.isCustomViewShowing()) {
1055 callback.onCustomViewHidden();
1056 return;
1057 }
1058 mUi.showCustomView(view, callback);
1059 // Save the menu state and set it to empty while the custom
1060 // view is showing.
1061 mOldMenuState = mMenuState;
1062 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001063 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001064 }
1065 }
1066
1067 @Override
1068 public void hideCustomView() {
1069 if (mUi.isCustomViewShowing()) {
1070 mUi.onHideCustomView();
1071 // Reset the old menu state.
1072 mMenuState = mOldMenuState;
1073 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001074 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001075 }
1076 }
1077
1078 protected void onActivityResult(int requestCode, int resultCode,
1079 Intent intent) {
1080 if (getCurrentTopWebView() == null) return;
1081 switch (requestCode) {
1082 case PREFERENCES_PAGE:
1083 if (resultCode == Activity.RESULT_OK && intent != null) {
1084 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
1085 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
1086 mTabControl.removeParentChildRelationShips();
1087 }
1088 }
1089 break;
1090 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001091 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001092 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001093 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001094 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001095 case AUTOFILL_SETUP:
1096 // Determine whether a profile was actually set up or not
1097 // and if so, send the message back to the WebTextView to
1098 // fill the form with the new profile.
1099 if (getSettings().getAutoFillProfile() != null) {
1100 mAutoFillSetupMessage.sendToTarget();
1101 mAutoFillSetupMessage = null;
1102 }
1103 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001104 default:
1105 break;
1106 }
1107 getCurrentTopWebView().requestFocus();
1108 }
1109
1110 /**
1111 * Open the Go page.
1112 * @param startWithHistory If true, open starting on the history tab.
1113 * Otherwise, start with the bookmarks tab.
1114 */
1115 @Override
1116 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1117 if (mTabControl.getCurrentWebView() == null) {
1118 return;
1119 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001120 // clear action mode
1121 if (isInCustomActionMode()) {
1122 endActionMode();
1123 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001124 Bundle extras = new Bundle();
1125 // Disable opening in a new window if we have maxed out the windows
1126 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1127 !mTabControl.canCreateNewTab());
1128 mUi.showComboView(startWithHistory, extras);
1129 }
1130
1131 // combo view callbacks
1132
1133 /**
1134 * callback from ComboPage when clear history is requested
1135 */
1136 public void onRemoveParentChildRelationships() {
1137 mTabControl.removeParentChildRelationShips();
1138 }
1139
1140 /**
1141 * callback from ComboPage when bookmark/history selection
1142 */
1143 @Override
1144 public void onUrlSelected(String url, boolean newTab) {
1145 removeComboView();
1146 if (!TextUtils.isEmpty(url)) {
1147 if (newTab) {
Michael Kolb18eb3772010-12-10 14:29:51 -08001148 openTab(mTabControl.getCurrentTab(), url, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001149 } else {
1150 final Tab currentTab = mTabControl.getCurrentTab();
1151 dismissSubWindow(currentTab);
1152 loadUrl(getCurrentTopWebView(), url);
1153 }
1154 }
1155 }
1156
1157 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07001158 * dismiss the ComboPage
1159 */
1160 @Override
1161 public void removeComboView() {
1162 mUi.hideComboView();
1163 }
1164
1165 // active tabs page handling
1166
1167 protected void showActiveTabsPage() {
1168 mMenuState = EMPTY_MENU;
1169 mUi.showActiveTabsPage();
1170 }
1171
1172 /**
1173 * Remove the active tabs page.
1174 * @param needToAttach If true, the active tabs page did not attach a tab
1175 * to the content view, so we need to do that here.
1176 */
1177 @Override
1178 public void removeActiveTabsPage(boolean needToAttach) {
1179 mMenuState = R.id.MAIN_MENU;
1180 mUi.removeActiveTabsPage();
1181 if (needToAttach) {
1182 setActiveTab(mTabControl.getCurrentTab());
1183 }
1184 getCurrentTopWebView().requestFocus();
1185 }
1186
1187 // key handling
1188 protected void onBackKey() {
1189 if (!mUi.onBackKey()) {
1190 WebView subwindow = mTabControl.getCurrentSubWindow();
1191 if (subwindow != null) {
1192 if (subwindow.canGoBack()) {
1193 subwindow.goBack();
1194 } else {
1195 dismissSubWindow(mTabControl.getCurrentTab());
1196 }
1197 } else {
1198 goBackOnePageOrQuit();
1199 }
1200 }
1201 }
1202
1203 // menu handling and state
1204 // TODO: maybe put into separate handler
1205
1206 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckb3417f02011-01-14 11:01:05 -08001207 if (mOptionsMenuHandler != null) {
1208 return mOptionsMenuHandler.onCreateOptionsMenu(menu);
1209 }
1210
John Reckd73c5a22010-12-22 10:22:50 -08001211 if (mMenuState == EMPTY_MENU) {
1212 return false;
1213 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001214 MenuInflater inflater = mActivity.getMenuInflater();
1215 inflater.inflate(R.menu.browser, menu);
1216 updateInLoadMenuItems(menu);
1217 // hold on to the menu reference here; it is used by the page callbacks
1218 // to update the menu based on loading state
1219 mCachedMenu = menu;
1220 return true;
1221 }
1222
1223 protected void onCreateContextMenu(ContextMenu menu, View v,
1224 ContextMenuInfo menuInfo) {
1225 if (v instanceof TitleBarBase) {
1226 return;
1227 }
1228 if (!(v instanceof WebView)) {
1229 return;
1230 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001231 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001232 WebView.HitTestResult result = webview.getHitTestResult();
1233 if (result == null) {
1234 return;
1235 }
1236
1237 int type = result.getType();
1238 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1239 Log.w(LOGTAG,
1240 "We should not show context menu when nothing is touched");
1241 return;
1242 }
1243 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1244 // let TextView handles context menu
1245 return;
1246 }
1247
1248 // Note, http://b/issue?id=1106666 is requesting that
1249 // an inflated menu can be used again. This is not available
1250 // yet, so inflate each time (yuk!)
1251 MenuInflater inflater = mActivity.getMenuInflater();
1252 inflater.inflate(R.menu.browsercontext, menu);
1253
1254 // Show the correct menu group
1255 final String extra = result.getExtra();
1256 menu.setGroupVisible(R.id.PHONE_MENU,
1257 type == WebView.HitTestResult.PHONE_TYPE);
1258 menu.setGroupVisible(R.id.EMAIL_MENU,
1259 type == WebView.HitTestResult.EMAIL_TYPE);
1260 menu.setGroupVisible(R.id.GEO_MENU,
1261 type == WebView.HitTestResult.GEO_TYPE);
1262 menu.setGroupVisible(R.id.IMAGE_MENU,
1263 type == WebView.HitTestResult.IMAGE_TYPE
1264 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1265 menu.setGroupVisible(R.id.ANCHOR_MENU,
1266 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1267 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001268 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1269 || type == WebView.HitTestResult.PHONE_TYPE
1270 || type == WebView.HitTestResult.EMAIL_TYPE
1271 || type == WebView.HitTestResult.GEO_TYPE;
1272 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1273 if (hitText) {
1274 menu.findItem(R.id.select_text_menu_id)
1275 .setOnMenuItemClickListener(new SelectText(webview));
1276 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001277 // Setup custom handling depending on the type
1278 switch (type) {
1279 case WebView.HitTestResult.PHONE_TYPE:
1280 menu.setHeaderTitle(Uri.decode(extra));
1281 menu.findItem(R.id.dial_context_menu_id).setIntent(
1282 new Intent(Intent.ACTION_VIEW, Uri
1283 .parse(WebView.SCHEME_TEL + extra)));
1284 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1285 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1286 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1287 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1288 addIntent);
1289 menu.findItem(R.id.copy_phone_context_menu_id)
1290 .setOnMenuItemClickListener(
1291 new Copy(extra));
1292 break;
1293
1294 case WebView.HitTestResult.EMAIL_TYPE:
1295 menu.setHeaderTitle(extra);
1296 menu.findItem(R.id.email_context_menu_id).setIntent(
1297 new Intent(Intent.ACTION_VIEW, Uri
1298 .parse(WebView.SCHEME_MAILTO + extra)));
1299 menu.findItem(R.id.copy_mail_context_menu_id)
1300 .setOnMenuItemClickListener(
1301 new Copy(extra));
1302 break;
1303
1304 case WebView.HitTestResult.GEO_TYPE:
1305 menu.setHeaderTitle(extra);
1306 menu.findItem(R.id.map_context_menu_id).setIntent(
1307 new Intent(Intent.ACTION_VIEW, Uri
1308 .parse(WebView.SCHEME_GEO
1309 + URLEncoder.encode(extra))));
1310 menu.findItem(R.id.copy_geo_context_menu_id)
1311 .setOnMenuItemClickListener(
1312 new Copy(extra));
1313 break;
1314
1315 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1316 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001317 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001318 // decide whether to show the open link in new tab option
1319 boolean showNewTab = mTabControl.canCreateNewTab();
1320 MenuItem newTabItem
1321 = menu.findItem(R.id.open_newtab_context_menu_id);
Michael Kolb2dd65c82011-01-14 11:07:38 -08001322 newTabItem.setTitle(
1323 BrowserSettings.getInstance().openInBackground()
1324 ? R.string.contextmenu_openlink_newwindow_background
1325 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001326 newTabItem.setVisible(showNewTab);
1327 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001328 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1329 newTabItem.setOnMenuItemClickListener(
1330 new MenuItem.OnMenuItemClickListener() {
1331 @Override
1332 public boolean onMenuItemClick(MenuItem item) {
1333 final HashMap<String, WebView> hrefMap =
1334 new HashMap<String, WebView>();
1335 hrefMap.put("webview", webview);
1336 final Message msg = mHandler.obtainMessage(
1337 FOCUS_NODE_HREF,
1338 R.id.open_newtab_context_menu_id,
1339 0, hrefMap);
1340 webview.requestFocusNodeHref(msg);
1341 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001342 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001343 });
1344 } else {
1345 newTabItem.setOnMenuItemClickListener(
1346 new MenuItem.OnMenuItemClickListener() {
1347 @Override
1348 public boolean onMenuItemClick(MenuItem item) {
1349 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -08001350 final Tab newTab = openTab(parent,
1351 extra, false);
Leon Scroggins026f2542010-11-22 13:26:12 -05001352 if (newTab != parent) {
1353 parent.addChildTab(newTab);
1354 }
1355 return true;
1356 }
1357 });
1358 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001359 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001360 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1361 break;
1362 }
1363 // otherwise fall through to handle image part
1364 case WebView.HitTestResult.IMAGE_TYPE:
1365 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1366 menu.setHeaderTitle(extra);
1367 }
1368 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1369 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1370 menu.findItem(R.id.download_context_menu_id).
Leon Scroggins63c02662010-11-18 15:16:27 -05001371 setOnMenuItemClickListener(new Download(mActivity, extra));
John Reck3527dd12011-02-22 10:35:29 -08001372 menu.findItem(R.id.set_wallpaper_context_menu_id).
1373 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1374 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001375 break;
1376
1377 default:
1378 Log.w(LOGTAG, "We should not get here.");
1379 break;
1380 }
1381 //update the ui
1382 mUi.onContextMenuCreated(menu);
1383 }
1384
1385 /**
1386 * As the menu can be open when loading state changes
1387 * we must manually update the state of the stop/reload menu
1388 * item
1389 */
1390 private void updateInLoadMenuItems(Menu menu) {
1391 if (menu == null) {
1392 return;
1393 }
1394 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1395 MenuItem src = mInLoad ?
1396 menu.findItem(R.id.stop_menu_id):
1397 menu.findItem(R.id.reload_menu_id);
1398 if (src != null) {
1399 dest.setIcon(src.getIcon());
1400 dest.setTitle(src.getTitle());
1401 }
1402 }
1403
John Reckb3417f02011-01-14 11:01:05 -08001404 boolean onPrepareOptionsMenu(Menu menu) {
1405 if (mOptionsMenuHandler != null) {
1406 return mOptionsMenuHandler.onPrepareOptionsMenu(menu);
1407 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001408 // This happens when the user begins to hold down the menu key, so
1409 // allow them to chord to get a shortcut.
1410 mCanChord = true;
1411 // Note: setVisible will decide whether an item is visible; while
1412 // setEnabled() will decide whether an item is enabled, which also means
1413 // whether the matching shortcut key will function.
1414 switch (mMenuState) {
1415 case EMPTY_MENU:
1416 if (mCurrentMenuState != mMenuState) {
1417 menu.setGroupVisible(R.id.MAIN_MENU, false);
1418 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1419 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1420 }
1421 break;
1422 default:
1423 if (mCurrentMenuState != mMenuState) {
1424 menu.setGroupVisible(R.id.MAIN_MENU, true);
1425 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1426 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1427 }
1428 final WebView w = getCurrentTopWebView();
1429 boolean canGoBack = false;
1430 boolean canGoForward = false;
1431 boolean isHome = false;
1432 if (w != null) {
1433 canGoBack = w.canGoBack();
1434 canGoForward = w.canGoForward();
1435 isHome = mSettings.getHomePage().equals(w.getUrl());
1436 }
1437 final MenuItem back = menu.findItem(R.id.back_menu_id);
1438 back.setEnabled(canGoBack);
1439
1440 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1441 home.setEnabled(!isHome);
1442
1443 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1444 forward.setEnabled(canGoForward);
1445
1446 // decide whether to show the share link option
1447 PackageManager pm = mActivity.getPackageManager();
1448 Intent send = new Intent(Intent.ACTION_SEND);
1449 send.setType("text/plain");
1450 ResolveInfo ri = pm.resolveActivity(send,
1451 PackageManager.MATCH_DEFAULT_ONLY);
1452 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1453
1454 boolean isNavDump = mSettings.isNavDump();
1455 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1456 nav.setVisible(isNavDump);
1457 nav.setEnabled(isNavDump);
1458
1459 boolean showDebugSettings = mSettings.showDebugSettings();
1460 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1461 counter.setVisible(showDebugSettings);
1462 counter.setEnabled(showDebugSettings);
1463
John Reckb3417f02011-01-14 11:01:05 -08001464 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1465 newtab.setEnabled(getTabControl().canCreateNewTab());
Michael Kolb8233fac2010-10-26 16:08:53 -07001466
Leon Scroggins81983762011-02-11 15:17:36 -05001467 MenuItem archive = menu.findItem(R.id.save_webarchive_menu_id);
Cary Clarkba860522011-02-16 11:22:42 -05001468 String url = w != null ? w.getUrl() : null;
1469 archive.setVisible(url != null && !url.endsWith(".webarchivexml"));
Michael Kolb8233fac2010-10-26 16:08:53 -07001470 break;
1471 }
1472 mCurrentMenuState = mMenuState;
1473 return true;
1474 }
1475
1476 public boolean onOptionsItemSelected(MenuItem item) {
John Reckb3417f02011-01-14 11:01:05 -08001477 if (mOptionsMenuHandler != null &&
1478 mOptionsMenuHandler.onOptionsItemSelected(item)) {
1479 return true;
1480 }
1481
Michael Kolb8233fac2010-10-26 16:08:53 -07001482 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1483 // menu remains active, so ensure comboview is dismissed
1484 // if main menu option is selected
1485 removeComboView();
1486 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001487 if (!mCanChord) {
1488 // The user has already fired a shortcut with this hold down of the
1489 // menu key.
1490 return false;
1491 }
1492 if (null == getCurrentTopWebView()) {
1493 return false;
1494 }
1495 if (mMenuIsDown) {
1496 // The shortcut action consumes the MENU. Even if it is still down,
1497 // it won't trigger the next shortcut action. In the case of the
1498 // shortcut action triggering a new activity, like Bookmarks, we
1499 // won't get onKeyUp for MENU. So it is important to reset it here.
1500 mMenuIsDown = false;
1501 }
1502 switch (item.getItemId()) {
1503 // -- Main menu
1504 case R.id.new_tab_menu_id:
1505 openTabToHomePage();
1506 break;
1507
1508 case R.id.incognito_menu_id:
1509 openIncognitoTab();
1510 break;
1511
1512 case R.id.goto_menu_id:
1513 editUrl();
1514 break;
1515
1516 case R.id.bookmarks_menu_id:
1517 bookmarksOrHistoryPicker(false);
1518 break;
1519
1520 case R.id.active_tabs_menu_id:
1521 showActiveTabsPage();
1522 break;
1523
1524 case R.id.add_bookmark_menu_id:
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001525 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001526 break;
1527
1528 case R.id.stop_reload_menu_id:
1529 if (mInLoad) {
1530 stopLoading();
1531 } else {
1532 getCurrentTopWebView().reload();
1533 }
1534 break;
1535
1536 case R.id.back_menu_id:
1537 getCurrentTopWebView().goBack();
1538 break;
1539
1540 case R.id.forward_menu_id:
1541 getCurrentTopWebView().goForward();
1542 break;
1543
1544 case R.id.close_menu_id:
1545 // Close the subwindow if it exists.
1546 if (mTabControl.getCurrentSubWindow() != null) {
1547 dismissSubWindow(mTabControl.getCurrentTab());
1548 break;
1549 }
1550 closeCurrentTab();
1551 break;
1552
1553 case R.id.homepage_menu_id:
1554 Tab current = mTabControl.getCurrentTab();
1555 if (current != null) {
1556 dismissSubWindow(current);
1557 loadUrl(current.getWebView(), mSettings.getHomePage());
1558 }
1559 break;
1560
1561 case R.id.preferences_menu_id:
1562 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1563 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1564 getCurrentTopWebView().getUrl());
1565 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1566 break;
1567
1568 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001569 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001570 break;
1571
Leon Scrogginsac993842011-02-02 12:54:07 -05001572 case R.id.save_webarchive_menu_id:
1573 String state = Environment.getExternalStorageState();
1574 if (!Environment.MEDIA_MOUNTED.equals(state)) {
1575 Log.e(LOGTAG, "External storage not mounted");
1576 Toast.makeText(mActivity, R.string.webarchive_failed,
1577 Toast.LENGTH_SHORT).show();
1578 break;
1579 }
1580 final String directory = Environment.getExternalStoragePublicDirectory(
1581 Environment.DIRECTORY_DOWNLOADS) + File.separator;
1582 File dir = new File(directory);
1583 if (!dir.exists() && !dir.mkdirs()) {
1584 Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
1585 Toast.makeText(mActivity, R.string.webarchive_failed,
1586 Toast.LENGTH_SHORT).show();
1587 break;
1588 }
1589 WebView topWebView = getCurrentTopWebView();
1590 final String title = topWebView.getTitle();
1591 topWebView.saveWebArchive(directory, true,
1592 new ValueCallback<String>() {
1593 @Override
1594 public void onReceiveValue(final String value) {
1595 if (value != null) {
1596 File file = new File(value);
1597 final long length = file.length();
1598 if (file.exists() && length > 0) {
Leon Scroggins1cb96552011-02-11 14:22:57 -05001599 Toast.makeText(mActivity, R.string.webarchive_saved,
1600 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001601 final DownloadManager manager = (DownloadManager) mActivity
1602 .getSystemService(Context.DOWNLOAD_SERVICE);
1603 new Thread("Add WebArchive to download manager") {
1604 @Override
1605 public void run() {
1606 manager.completedDownload(null == title ? value : title,
1607 value, true, "application/x-webarchive-xml",
1608 value, length, true);
1609 }
1610 }.start();
1611 return;
1612 }
1613 }
1614 Toast.makeText(mActivity,
1615 R.string.webarchive_failed, Toast.LENGTH_SHORT).show();
1616 }
1617 });
1618 break;
1619
Michael Kolb8233fac2010-10-26 16:08:53 -07001620 case R.id.page_info_menu_id:
1621 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1622 false);
1623 break;
1624
1625 case R.id.classic_history_menu_id:
1626 bookmarksOrHistoryPicker(true);
1627 break;
1628
1629 case R.id.title_bar_share_page_url:
1630 case R.id.share_page_menu_id:
1631 Tab currentTab = mTabControl.getCurrentTab();
1632 if (null == currentTab) {
1633 mCanChord = false;
1634 return false;
1635 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001636 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001637 break;
1638
1639 case R.id.dump_nav_menu_id:
1640 getCurrentTopWebView().debugDump();
1641 break;
1642
1643 case R.id.dump_counters_menu_id:
1644 getCurrentTopWebView().dumpV8Counters();
1645 break;
1646
1647 case R.id.zoom_in_menu_id:
1648 getCurrentTopWebView().zoomIn();
1649 break;
1650
1651 case R.id.zoom_out_menu_id:
1652 getCurrentTopWebView().zoomOut();
1653 break;
1654
1655 case R.id.view_downloads_menu_id:
1656 viewDownloads();
1657 break;
1658
1659 case R.id.window_one_menu_id:
1660 case R.id.window_two_menu_id:
1661 case R.id.window_three_menu_id:
1662 case R.id.window_four_menu_id:
1663 case R.id.window_five_menu_id:
1664 case R.id.window_six_menu_id:
1665 case R.id.window_seven_menu_id:
1666 case R.id.window_eight_menu_id:
1667 {
1668 int menuid = item.getItemId();
1669 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1670 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1671 Tab desiredTab = mTabControl.getTab(id);
1672 if (desiredTab != null &&
1673 desiredTab != mTabControl.getCurrentTab()) {
1674 switchToTab(id);
1675 }
1676 break;
1677 }
1678 }
1679 }
1680 break;
1681
1682 default:
1683 return false;
1684 }
1685 mCanChord = false;
1686 return true;
1687 }
1688
1689 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001690 // Let the History and Bookmark fragments handle menus they created.
1691 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1692 return false;
1693 }
1694
Michael Kolb8233fac2010-10-26 16:08:53 -07001695 // chording is not an issue with context menus, but we use the same
1696 // options selector, so set mCanChord to true so we can access them.
1697 mCanChord = true;
1698 int id = item.getItemId();
1699 boolean result = true;
1700 switch (id) {
1701 // For the context menu from the title bar
1702 case R.id.title_bar_copy_page_url:
1703 Tab currentTab = mTabControl.getCurrentTab();
1704 if (null == currentTab) {
1705 result = false;
1706 break;
1707 }
1708 WebView mainView = currentTab.getWebView();
1709 if (null == mainView) {
1710 result = false;
1711 break;
1712 }
1713 copy(mainView.getUrl());
1714 break;
1715 // -- Browser context menu
1716 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001717 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001718 case R.id.copy_link_context_menu_id:
1719 final WebView webView = getCurrentTopWebView();
1720 if (null == webView) {
1721 result = false;
1722 break;
1723 }
1724 final HashMap<String, WebView> hrefMap =
1725 new HashMap<String, WebView>();
1726 hrefMap.put("webview", webView);
1727 final Message msg = mHandler.obtainMessage(
1728 FOCUS_NODE_HREF, id, 0, hrefMap);
1729 webView.requestFocusNodeHref(msg);
1730 break;
1731
1732 default:
1733 // For other context menus
1734 result = onOptionsItemSelected(item);
1735 }
1736 mCanChord = false;
1737 return result;
1738 }
1739
1740 /**
1741 * support programmatically opening the context menu
1742 */
1743 public void openContextMenu(View view) {
1744 mActivity.openContextMenu(view);
1745 }
1746
1747 /**
1748 * programmatically open the options menu
1749 */
1750 public void openOptionsMenu() {
1751 mActivity.openOptionsMenu();
1752 }
1753
1754 public boolean onMenuOpened(int featureId, Menu menu) {
1755 if (mOptionsMenuOpen) {
1756 if (mConfigChanged) {
1757 // We do not need to make any changes to the state of the
1758 // title bar, since the only thing that happened was a
1759 // change in orientation
1760 mConfigChanged = false;
1761 } else {
1762 if (!mExtendedMenuOpen) {
1763 mExtendedMenuOpen = true;
1764 mUi.onExtendedMenuOpened();
1765 } else {
1766 // Switching the menu back to icon view, so show the
1767 // title bar once again.
1768 mExtendedMenuOpen = false;
1769 mUi.onExtendedMenuClosed(mInLoad);
1770 mUi.onOptionsMenuOpened();
1771 }
1772 }
1773 } else {
1774 // The options menu is closed, so open it, and show the title
1775 mOptionsMenuOpen = true;
1776 mConfigChanged = false;
1777 mExtendedMenuOpen = false;
1778 mUi.onOptionsMenuOpened();
1779 }
1780 return true;
1781 }
1782
1783 public void onOptionsMenuClosed(Menu menu) {
1784 mOptionsMenuOpen = false;
1785 mUi.onOptionsMenuClosed(mInLoad);
1786 }
1787
1788 public void onContextMenuClosed(Menu menu) {
1789 mUi.onContextMenuClosed(menu, mInLoad);
1790 }
1791
1792 // Helper method for getting the top window.
1793 @Override
1794 public WebView getCurrentTopWebView() {
1795 return mTabControl.getCurrentTopWebView();
1796 }
1797
1798 @Override
1799 public WebView getCurrentWebView() {
1800 return mTabControl.getCurrentWebView();
1801 }
1802
1803 /*
1804 * This method is called as a result of the user selecting the options
1805 * menu to see the download window. It shows the download window on top of
1806 * the current window.
1807 */
1808 void viewDownloads() {
1809 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1810 mActivity.startActivity(intent);
1811 }
1812
1813 // action mode
1814
1815 void onActionModeStarted(ActionMode mode) {
1816 mUi.onActionModeStarted(mode);
1817 mActionMode = mode;
1818 }
1819
1820 /*
1821 * True if a custom ActionMode (i.e. find or select) is in use.
1822 */
1823 @Override
1824 public boolean isInCustomActionMode() {
1825 return mActionMode != null;
1826 }
1827
1828 /*
1829 * End the current ActionMode.
1830 */
1831 @Override
1832 public void endActionMode() {
1833 if (mActionMode != null) {
1834 mActionMode.finish();
1835 }
1836 }
1837
1838 /*
1839 * Called by find and select when they are finished. Replace title bars
1840 * as necessary.
1841 */
1842 public void onActionModeFinished(ActionMode mode) {
1843 if (!isInCustomActionMode()) return;
1844 mUi.onActionModeFinished(mInLoad);
1845 mActionMode = null;
1846 }
1847
1848 boolean isInLoad() {
1849 return mInLoad;
1850 }
1851
1852 // bookmark handling
1853
1854 /**
1855 * add the current page as a bookmark to the given folder id
1856 * @param folderId use -1 for the default folder
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001857 * @param canBeAnEdit If true, check to see whether the site is already
1858 * bookmarked, and if it is, edit that bookmark. If false, and
1859 * the site is already bookmarked, do not attempt to edit the
1860 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001861 */
1862 @Override
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001863 public void bookmarkCurrentPage(long folderId, boolean canBeAnEdit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001864 Intent i = new Intent(mActivity,
1865 AddBookmarkPage.class);
1866 WebView w = getCurrentTopWebView();
1867 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1868 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1869 String touchIconUrl = w.getTouchIconUrl();
1870 if (touchIconUrl != null) {
1871 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1872 WebSettings settings = w.getSettings();
1873 if (settings != null) {
1874 i.putExtra(AddBookmarkPage.USER_AGENT,
1875 settings.getUserAgentString());
1876 }
1877 }
1878 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1879 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1880 getDesiredThumbnailHeight(mActivity)));
1881 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1882 i.putExtra(BrowserContract.Bookmarks.PARENT,
1883 folderId);
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001884 if (canBeAnEdit) {
1885 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1886 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001887 // Put the dialog at the upper right of the screen, covering the
1888 // star on the title bar.
1889 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1890 mActivity.startActivity(i);
1891 }
1892
1893 // file chooser
1894 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1895 mUploadHandler = new UploadHandler(this);
1896 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1897 }
1898
1899 // thumbnails
1900
1901 /**
1902 * Return the desired width for thumbnail screenshots, which are stored in
1903 * the database, and used on the bookmarks screen.
1904 * @param context Context for finding out the density of the screen.
1905 * @return desired width for thumbnail screenshot.
1906 */
1907 static int getDesiredThumbnailWidth(Context context) {
1908 return context.getResources().getDimensionPixelOffset(
1909 R.dimen.bookmarkThumbnailWidth);
1910 }
1911
1912 /**
1913 * Return the desired height for thumbnail screenshots, which are stored in
1914 * the database, and used on the bookmarks screen.
1915 * @param context Context for finding out the density of the screen.
1916 * @return desired height for thumbnail screenshot.
1917 */
1918 static int getDesiredThumbnailHeight(Context context) {
1919 return context.getResources().getDimensionPixelOffset(
1920 R.dimen.bookmarkThumbnailHeight);
1921 }
1922
1923 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001924 // We render to a bitmap 2x the desired size so that we can then
1925 // re-scale it with filtering since canvas.scale doesn't filter
1926 // This helps reduce aliasing at the cost of being slightly blurry
1927 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001928 Picture thumbnail = view.capturePicture();
1929 if (thumbnail == null) {
1930 return null;
1931 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001932 width *= filter_scale;
1933 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001934 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1935 Canvas canvas = new Canvas(bm);
1936 // May need to tweak these values to determine what is the
1937 // best scale factor
1938 int thumbnailWidth = thumbnail.getWidth();
1939 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001940 float scaleFactor = 1.0f;
Michael Kolb8233fac2010-10-26 16:08:53 -07001941 if (thumbnailWidth > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001942 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001943 } else {
1944 return null;
1945 }
John Reckfe49ab42010-11-16 17:09:37 -08001946
Michael Kolb8233fac2010-10-26 16:08:53 -07001947 if (view.getWidth() > view.getHeight() &&
1948 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
1949 // If the device is in landscape and the page is shorter
John Reckfe49ab42010-11-16 17:09:37 -08001950 // than the height of the view, center the thumnail and crop the sides
1951 scaleFactor = (float) height / (float)thumbnailHeight;
1952 float wx = (thumbnailWidth * scaleFactor) - width;
1953 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001954 }
1955
John Reckfe49ab42010-11-16 17:09:37 -08001956 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001957
1958 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001959 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
1960 height / filter_scale, true);
1961 bm.recycle();
1962 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001963 }
1964
John Reck34ef2672011-02-10 11:30:55 -08001965 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001966 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07001967 // FIXME: Would like to make sure there is actually something to
1968 // draw, but the API for that (WebViewCore.pictureReady()) is not
1969 // currently accessible here.
1970
John Reck34ef2672011-02-10 11:30:55 -08001971 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08001972 if (view == null) {
1973 // Tab was destroyed
1974 return;
1975 }
John Reck34ef2672011-02-10 11:30:55 -08001976 final String url = tab.getUrl();
1977 final String originalUrl = view.getOriginalUrl();
1978
1979 if (TextUtils.isEmpty(url)) {
1980 return;
1981 }
1982
1983 // Only update thumbnails for web urls (http(s)://), not for
1984 // about:, javascript:, data:, etc...
1985 // Unless it is a bookmarked site, then always update
1986 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
1987 return;
1988 }
1989
Michael Kolb8233fac2010-10-26 16:08:53 -07001990 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1991 getDesiredThumbnailHeight(mActivity));
1992 if (bm == null) {
1993 return;
1994 }
1995
1996 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08001997 new AsyncTask<Void, Void, Void>() {
1998 @Override
1999 protected Void doInBackground(Void... unused) {
2000 Cursor cursor = null;
2001 try {
2002 // TODO: Clean this up
2003 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2004 if (cursor != null && cursor.moveToFirst()) {
2005 final ByteArrayOutputStream os =
2006 new ByteArrayOutputStream();
2007 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002008
John Reck34ef2672011-02-10 11:30:55 -08002009 ContentValues values = new ContentValues();
2010 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002011
John Reck34ef2672011-02-10 11:30:55 -08002012 do {
John Reck617fd832011-02-16 14:35:59 -08002013 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002014 cr.update(Images.CONTENT_URI, values, null, null);
2015 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002016 }
John Reck34ef2672011-02-10 11:30:55 -08002017 } catch (IllegalStateException e) {
2018 // Ignore
2019 } finally {
2020 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002021 }
John Reck34ef2672011-02-10 11:30:55 -08002022 return null;
2023 }
2024 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002025 }
2026
2027 private class Copy implements OnMenuItemClickListener {
2028 private CharSequence mText;
2029
2030 public boolean onMenuItemClick(MenuItem item) {
2031 copy(mText);
2032 return true;
2033 }
2034
2035 public Copy(CharSequence toCopy) {
2036 mText = toCopy;
2037 }
2038 }
2039
Leon Scroggins63c02662010-11-18 15:16:27 -05002040 private static class Download implements OnMenuItemClickListener {
2041 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002042 private String mText;
2043
2044 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002045 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
2046 null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07002047 return true;
2048 }
2049
Leon Scroggins63c02662010-11-18 15:16:27 -05002050 public Download(Activity activity, String toDownload) {
2051 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002052 mText = toDownload;
2053 }
2054 }
2055
Cary Clark8974d282010-11-22 10:46:05 -05002056 private static class SelectText implements OnMenuItemClickListener {
2057 private WebView mWebView;
2058
2059 public boolean onMenuItemClick(MenuItem item) {
2060 if (mWebView != null) {
2061 return mWebView.selectText();
2062 }
2063 return false;
2064 }
2065
2066 public SelectText(WebView webView) {
2067 mWebView = webView;
2068 }
2069
2070 }
2071
Michael Kolb8233fac2010-10-26 16:08:53 -07002072 /********************** TODO: UI stuff *****************************/
2073
2074 // these methods have been copied, they still need to be cleaned up
2075
2076 /****************** tabs ***************************************************/
2077
2078 // basic tab interactions:
2079
2080 // it is assumed that tabcontrol already knows about the tab
2081 protected void addTab(Tab tab) {
2082 mUi.addTab(tab);
2083 }
2084
2085 protected void removeTab(Tab tab) {
2086 mUi.removeTab(tab);
2087 mTabControl.removeTab(tab);
2088 }
2089
2090 protected void setActiveTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002091 mTabControl.setCurrentTab(tab);
Michael Kolb77df4562010-11-19 14:49:34 -08002092 // the tab is guaranteed to have a webview after setCurrentTab
2093 mUi.setActiveTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002094 }
2095
2096 protected void closeEmptyChildTab() {
2097 Tab current = mTabControl.getCurrentTab();
2098 if (current != null
2099 && current.getWebView().copyBackForwardList().getSize() == 0) {
2100 Tab parent = current.getParentTab();
2101 if (parent != null) {
2102 switchToTab(mTabControl.getTabIndex(parent));
2103 closeTab(current);
2104 }
2105 }
2106 }
2107
2108 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002109 // Dismiss the subwindow if applicable.
2110 dismissSubWindow(appTab);
2111 // Since we might kill the WebView, remove it from the
2112 // content view first.
2113 mUi.detachTab(appTab);
2114 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002115 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002116 // TODO: analyze why the remove and add are necessary
2117 mUi.attachTab(appTab);
2118 if (mTabControl.getCurrentTab() != appTab) {
2119 switchToTab(mTabControl.getTabIndex(appTab));
John Reck30c714c2010-12-16 17:30:34 -08002120 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002121 } else {
2122 // If the tab was the current tab, we have to attach
2123 // it to the view system again.
2124 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002125 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002126 }
2127 }
2128
2129 // Remove the sub window if it exists. Also called by TabControl when the
2130 // user clicks the 'X' to dismiss a sub window.
2131 public void dismissSubWindow(Tab tab) {
2132 removeSubWindow(tab);
2133 // dismiss the subwindow. This will destroy the WebView.
2134 tab.dismissSubWindow();
2135 getCurrentTopWebView().requestFocus();
2136 }
2137
2138 @Override
2139 public void removeSubWindow(Tab t) {
2140 if (t.getSubWebView() != null) {
2141 mUi.removeSubWindow(t.getSubViewContainer());
2142 }
2143 }
2144
2145 @Override
2146 public void attachSubWindow(Tab tab) {
2147 if (tab.getSubWebView() != null) {
2148 mUi.attachSubWindow(tab.getSubViewContainer());
2149 getCurrentTopWebView().requestFocus();
2150 }
2151 }
2152
Michael Kolb843510f2010-12-09 10:51:49 -08002153 @Override
2154 public Tab openTabToHomePage() {
2155 // check for max tabs
2156 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002157 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2158 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002159 } else {
2160 mUi.showMaxTabsWarning();
2161 return null;
2162 }
2163 }
2164
Michael Kolb18eb3772010-12-10 14:29:51 -08002165 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2166 if (mSettings.openInBackground() && !forceForeground) {
2167 Tab tab = mTabControl.createNewTab(false, null, null,
2168 (parent != null) && parent.isPrivateBrowsingEnabled());
2169 if (tab != null) {
2170 addTab(tab);
2171 WebView view = tab.getWebView();
2172 loadUrl(view, url);
2173 }
2174 return tab;
2175 } else {
2176 return openTabAndShow(parent, new UrlData(url), false, null);
2177 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002178 }
2179
Michael Kolb18eb3772010-12-10 14:29:51 -08002180
Michael Kolb8233fac2010-10-26 16:08:53 -07002181 // This method does a ton of stuff. It will attempt to create a new tab
2182 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2183 // url isn't null, it will load the given url.
Patrick Scottcd135082011-01-31 18:21:58 -05002184 public Tab openTabAndShow(Tab parent, final UrlData urlData,
2185 boolean closeOnExit, String appId) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002186 final Tab currentTab = mTabControl.getCurrentTab();
2187 if (mTabControl.canCreateNewTab()) {
2188 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Michael Kolb18eb3772010-12-10 14:29:51 -08002189 urlData.mUrl,
2190 (parent != null) && parent.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -07002191 WebView webview = tab.getWebView();
2192 // We must set the new tab as the current tab to reflect the old
2193 // animation behavior.
2194 addTab(tab);
2195 setActiveTab(tab);
Patrick Scottcd135082011-01-31 18:21:58 -05002196
2197 // Callback to load the url data.
2198 final Runnable load = new Runnable() {
2199 @Override public void run() {
2200 if (!urlData.isEmpty()) {
2201 loadUrlDataIn(tab, urlData);
2202 }
2203 }
2204 };
2205
2206 GoogleAccountLogin.startLoginIfNeeded(mActivity, mSettings, load);
Michael Kolb8233fac2010-10-26 16:08:53 -07002207 return tab;
2208 } else {
2209 // Get rid of the subwindow if it exists
2210 dismissSubWindow(currentTab);
2211 if (!urlData.isEmpty()) {
2212 // Load the given url.
2213 loadUrlDataIn(currentTab, urlData);
2214 }
2215 return currentTab;
2216 }
2217 }
2218
Michael Kolb8233fac2010-10-26 16:08:53 -07002219 @Override
2220 public Tab openIncognitoTab() {
2221 if (mTabControl.canCreateNewTab()) {
2222 Tab currentTab = mTabControl.getCurrentTab();
Michael Kolb8e7178d2011-01-26 19:13:36 -08002223 Tab tab = mTabControl.createNewTab(false, null,
John Reck4bfc0db2011-01-27 17:47:12 -08002224 null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07002225 addTab(tab);
2226 setActiveTab(tab);
John Reck4bfc0db2011-01-27 17:47:12 -08002227 loadUrlDataIn(tab, new UrlData("browser:incognito"));
Michael Kolb8233fac2010-10-26 16:08:53 -07002228 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002229 } else {
2230 mUi.showMaxTabsWarning();
2231 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002232 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002233 }
2234
2235 /**
2236 * @param index Index of the tab to change to, as defined by
2237 * mTabControl.getTabIndex(Tab t).
2238 * @return boolean True if we successfully switched to a different tab. If
2239 * the indexth tab is null, or if that tab is the same as
2240 * the current one, return false.
2241 */
2242 @Override
2243 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002244 // hide combo view if open
2245 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002246 Tab tab = mTabControl.getTab(index);
2247 Tab currentTab = mTabControl.getCurrentTab();
2248 if (tab == null || tab == currentTab) {
2249 return false;
2250 }
2251 setActiveTab(tab);
2252 return true;
2253 }
2254
2255 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002256 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002257 // hide combo view if open
2258 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002259 final Tab current = mTabControl.getCurrentTab();
2260 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002261 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002262 return;
2263 }
2264 final Tab parent = current.getParentTab();
2265 int indexToShow = -1;
2266 if (parent != null) {
2267 indexToShow = mTabControl.getTabIndex(parent);
2268 } else {
2269 final int currentIndex = mTabControl.getCurrentIndex();
2270 // Try to move to the tab to the right
2271 indexToShow = currentIndex + 1;
2272 if (indexToShow > mTabControl.getTabCount() - 1) {
2273 // Try to move to the tab to the left
2274 indexToShow = currentIndex - 1;
2275 }
2276 }
2277 if (switchToTab(indexToShow)) {
2278 // Close window
2279 closeTab(current);
2280 }
2281 }
2282
2283 /**
2284 * Close the tab, remove its associated title bar, and adjust mTabControl's
2285 * current tab to a valid value.
2286 */
2287 @Override
2288 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002289 // hide combo view if open
2290 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002291 int currentIndex = mTabControl.getCurrentIndex();
2292 int removeIndex = mTabControl.getTabIndex(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002293 Tab newtab = mTabControl.getTab(currentIndex);
2294 setActiveTab(newtab);
Michael Kolb2d59c322011-01-25 13:18:55 -08002295 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002296 }
2297
2298 /**************** TODO: Url loading clean up *******************************/
2299
2300 // Called when loading from context menu or LOAD_URL message
2301 protected void loadUrlFromContext(WebView view, String url) {
2302 // In case the user enters nothing.
2303 if (url != null && url.length() != 0 && view != null) {
2304 url = UrlUtils.smartUrlFilter(url);
2305 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2306 loadUrl(view, url);
2307 }
2308 }
2309 }
2310
2311 /**
2312 * Load the URL into the given WebView and update the title bar
2313 * to reflect the new load. Call this instead of WebView.loadUrl
2314 * directly.
2315 * @param view The WebView used to load url.
2316 * @param url The URL to load.
2317 */
2318 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002319 view.loadUrl(url);
2320 }
2321
2322 /**
2323 * Load UrlData into a Tab and update the title bar to reflect the new
2324 * load. Call this instead of UrlData.loadIn directly.
2325 * @param t The Tab used to load.
2326 * @param data The UrlData being loaded.
2327 */
2328 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002329 data.loadIn(t);
2330 }
2331
John Reck30c714c2010-12-16 17:30:34 -08002332 @Override
2333 public void onUserCanceledSsl(Tab tab) {
2334 WebView web = tab.getWebView();
2335 // TODO: Figure out the "right" behavior
2336 if (web.canGoBack()) {
2337 web.goBack();
2338 } else {
2339 web.loadUrl(mSettings.getHomePage());
2340 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002341 }
2342
2343 void goBackOnePageOrQuit() {
2344 Tab current = mTabControl.getCurrentTab();
2345 if (current == null) {
2346 /*
2347 * Instead of finishing the activity, simply push this to the back
2348 * of the stack and let ActivityManager to choose the foreground
2349 * activity. As BrowserActivity is singleTask, it will be always the
2350 * root of the task. So we can use either true or false for
2351 * moveTaskToBack().
2352 */
2353 mActivity.moveTaskToBack(true);
2354 return;
2355 }
2356 WebView w = current.getWebView();
2357 if (w.canGoBack()) {
2358 w.goBack();
2359 } else {
2360 // Check to see if we are closing a window that was created by
2361 // another window. If so, we switch back to that window.
2362 Tab parent = current.getParentTab();
2363 if (parent != null) {
2364 switchToTab(mTabControl.getTabIndex(parent));
2365 // Now we close the other tab
2366 closeTab(current);
2367 } else {
2368 if (current.closeOnExit()) {
2369 // force the tab's inLoad() to be false as we are going to
2370 // either finish the activity or remove the tab. This will
2371 // ensure pauseWebViewTimers() taking action.
Michael Kolb70976932010-11-30 11:34:01 -08002372 current.clearInPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07002373 if (mTabControl.getTabCount() == 1) {
2374 mActivity.finish();
2375 return;
2376 }
2377 if (mActivityPaused) {
2378 Log.e(LOGTAG, "BrowserActivity is already paused "
2379 + "while handing goBackOnePageOrQuit.");
2380 }
Michael Kolb70976932010-11-30 11:34:01 -08002381 pauseWebViewTimers(current);
Michael Kolb96683f72011-02-15 14:24:35 -08002382 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002383 }
2384 /*
2385 * Instead of finishing the activity, simply push this to the back
2386 * of the stack and let ActivityManager to choose the foreground
2387 * activity. As BrowserActivity is singleTask, it will be always the
2388 * root of the task. So we can use either true or false for
2389 * moveTaskToBack().
2390 */
2391 mActivity.moveTaskToBack(true);
2392 }
2393 }
2394 }
2395
2396 /**
2397 * Feed the previously stored results strings to the BrowserProvider so that
2398 * the SearchDialog will show them instead of the standard searches.
2399 * @param result String to show on the editable line of the SearchDialog.
2400 */
2401 @Override
2402 public void showVoiceSearchResults(String result) {
2403 ContentProviderClient client = mActivity.getContentResolver()
2404 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2405 ContentProvider prov = client.getLocalContentProvider();
2406 BrowserProvider bp = (BrowserProvider) prov;
2407 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2408 client.release();
2409
2410 Bundle bundle = createGoogleSearchSourceBundle(
2411 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2412 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2413 startSearch(result, false, bundle, false);
2414 }
2415
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002416 @Override
2417 public void startSearch(String url) {
2418 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
2419 null, false);
2420 }
2421
Michael Kolb8233fac2010-10-26 16:08:53 -07002422 private void startSearch(String initialQuery, boolean selectInitialQuery,
2423 Bundle appSearchData, boolean globalSearch) {
2424 if (appSearchData == null) {
2425 appSearchData = createGoogleSearchSourceBundle(
2426 GOOGLE_SEARCH_SOURCE_TYPE);
2427 }
2428
2429 SearchEngine searchEngine = mSettings.getSearchEngine();
2430 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2431 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2432 }
2433 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2434 globalSearch);
2435 }
2436
2437 private Bundle createGoogleSearchSourceBundle(String source) {
2438 Bundle bundle = new Bundle();
2439 bundle.putString(Search.SOURCE, source);
2440 return bundle;
2441 }
2442
2443 /**
2444 * handle key events in browser
2445 *
2446 * @param keyCode
2447 * @param event
2448 * @return true if handled, false to pass to super
2449 */
2450 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002451 boolean noModifiers = event.hasNoModifiers();
2452
Michael Kolb8233fac2010-10-26 16:08:53 -07002453 // Even if MENU is already held down, we need to call to super to open
2454 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002455 if (!noModifiers
2456 && ((KeyEvent.KEYCODE_MENU == keyCode)
2457 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2458 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002459 mMenuIsDown = true;
2460 return false;
2461 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002462
Cary Clark8ff8c662010-12-29 15:03:05 -05002463 WebView webView = getCurrentTopWebView();
2464 if (webView == null) return false;
2465
Cary Clark160bbb92011-01-10 11:17:07 -05002466 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2467 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002468
Michael Kolb8233fac2010-10-26 16:08:53 -07002469 switch(keyCode) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002470 case KeyEvent.KEYCODE_ESCAPE:
Cary Clark160bbb92011-01-10 11:17:07 -05002471 if (!noModifiers) break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002472 stopLoading();
2473 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07002474 case KeyEvent.KEYCODE_SPACE:
2475 // WebView/WebTextView handle the keys in the KeyDown. As
2476 // the Activity's shortcut keys are only handled when WebView
2477 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002478 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002479 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002480 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002481 pageDown();
2482 }
2483 return true;
2484 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002485 if (!noModifiers) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002486 if (event.getRepeatCount() == 0) {
2487 event.startTracking();
2488 return true;
2489 } else if (mUi.showsWeb()
2490 && event.isLongPress()) {
2491 bookmarksOrHistoryPicker(true);
2492 return true;
2493 }
2494 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002495 case KeyEvent.KEYCODE_DPAD_LEFT:
2496 if (ctrl) {
2497 webView.goBack();
2498 return true;
2499 }
2500 break;
2501 case KeyEvent.KEYCODE_DPAD_RIGHT:
2502 if (ctrl) {
2503 webView.goForward();
2504 return true;
2505 }
2506 break;
2507 case KeyEvent.KEYCODE_A:
2508 if (ctrl) {
2509 webView.selectAll();
2510 return true;
2511 }
2512 break;
Michael Kolba4183062011-01-16 10:43:21 -08002513// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002514 case KeyEvent.KEYCODE_C:
2515 if (ctrl) {
2516 webView.copySelection();
2517 return true;
2518 }
2519 break;
Michael Kolba4183062011-01-16 10:43:21 -08002520// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002521// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002522// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002523// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002524// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002525// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002526// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002527// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002528// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002529// case KeyEvent.KEYCODE_M: // unused
2530// case KeyEvent.KEYCODE_N: // in Chrome: new window
2531// case KeyEvent.KEYCODE_O: // in Chrome: open file
2532// case KeyEvent.KEYCODE_P: // in Chrome: print page
2533// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002534// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002535// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2536 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002537 // we can't use the ctrl/shift flags, they check for
2538 // exclusive use of a modifier
2539 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002540 if (event.isShiftPressed()) {
2541 openIncognitoTab();
2542 } else {
2543 openTabToHomePage();
2544 }
2545 return true;
2546 }
2547 break;
2548// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2549// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolba4183062011-01-16 10:43:21 -08002550// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002551// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2552// case KeyEvent.KEYCODE_Y: // unused
2553// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002554 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002555 // it is a regular key and webview is not null
2556 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002557 }
2558
2559 boolean onKeyUp(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002560 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002561 switch(keyCode) {
2562 case KeyEvent.KEYCODE_MENU:
2563 mMenuIsDown = false;
2564 break;
2565 case KeyEvent.KEYCODE_BACK:
2566 if (event.isTracking() && !event.isCanceled()) {
2567 onBackKey();
2568 return true;
2569 }
2570 break;
2571 }
2572 return false;
2573 }
2574
2575 public boolean isMenuDown() {
2576 return mMenuIsDown;
2577 }
2578
Ben Murdoch8029a772010-11-16 11:58:21 +00002579 public void setupAutoFill(Message message) {
2580 // Open the settings activity at the AutoFill profile fragment so that
2581 // the user can create a new profile. When they return, we will dispatch
2582 // the message so that we can autofill the form using their new profile.
2583 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2584 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2585 AutoFillSettingsFragment.class.getName());
2586 mAutoFillSetupMessage = message;
2587 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2588 }
John Reckb3417f02011-01-14 11:01:05 -08002589
2590 @Override
2591 public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
2592 mOptionsMenuHandler = handler;
2593 }
2594
2595 @Override
2596 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
2597 if (mOptionsMenuHandler == handler) {
2598 mOptionsMenuHandler = null;
2599 }
2600 }
2601
Michael Kolb8233fac2010-10-26 16:08:53 -07002602}