blob: 9561cb620df32da4d19c83ccf59ebacdde2b4831 [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() {
681 if (mUploadHandler != null) {
682 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();
1029 String url = (getCurrentTopWebView() == null) ? null : getCurrentTopWebView().getUrl();
1030 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1031 null, false);
1032 }
1033
Michael Kolbcfa3af52010-12-14 10:36:11 -08001034 public void startVoiceSearch() {
1035 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1036 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1037 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1038 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1039 mActivity.getComponentName().flattenToString());
1040 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001041 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001042 mActivity.startActivity(intent);
1043 }
1044
Michael Kolb8233fac2010-10-26 16:08:53 -07001045 public void activateVoiceSearchMode(String title) {
1046 mUi.showVoiceTitleBar(title);
1047 }
1048
1049 public void revertVoiceSearchMode(Tab tab) {
1050 mUi.revertVoiceTitleBar(tab);
1051 }
1052
1053 public void showCustomView(Tab tab, View view,
1054 WebChromeClient.CustomViewCallback callback) {
1055 if (tab.inForeground()) {
1056 if (mUi.isCustomViewShowing()) {
1057 callback.onCustomViewHidden();
1058 return;
1059 }
1060 mUi.showCustomView(view, callback);
1061 // Save the menu state and set it to empty while the custom
1062 // view is showing.
1063 mOldMenuState = mMenuState;
1064 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001065 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001066 }
1067 }
1068
1069 @Override
1070 public void hideCustomView() {
1071 if (mUi.isCustomViewShowing()) {
1072 mUi.onHideCustomView();
1073 // Reset the old menu state.
1074 mMenuState = mOldMenuState;
1075 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001076 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001077 }
1078 }
1079
1080 protected void onActivityResult(int requestCode, int resultCode,
1081 Intent intent) {
1082 if (getCurrentTopWebView() == null) return;
1083 switch (requestCode) {
1084 case PREFERENCES_PAGE:
1085 if (resultCode == Activity.RESULT_OK && intent != null) {
1086 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
1087 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
1088 mTabControl.removeParentChildRelationShips();
1089 }
1090 }
1091 break;
1092 case FILE_SELECTED:
1093 // Choose a file from the file picker.
1094 if (null == mUploadHandler) break;
1095 mUploadHandler.onResult(resultCode, intent);
1096 mUploadHandler = null;
1097 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001098 case AUTOFILL_SETUP:
1099 // Determine whether a profile was actually set up or not
1100 // and if so, send the message back to the WebTextView to
1101 // fill the form with the new profile.
1102 if (getSettings().getAutoFillProfile() != null) {
1103 mAutoFillSetupMessage.sendToTarget();
1104 mAutoFillSetupMessage = null;
1105 }
1106 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001107 default:
1108 break;
1109 }
1110 getCurrentTopWebView().requestFocus();
1111 }
1112
1113 /**
1114 * Open the Go page.
1115 * @param startWithHistory If true, open starting on the history tab.
1116 * Otherwise, start with the bookmarks tab.
1117 */
1118 @Override
1119 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1120 if (mTabControl.getCurrentWebView() == null) {
1121 return;
1122 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001123 // clear action mode
1124 if (isInCustomActionMode()) {
1125 endActionMode();
1126 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001127 Bundle extras = new Bundle();
1128 // Disable opening in a new window if we have maxed out the windows
1129 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1130 !mTabControl.canCreateNewTab());
1131 mUi.showComboView(startWithHistory, extras);
1132 }
1133
1134 // combo view callbacks
1135
1136 /**
1137 * callback from ComboPage when clear history is requested
1138 */
1139 public void onRemoveParentChildRelationships() {
1140 mTabControl.removeParentChildRelationShips();
1141 }
1142
1143 /**
1144 * callback from ComboPage when bookmark/history selection
1145 */
1146 @Override
1147 public void onUrlSelected(String url, boolean newTab) {
1148 removeComboView();
1149 if (!TextUtils.isEmpty(url)) {
1150 if (newTab) {
Michael Kolb18eb3772010-12-10 14:29:51 -08001151 openTab(mTabControl.getCurrentTab(), url, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001152 } else {
1153 final Tab currentTab = mTabControl.getCurrentTab();
1154 dismissSubWindow(currentTab);
1155 loadUrl(getCurrentTopWebView(), url);
1156 }
1157 }
1158 }
1159
1160 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07001161 * dismiss the ComboPage
1162 */
1163 @Override
1164 public void removeComboView() {
1165 mUi.hideComboView();
1166 }
1167
1168 // active tabs page handling
1169
1170 protected void showActiveTabsPage() {
1171 mMenuState = EMPTY_MENU;
1172 mUi.showActiveTabsPage();
1173 }
1174
1175 /**
1176 * Remove the active tabs page.
1177 * @param needToAttach If true, the active tabs page did not attach a tab
1178 * to the content view, so we need to do that here.
1179 */
1180 @Override
1181 public void removeActiveTabsPage(boolean needToAttach) {
1182 mMenuState = R.id.MAIN_MENU;
1183 mUi.removeActiveTabsPage();
1184 if (needToAttach) {
1185 setActiveTab(mTabControl.getCurrentTab());
1186 }
1187 getCurrentTopWebView().requestFocus();
1188 }
1189
1190 // key handling
1191 protected void onBackKey() {
1192 if (!mUi.onBackKey()) {
1193 WebView subwindow = mTabControl.getCurrentSubWindow();
1194 if (subwindow != null) {
1195 if (subwindow.canGoBack()) {
1196 subwindow.goBack();
1197 } else {
1198 dismissSubWindow(mTabControl.getCurrentTab());
1199 }
1200 } else {
1201 goBackOnePageOrQuit();
1202 }
1203 }
1204 }
1205
1206 // menu handling and state
1207 // TODO: maybe put into separate handler
1208
1209 protected boolean onCreateOptionsMenu(Menu menu) {
John Reckb3417f02011-01-14 11:01:05 -08001210 if (mOptionsMenuHandler != null) {
1211 return mOptionsMenuHandler.onCreateOptionsMenu(menu);
1212 }
1213
John Reckd73c5a22010-12-22 10:22:50 -08001214 if (mMenuState == EMPTY_MENU) {
1215 return false;
1216 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001217 MenuInflater inflater = mActivity.getMenuInflater();
1218 inflater.inflate(R.menu.browser, menu);
1219 updateInLoadMenuItems(menu);
1220 // hold on to the menu reference here; it is used by the page callbacks
1221 // to update the menu based on loading state
1222 mCachedMenu = menu;
1223 return true;
1224 }
1225
1226 protected void onCreateContextMenu(ContextMenu menu, View v,
1227 ContextMenuInfo menuInfo) {
1228 if (v instanceof TitleBarBase) {
1229 return;
1230 }
1231 if (!(v instanceof WebView)) {
1232 return;
1233 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001234 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001235 WebView.HitTestResult result = webview.getHitTestResult();
1236 if (result == null) {
1237 return;
1238 }
1239
1240 int type = result.getType();
1241 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1242 Log.w(LOGTAG,
1243 "We should not show context menu when nothing is touched");
1244 return;
1245 }
1246 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1247 // let TextView handles context menu
1248 return;
1249 }
1250
1251 // Note, http://b/issue?id=1106666 is requesting that
1252 // an inflated menu can be used again. This is not available
1253 // yet, so inflate each time (yuk!)
1254 MenuInflater inflater = mActivity.getMenuInflater();
1255 inflater.inflate(R.menu.browsercontext, menu);
1256
1257 // Show the correct menu group
1258 final String extra = result.getExtra();
1259 menu.setGroupVisible(R.id.PHONE_MENU,
1260 type == WebView.HitTestResult.PHONE_TYPE);
1261 menu.setGroupVisible(R.id.EMAIL_MENU,
1262 type == WebView.HitTestResult.EMAIL_TYPE);
1263 menu.setGroupVisible(R.id.GEO_MENU,
1264 type == WebView.HitTestResult.GEO_TYPE);
1265 menu.setGroupVisible(R.id.IMAGE_MENU,
1266 type == WebView.HitTestResult.IMAGE_TYPE
1267 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1268 menu.setGroupVisible(R.id.ANCHOR_MENU,
1269 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1270 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001271 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1272 || type == WebView.HitTestResult.PHONE_TYPE
1273 || type == WebView.HitTestResult.EMAIL_TYPE
1274 || type == WebView.HitTestResult.GEO_TYPE;
1275 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1276 if (hitText) {
1277 menu.findItem(R.id.select_text_menu_id)
1278 .setOnMenuItemClickListener(new SelectText(webview));
1279 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001280 // Setup custom handling depending on the type
1281 switch (type) {
1282 case WebView.HitTestResult.PHONE_TYPE:
1283 menu.setHeaderTitle(Uri.decode(extra));
1284 menu.findItem(R.id.dial_context_menu_id).setIntent(
1285 new Intent(Intent.ACTION_VIEW, Uri
1286 .parse(WebView.SCHEME_TEL + extra)));
1287 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1288 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1289 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1290 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1291 addIntent);
1292 menu.findItem(R.id.copy_phone_context_menu_id)
1293 .setOnMenuItemClickListener(
1294 new Copy(extra));
1295 break;
1296
1297 case WebView.HitTestResult.EMAIL_TYPE:
1298 menu.setHeaderTitle(extra);
1299 menu.findItem(R.id.email_context_menu_id).setIntent(
1300 new Intent(Intent.ACTION_VIEW, Uri
1301 .parse(WebView.SCHEME_MAILTO + extra)));
1302 menu.findItem(R.id.copy_mail_context_menu_id)
1303 .setOnMenuItemClickListener(
1304 new Copy(extra));
1305 break;
1306
1307 case WebView.HitTestResult.GEO_TYPE:
1308 menu.setHeaderTitle(extra);
1309 menu.findItem(R.id.map_context_menu_id).setIntent(
1310 new Intent(Intent.ACTION_VIEW, Uri
1311 .parse(WebView.SCHEME_GEO
1312 + URLEncoder.encode(extra))));
1313 menu.findItem(R.id.copy_geo_context_menu_id)
1314 .setOnMenuItemClickListener(
1315 new Copy(extra));
1316 break;
1317
1318 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1319 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001320 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001321 // decide whether to show the open link in new tab option
1322 boolean showNewTab = mTabControl.canCreateNewTab();
1323 MenuItem newTabItem
1324 = menu.findItem(R.id.open_newtab_context_menu_id);
Michael Kolb2dd65c82011-01-14 11:07:38 -08001325 newTabItem.setTitle(
1326 BrowserSettings.getInstance().openInBackground()
1327 ? R.string.contextmenu_openlink_newwindow_background
1328 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001329 newTabItem.setVisible(showNewTab);
1330 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001331 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1332 newTabItem.setOnMenuItemClickListener(
1333 new MenuItem.OnMenuItemClickListener() {
1334 @Override
1335 public boolean onMenuItemClick(MenuItem item) {
1336 final HashMap<String, WebView> hrefMap =
1337 new HashMap<String, WebView>();
1338 hrefMap.put("webview", webview);
1339 final Message msg = mHandler.obtainMessage(
1340 FOCUS_NODE_HREF,
1341 R.id.open_newtab_context_menu_id,
1342 0, hrefMap);
1343 webview.requestFocusNodeHref(msg);
1344 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001345 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001346 });
1347 } else {
1348 newTabItem.setOnMenuItemClickListener(
1349 new MenuItem.OnMenuItemClickListener() {
1350 @Override
1351 public boolean onMenuItemClick(MenuItem item) {
1352 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -08001353 final Tab newTab = openTab(parent,
1354 extra, false);
Leon Scroggins026f2542010-11-22 13:26:12 -05001355 if (newTab != parent) {
1356 parent.addChildTab(newTab);
1357 }
1358 return true;
1359 }
1360 });
1361 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001362 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001363 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1364 break;
1365 }
1366 // otherwise fall through to handle image part
1367 case WebView.HitTestResult.IMAGE_TYPE:
1368 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1369 menu.setHeaderTitle(extra);
1370 }
1371 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1372 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1373 menu.findItem(R.id.download_context_menu_id).
Leon Scroggins63c02662010-11-18 15:16:27 -05001374 setOnMenuItemClickListener(new Download(mActivity, extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001375 menu.findItem(R.id.set_wallpaper_context_menu_id).
1376 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1377 extra));
1378 break;
1379
1380 default:
1381 Log.w(LOGTAG, "We should not get here.");
1382 break;
1383 }
1384 //update the ui
1385 mUi.onContextMenuCreated(menu);
1386 }
1387
1388 /**
1389 * As the menu can be open when loading state changes
1390 * we must manually update the state of the stop/reload menu
1391 * item
1392 */
1393 private void updateInLoadMenuItems(Menu menu) {
1394 if (menu == null) {
1395 return;
1396 }
1397 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1398 MenuItem src = mInLoad ?
1399 menu.findItem(R.id.stop_menu_id):
1400 menu.findItem(R.id.reload_menu_id);
1401 if (src != null) {
1402 dest.setIcon(src.getIcon());
1403 dest.setTitle(src.getTitle());
1404 }
1405 }
1406
John Reckb3417f02011-01-14 11:01:05 -08001407 boolean onPrepareOptionsMenu(Menu menu) {
1408 if (mOptionsMenuHandler != null) {
1409 return mOptionsMenuHandler.onPrepareOptionsMenu(menu);
1410 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001411 // This happens when the user begins to hold down the menu key, so
1412 // allow them to chord to get a shortcut.
1413 mCanChord = true;
1414 // Note: setVisible will decide whether an item is visible; while
1415 // setEnabled() will decide whether an item is enabled, which also means
1416 // whether the matching shortcut key will function.
1417 switch (mMenuState) {
1418 case EMPTY_MENU:
1419 if (mCurrentMenuState != mMenuState) {
1420 menu.setGroupVisible(R.id.MAIN_MENU, false);
1421 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1422 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1423 }
1424 break;
1425 default:
1426 if (mCurrentMenuState != mMenuState) {
1427 menu.setGroupVisible(R.id.MAIN_MENU, true);
1428 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1429 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1430 }
1431 final WebView w = getCurrentTopWebView();
1432 boolean canGoBack = false;
1433 boolean canGoForward = false;
1434 boolean isHome = false;
1435 if (w != null) {
1436 canGoBack = w.canGoBack();
1437 canGoForward = w.canGoForward();
1438 isHome = mSettings.getHomePage().equals(w.getUrl());
1439 }
1440 final MenuItem back = menu.findItem(R.id.back_menu_id);
1441 back.setEnabled(canGoBack);
1442
1443 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1444 home.setEnabled(!isHome);
1445
1446 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1447 forward.setEnabled(canGoForward);
1448
1449 // decide whether to show the share link option
1450 PackageManager pm = mActivity.getPackageManager();
1451 Intent send = new Intent(Intent.ACTION_SEND);
1452 send.setType("text/plain");
1453 ResolveInfo ri = pm.resolveActivity(send,
1454 PackageManager.MATCH_DEFAULT_ONLY);
1455 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1456
1457 boolean isNavDump = mSettings.isNavDump();
1458 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1459 nav.setVisible(isNavDump);
1460 nav.setEnabled(isNavDump);
1461
1462 boolean showDebugSettings = mSettings.showDebugSettings();
1463 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1464 counter.setVisible(showDebugSettings);
1465 counter.setEnabled(showDebugSettings);
1466
John Reckb3417f02011-01-14 11:01:05 -08001467 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1468 newtab.setEnabled(getTabControl().canCreateNewTab());
Michael Kolb8233fac2010-10-26 16:08:53 -07001469
Leon Scroggins81983762011-02-11 15:17:36 -05001470 MenuItem archive = menu.findItem(R.id.save_webarchive_menu_id);
1471 String url = getCurrentTopWebView().getUrl();
1472 archive.setVisible(!TextUtils.isEmpty(url)
1473 && !url.endsWith("webarchivexml"));
1474
Michael Kolb8233fac2010-10-26 16:08:53 -07001475 break;
1476 }
1477 mCurrentMenuState = mMenuState;
1478 return true;
1479 }
1480
1481 public boolean onOptionsItemSelected(MenuItem item) {
John Reckb3417f02011-01-14 11:01:05 -08001482 if (mOptionsMenuHandler != null &&
1483 mOptionsMenuHandler.onOptionsItemSelected(item)) {
1484 return true;
1485 }
1486
Michael Kolb8233fac2010-10-26 16:08:53 -07001487 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1488 // menu remains active, so ensure comboview is dismissed
1489 // if main menu option is selected
1490 removeComboView();
1491 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001492 if (!mCanChord) {
1493 // The user has already fired a shortcut with this hold down of the
1494 // menu key.
1495 return false;
1496 }
1497 if (null == getCurrentTopWebView()) {
1498 return false;
1499 }
1500 if (mMenuIsDown) {
1501 // The shortcut action consumes the MENU. Even if it is still down,
1502 // it won't trigger the next shortcut action. In the case of the
1503 // shortcut action triggering a new activity, like Bookmarks, we
1504 // won't get onKeyUp for MENU. So it is important to reset it here.
1505 mMenuIsDown = false;
1506 }
1507 switch (item.getItemId()) {
1508 // -- Main menu
1509 case R.id.new_tab_menu_id:
1510 openTabToHomePage();
1511 break;
1512
1513 case R.id.incognito_menu_id:
1514 openIncognitoTab();
1515 break;
1516
1517 case R.id.goto_menu_id:
1518 editUrl();
1519 break;
1520
1521 case R.id.bookmarks_menu_id:
1522 bookmarksOrHistoryPicker(false);
1523 break;
1524
1525 case R.id.active_tabs_menu_id:
1526 showActiveTabsPage();
1527 break;
1528
1529 case R.id.add_bookmark_menu_id:
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001530 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001531 break;
1532
1533 case R.id.stop_reload_menu_id:
1534 if (mInLoad) {
1535 stopLoading();
1536 } else {
1537 getCurrentTopWebView().reload();
1538 }
1539 break;
1540
1541 case R.id.back_menu_id:
1542 getCurrentTopWebView().goBack();
1543 break;
1544
1545 case R.id.forward_menu_id:
1546 getCurrentTopWebView().goForward();
1547 break;
1548
1549 case R.id.close_menu_id:
1550 // Close the subwindow if it exists.
1551 if (mTabControl.getCurrentSubWindow() != null) {
1552 dismissSubWindow(mTabControl.getCurrentTab());
1553 break;
1554 }
1555 closeCurrentTab();
1556 break;
1557
1558 case R.id.homepage_menu_id:
1559 Tab current = mTabControl.getCurrentTab();
1560 if (current != null) {
1561 dismissSubWindow(current);
1562 loadUrl(current.getWebView(), mSettings.getHomePage());
1563 }
1564 break;
1565
1566 case R.id.preferences_menu_id:
1567 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1568 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1569 getCurrentTopWebView().getUrl());
1570 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1571 break;
1572
1573 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001574 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001575 break;
1576
Leon Scrogginsac993842011-02-02 12:54:07 -05001577 case R.id.save_webarchive_menu_id:
1578 String state = Environment.getExternalStorageState();
1579 if (!Environment.MEDIA_MOUNTED.equals(state)) {
1580 Log.e(LOGTAG, "External storage not mounted");
1581 Toast.makeText(mActivity, R.string.webarchive_failed,
1582 Toast.LENGTH_SHORT).show();
1583 break;
1584 }
1585 final String directory = Environment.getExternalStoragePublicDirectory(
1586 Environment.DIRECTORY_DOWNLOADS) + File.separator;
1587 File dir = new File(directory);
1588 if (!dir.exists() && !dir.mkdirs()) {
1589 Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
1590 Toast.makeText(mActivity, R.string.webarchive_failed,
1591 Toast.LENGTH_SHORT).show();
1592 break;
1593 }
1594 WebView topWebView = getCurrentTopWebView();
1595 final String title = topWebView.getTitle();
1596 topWebView.saveWebArchive(directory, true,
1597 new ValueCallback<String>() {
1598 @Override
1599 public void onReceiveValue(final String value) {
1600 if (value != null) {
1601 File file = new File(value);
1602 final long length = file.length();
1603 if (file.exists() && length > 0) {
Leon Scroggins1cb96552011-02-11 14:22:57 -05001604 Toast.makeText(mActivity, R.string.webarchive_saved,
1605 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001606 final DownloadManager manager = (DownloadManager) mActivity
1607 .getSystemService(Context.DOWNLOAD_SERVICE);
1608 new Thread("Add WebArchive to download manager") {
1609 @Override
1610 public void run() {
1611 manager.completedDownload(null == title ? value : title,
1612 value, true, "application/x-webarchive-xml",
1613 value, length, true);
1614 }
1615 }.start();
1616 return;
1617 }
1618 }
1619 Toast.makeText(mActivity,
1620 R.string.webarchive_failed, Toast.LENGTH_SHORT).show();
1621 }
1622 });
1623 break;
1624
Michael Kolb8233fac2010-10-26 16:08:53 -07001625 case R.id.page_info_menu_id:
1626 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1627 false);
1628 break;
1629
1630 case R.id.classic_history_menu_id:
1631 bookmarksOrHistoryPicker(true);
1632 break;
1633
1634 case R.id.title_bar_share_page_url:
1635 case R.id.share_page_menu_id:
1636 Tab currentTab = mTabControl.getCurrentTab();
1637 if (null == currentTab) {
1638 mCanChord = false;
1639 return false;
1640 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001641 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001642 break;
1643
1644 case R.id.dump_nav_menu_id:
1645 getCurrentTopWebView().debugDump();
1646 break;
1647
1648 case R.id.dump_counters_menu_id:
1649 getCurrentTopWebView().dumpV8Counters();
1650 break;
1651
1652 case R.id.zoom_in_menu_id:
1653 getCurrentTopWebView().zoomIn();
1654 break;
1655
1656 case R.id.zoom_out_menu_id:
1657 getCurrentTopWebView().zoomOut();
1658 break;
1659
1660 case R.id.view_downloads_menu_id:
1661 viewDownloads();
1662 break;
1663
1664 case R.id.window_one_menu_id:
1665 case R.id.window_two_menu_id:
1666 case R.id.window_three_menu_id:
1667 case R.id.window_four_menu_id:
1668 case R.id.window_five_menu_id:
1669 case R.id.window_six_menu_id:
1670 case R.id.window_seven_menu_id:
1671 case R.id.window_eight_menu_id:
1672 {
1673 int menuid = item.getItemId();
1674 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1675 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1676 Tab desiredTab = mTabControl.getTab(id);
1677 if (desiredTab != null &&
1678 desiredTab != mTabControl.getCurrentTab()) {
1679 switchToTab(id);
1680 }
1681 break;
1682 }
1683 }
1684 }
1685 break;
1686
1687 default:
1688 return false;
1689 }
1690 mCanChord = false;
1691 return true;
1692 }
1693
1694 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001695 // Let the History and Bookmark fragments handle menus they created.
1696 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1697 return false;
1698 }
1699
Michael Kolb8233fac2010-10-26 16:08:53 -07001700 // chording is not an issue with context menus, but we use the same
1701 // options selector, so set mCanChord to true so we can access them.
1702 mCanChord = true;
1703 int id = item.getItemId();
1704 boolean result = true;
1705 switch (id) {
1706 // For the context menu from the title bar
1707 case R.id.title_bar_copy_page_url:
1708 Tab currentTab = mTabControl.getCurrentTab();
1709 if (null == currentTab) {
1710 result = false;
1711 break;
1712 }
1713 WebView mainView = currentTab.getWebView();
1714 if (null == mainView) {
1715 result = false;
1716 break;
1717 }
1718 copy(mainView.getUrl());
1719 break;
1720 // -- Browser context menu
1721 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001722 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001723 case R.id.copy_link_context_menu_id:
1724 final WebView webView = getCurrentTopWebView();
1725 if (null == webView) {
1726 result = false;
1727 break;
1728 }
1729 final HashMap<String, WebView> hrefMap =
1730 new HashMap<String, WebView>();
1731 hrefMap.put("webview", webView);
1732 final Message msg = mHandler.obtainMessage(
1733 FOCUS_NODE_HREF, id, 0, hrefMap);
1734 webView.requestFocusNodeHref(msg);
1735 break;
1736
1737 default:
1738 // For other context menus
1739 result = onOptionsItemSelected(item);
1740 }
1741 mCanChord = false;
1742 return result;
1743 }
1744
1745 /**
1746 * support programmatically opening the context menu
1747 */
1748 public void openContextMenu(View view) {
1749 mActivity.openContextMenu(view);
1750 }
1751
1752 /**
1753 * programmatically open the options menu
1754 */
1755 public void openOptionsMenu() {
1756 mActivity.openOptionsMenu();
1757 }
1758
1759 public boolean onMenuOpened(int featureId, Menu menu) {
1760 if (mOptionsMenuOpen) {
1761 if (mConfigChanged) {
1762 // We do not need to make any changes to the state of the
1763 // title bar, since the only thing that happened was a
1764 // change in orientation
1765 mConfigChanged = false;
1766 } else {
1767 if (!mExtendedMenuOpen) {
1768 mExtendedMenuOpen = true;
1769 mUi.onExtendedMenuOpened();
1770 } else {
1771 // Switching the menu back to icon view, so show the
1772 // title bar once again.
1773 mExtendedMenuOpen = false;
1774 mUi.onExtendedMenuClosed(mInLoad);
1775 mUi.onOptionsMenuOpened();
1776 }
1777 }
1778 } else {
1779 // The options menu is closed, so open it, and show the title
1780 mOptionsMenuOpen = true;
1781 mConfigChanged = false;
1782 mExtendedMenuOpen = false;
1783 mUi.onOptionsMenuOpened();
1784 }
1785 return true;
1786 }
1787
1788 public void onOptionsMenuClosed(Menu menu) {
1789 mOptionsMenuOpen = false;
1790 mUi.onOptionsMenuClosed(mInLoad);
1791 }
1792
1793 public void onContextMenuClosed(Menu menu) {
1794 mUi.onContextMenuClosed(menu, mInLoad);
1795 }
1796
1797 // Helper method for getting the top window.
1798 @Override
1799 public WebView getCurrentTopWebView() {
1800 return mTabControl.getCurrentTopWebView();
1801 }
1802
1803 @Override
1804 public WebView getCurrentWebView() {
1805 return mTabControl.getCurrentWebView();
1806 }
1807
1808 /*
1809 * This method is called as a result of the user selecting the options
1810 * menu to see the download window. It shows the download window on top of
1811 * the current window.
1812 */
1813 void viewDownloads() {
1814 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1815 mActivity.startActivity(intent);
1816 }
1817
1818 // action mode
1819
1820 void onActionModeStarted(ActionMode mode) {
1821 mUi.onActionModeStarted(mode);
1822 mActionMode = mode;
1823 }
1824
1825 /*
1826 * True if a custom ActionMode (i.e. find or select) is in use.
1827 */
1828 @Override
1829 public boolean isInCustomActionMode() {
1830 return mActionMode != null;
1831 }
1832
1833 /*
1834 * End the current ActionMode.
1835 */
1836 @Override
1837 public void endActionMode() {
1838 if (mActionMode != null) {
1839 mActionMode.finish();
1840 }
1841 }
1842
1843 /*
1844 * Called by find and select when they are finished. Replace title bars
1845 * as necessary.
1846 */
1847 public void onActionModeFinished(ActionMode mode) {
1848 if (!isInCustomActionMode()) return;
1849 mUi.onActionModeFinished(mInLoad);
1850 mActionMode = null;
1851 }
1852
1853 boolean isInLoad() {
1854 return mInLoad;
1855 }
1856
1857 // bookmark handling
1858
1859 /**
1860 * add the current page as a bookmark to the given folder id
1861 * @param folderId use -1 for the default folder
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001862 * @param canBeAnEdit If true, check to see whether the site is already
1863 * bookmarked, and if it is, edit that bookmark. If false, and
1864 * the site is already bookmarked, do not attempt to edit the
1865 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001866 */
1867 @Override
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001868 public void bookmarkCurrentPage(long folderId, boolean canBeAnEdit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001869 Intent i = new Intent(mActivity,
1870 AddBookmarkPage.class);
1871 WebView w = getCurrentTopWebView();
1872 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1873 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1874 String touchIconUrl = w.getTouchIconUrl();
1875 if (touchIconUrl != null) {
1876 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1877 WebSettings settings = w.getSettings();
1878 if (settings != null) {
1879 i.putExtra(AddBookmarkPage.USER_AGENT,
1880 settings.getUserAgentString());
1881 }
1882 }
1883 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1884 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1885 getDesiredThumbnailHeight(mActivity)));
1886 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1887 i.putExtra(BrowserContract.Bookmarks.PARENT,
1888 folderId);
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001889 if (canBeAnEdit) {
1890 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1891 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001892 // Put the dialog at the upper right of the screen, covering the
1893 // star on the title bar.
1894 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1895 mActivity.startActivity(i);
1896 }
1897
1898 // file chooser
1899 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1900 mUploadHandler = new UploadHandler(this);
1901 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1902 }
1903
1904 // thumbnails
1905
1906 /**
1907 * Return the desired width for thumbnail screenshots, which are stored in
1908 * the database, and used on the bookmarks screen.
1909 * @param context Context for finding out the density of the screen.
1910 * @return desired width for thumbnail screenshot.
1911 */
1912 static int getDesiredThumbnailWidth(Context context) {
1913 return context.getResources().getDimensionPixelOffset(
1914 R.dimen.bookmarkThumbnailWidth);
1915 }
1916
1917 /**
1918 * Return the desired height for thumbnail screenshots, which are stored in
1919 * the database, and used on the bookmarks screen.
1920 * @param context Context for finding out the density of the screen.
1921 * @return desired height for thumbnail screenshot.
1922 */
1923 static int getDesiredThumbnailHeight(Context context) {
1924 return context.getResources().getDimensionPixelOffset(
1925 R.dimen.bookmarkThumbnailHeight);
1926 }
1927
1928 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001929 // We render to a bitmap 2x the desired size so that we can then
1930 // re-scale it with filtering since canvas.scale doesn't filter
1931 // This helps reduce aliasing at the cost of being slightly blurry
1932 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001933 Picture thumbnail = view.capturePicture();
1934 if (thumbnail == null) {
1935 return null;
1936 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001937 width *= filter_scale;
1938 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001939 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1940 Canvas canvas = new Canvas(bm);
1941 // May need to tweak these values to determine what is the
1942 // best scale factor
1943 int thumbnailWidth = thumbnail.getWidth();
1944 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001945 float scaleFactor = 1.0f;
Michael Kolb8233fac2010-10-26 16:08:53 -07001946 if (thumbnailWidth > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001947 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001948 } else {
1949 return null;
1950 }
John Reckfe49ab42010-11-16 17:09:37 -08001951
Michael Kolb8233fac2010-10-26 16:08:53 -07001952 if (view.getWidth() > view.getHeight() &&
1953 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
1954 // If the device is in landscape and the page is shorter
John Reckfe49ab42010-11-16 17:09:37 -08001955 // than the height of the view, center the thumnail and crop the sides
1956 scaleFactor = (float) height / (float)thumbnailHeight;
1957 float wx = (thumbnailWidth * scaleFactor) - width;
1958 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001959 }
1960
John Reckfe49ab42010-11-16 17:09:37 -08001961 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001962
1963 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001964 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
1965 height / filter_scale, true);
1966 bm.recycle();
1967 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001968 }
1969
John Reck34ef2672011-02-10 11:30:55 -08001970 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001971 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07001972 // FIXME: Would like to make sure there is actually something to
1973 // draw, but the API for that (WebViewCore.pictureReady()) is not
1974 // currently accessible here.
1975
John Reck34ef2672011-02-10 11:30:55 -08001976 WebView view = tab.getWebView();
1977 final String url = tab.getUrl();
1978 final String originalUrl = view.getOriginalUrl();
1979
1980 if (TextUtils.isEmpty(url)) {
1981 return;
1982 }
1983
1984 // Only update thumbnails for web urls (http(s)://), not for
1985 // about:, javascript:, data:, etc...
1986 // Unless it is a bookmarked site, then always update
1987 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
1988 return;
1989 }
1990
Michael Kolb8233fac2010-10-26 16:08:53 -07001991 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1992 getDesiredThumbnailHeight(mActivity));
1993 if (bm == null) {
1994 return;
1995 }
1996
1997 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08001998 new AsyncTask<Void, Void, Void>() {
1999 @Override
2000 protected Void doInBackground(Void... unused) {
2001 Cursor cursor = null;
2002 try {
2003 // TODO: Clean this up
2004 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2005 if (cursor != null && cursor.moveToFirst()) {
2006 final ByteArrayOutputStream os =
2007 new ByteArrayOutputStream();
2008 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002009
John Reck34ef2672011-02-10 11:30:55 -08002010 ContentValues values = new ContentValues();
2011 values.put(Images.THUMBNAIL, os.toByteArray());
2012 values.put(Images.URL, cursor.getString(0));
Michael Kolb8233fac2010-10-26 16:08:53 -07002013
John Reck34ef2672011-02-10 11:30:55 -08002014 do {
2015 cr.update(Images.CONTENT_URI, values, null, null);
2016 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002017 }
John Reck34ef2672011-02-10 11:30:55 -08002018 } catch (IllegalStateException e) {
2019 // Ignore
2020 } finally {
2021 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002022 }
John Reck34ef2672011-02-10 11:30:55 -08002023 return null;
2024 }
2025 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002026 }
2027
2028 private class Copy implements OnMenuItemClickListener {
2029 private CharSequence mText;
2030
2031 public boolean onMenuItemClick(MenuItem item) {
2032 copy(mText);
2033 return true;
2034 }
2035
2036 public Copy(CharSequence toCopy) {
2037 mText = toCopy;
2038 }
2039 }
2040
Leon Scroggins63c02662010-11-18 15:16:27 -05002041 private static class Download implements OnMenuItemClickListener {
2042 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002043 private String mText;
2044
2045 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002046 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
2047 null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07002048 return true;
2049 }
2050
Leon Scroggins63c02662010-11-18 15:16:27 -05002051 public Download(Activity activity, String toDownload) {
2052 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002053 mText = toDownload;
2054 }
2055 }
2056
Cary Clark8974d282010-11-22 10:46:05 -05002057 private static class SelectText implements OnMenuItemClickListener {
2058 private WebView mWebView;
2059
2060 public boolean onMenuItemClick(MenuItem item) {
2061 if (mWebView != null) {
2062 return mWebView.selectText();
2063 }
2064 return false;
2065 }
2066
2067 public SelectText(WebView webView) {
2068 mWebView = webView;
2069 }
2070
2071 }
2072
Michael Kolb8233fac2010-10-26 16:08:53 -07002073 /********************** TODO: UI stuff *****************************/
2074
2075 // these methods have been copied, they still need to be cleaned up
2076
2077 /****************** tabs ***************************************************/
2078
2079 // basic tab interactions:
2080
2081 // it is assumed that tabcontrol already knows about the tab
2082 protected void addTab(Tab tab) {
2083 mUi.addTab(tab);
2084 }
2085
2086 protected void removeTab(Tab tab) {
2087 mUi.removeTab(tab);
2088 mTabControl.removeTab(tab);
2089 }
2090
2091 protected void setActiveTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002092 mTabControl.setCurrentTab(tab);
Michael Kolb77df4562010-11-19 14:49:34 -08002093 // the tab is guaranteed to have a webview after setCurrentTab
2094 mUi.setActiveTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002095 }
2096
2097 protected void closeEmptyChildTab() {
2098 Tab current = mTabControl.getCurrentTab();
2099 if (current != null
2100 && current.getWebView().copyBackForwardList().getSize() == 0) {
2101 Tab parent = current.getParentTab();
2102 if (parent != null) {
2103 switchToTab(mTabControl.getTabIndex(parent));
2104 closeTab(current);
2105 }
2106 }
2107 }
2108
2109 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002110 // Dismiss the subwindow if applicable.
2111 dismissSubWindow(appTab);
2112 // Since we might kill the WebView, remove it from the
2113 // content view first.
2114 mUi.detachTab(appTab);
2115 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002116 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002117 // TODO: analyze why the remove and add are necessary
2118 mUi.attachTab(appTab);
2119 if (mTabControl.getCurrentTab() != appTab) {
2120 switchToTab(mTabControl.getTabIndex(appTab));
John Reck30c714c2010-12-16 17:30:34 -08002121 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002122 } else {
2123 // If the tab was the current tab, we have to attach
2124 // it to the view system again.
2125 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002126 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002127 }
2128 }
2129
2130 // Remove the sub window if it exists. Also called by TabControl when the
2131 // user clicks the 'X' to dismiss a sub window.
2132 public void dismissSubWindow(Tab tab) {
2133 removeSubWindow(tab);
2134 // dismiss the subwindow. This will destroy the WebView.
2135 tab.dismissSubWindow();
2136 getCurrentTopWebView().requestFocus();
2137 }
2138
2139 @Override
2140 public void removeSubWindow(Tab t) {
2141 if (t.getSubWebView() != null) {
2142 mUi.removeSubWindow(t.getSubViewContainer());
2143 }
2144 }
2145
2146 @Override
2147 public void attachSubWindow(Tab tab) {
2148 if (tab.getSubWebView() != null) {
2149 mUi.attachSubWindow(tab.getSubViewContainer());
2150 getCurrentTopWebView().requestFocus();
2151 }
2152 }
2153
Michael Kolb843510f2010-12-09 10:51:49 -08002154 @Override
2155 public Tab openTabToHomePage() {
2156 // check for max tabs
2157 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002158 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2159 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002160 } else {
2161 mUi.showMaxTabsWarning();
2162 return null;
2163 }
2164 }
2165
Michael Kolb18eb3772010-12-10 14:29:51 -08002166 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2167 if (mSettings.openInBackground() && !forceForeground) {
2168 Tab tab = mTabControl.createNewTab(false, null, null,
2169 (parent != null) && parent.isPrivateBrowsingEnabled());
2170 if (tab != null) {
2171 addTab(tab);
2172 WebView view = tab.getWebView();
2173 loadUrl(view, url);
2174 }
2175 return tab;
2176 } else {
2177 return openTabAndShow(parent, new UrlData(url), false, null);
2178 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002179 }
2180
Michael Kolb18eb3772010-12-10 14:29:51 -08002181
Michael Kolb8233fac2010-10-26 16:08:53 -07002182 // This method does a ton of stuff. It will attempt to create a new tab
2183 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2184 // url isn't null, it will load the given url.
Patrick Scottcd135082011-01-31 18:21:58 -05002185 public Tab openTabAndShow(Tab parent, final UrlData urlData,
2186 boolean closeOnExit, String appId) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002187 final Tab currentTab = mTabControl.getCurrentTab();
2188 if (mTabControl.canCreateNewTab()) {
2189 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Michael Kolb18eb3772010-12-10 14:29:51 -08002190 urlData.mUrl,
2191 (parent != null) && parent.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -07002192 WebView webview = tab.getWebView();
2193 // We must set the new tab as the current tab to reflect the old
2194 // animation behavior.
2195 addTab(tab);
2196 setActiveTab(tab);
Patrick Scottcd135082011-01-31 18:21:58 -05002197
2198 // Callback to load the url data.
2199 final Runnable load = new Runnable() {
2200 @Override public void run() {
2201 if (!urlData.isEmpty()) {
2202 loadUrlDataIn(tab, urlData);
2203 }
2204 }
2205 };
2206
2207 GoogleAccountLogin.startLoginIfNeeded(mActivity, mSettings, load);
Michael Kolb8233fac2010-10-26 16:08:53 -07002208 return tab;
2209 } else {
2210 // Get rid of the subwindow if it exists
2211 dismissSubWindow(currentTab);
2212 if (!urlData.isEmpty()) {
2213 // Load the given url.
2214 loadUrlDataIn(currentTab, urlData);
2215 }
2216 return currentTab;
2217 }
2218 }
2219
Michael Kolb8233fac2010-10-26 16:08:53 -07002220 @Override
2221 public Tab openIncognitoTab() {
2222 if (mTabControl.canCreateNewTab()) {
2223 Tab currentTab = mTabControl.getCurrentTab();
Michael Kolb8e7178d2011-01-26 19:13:36 -08002224 Tab tab = mTabControl.createNewTab(false, null,
John Reck4bfc0db2011-01-27 17:47:12 -08002225 null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07002226 addTab(tab);
2227 setActiveTab(tab);
John Reck4bfc0db2011-01-27 17:47:12 -08002228 loadUrlDataIn(tab, new UrlData("browser:incognito"));
Michael Kolb8233fac2010-10-26 16:08:53 -07002229 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002230 } else {
2231 mUi.showMaxTabsWarning();
2232 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002233 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002234 }
2235
2236 /**
2237 * @param index Index of the tab to change to, as defined by
2238 * mTabControl.getTabIndex(Tab t).
2239 * @return boolean True if we successfully switched to a different tab. If
2240 * the indexth tab is null, or if that tab is the same as
2241 * the current one, return false.
2242 */
2243 @Override
2244 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002245 // hide combo view if open
2246 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002247 Tab tab = mTabControl.getTab(index);
2248 Tab currentTab = mTabControl.getCurrentTab();
2249 if (tab == null || tab == currentTab) {
2250 return false;
2251 }
2252 setActiveTab(tab);
2253 return true;
2254 }
2255
2256 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002257 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002258 // hide combo view if open
2259 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002260 final Tab current = mTabControl.getCurrentTab();
2261 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002262 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002263 return;
2264 }
2265 final Tab parent = current.getParentTab();
2266 int indexToShow = -1;
2267 if (parent != null) {
2268 indexToShow = mTabControl.getTabIndex(parent);
2269 } else {
2270 final int currentIndex = mTabControl.getCurrentIndex();
2271 // Try to move to the tab to the right
2272 indexToShow = currentIndex + 1;
2273 if (indexToShow > mTabControl.getTabCount() - 1) {
2274 // Try to move to the tab to the left
2275 indexToShow = currentIndex - 1;
2276 }
2277 }
2278 if (switchToTab(indexToShow)) {
2279 // Close window
2280 closeTab(current);
2281 }
2282 }
2283
2284 /**
2285 * Close the tab, remove its associated title bar, and adjust mTabControl's
2286 * current tab to a valid value.
2287 */
2288 @Override
2289 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002290 // hide combo view if open
2291 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002292 int currentIndex = mTabControl.getCurrentIndex();
2293 int removeIndex = mTabControl.getTabIndex(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002294 Tab newtab = mTabControl.getTab(currentIndex);
2295 setActiveTab(newtab);
Michael Kolb2d59c322011-01-25 13:18:55 -08002296 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002297 }
2298
2299 /**************** TODO: Url loading clean up *******************************/
2300
2301 // Called when loading from context menu or LOAD_URL message
2302 protected void loadUrlFromContext(WebView view, String url) {
2303 // In case the user enters nothing.
2304 if (url != null && url.length() != 0 && view != null) {
2305 url = UrlUtils.smartUrlFilter(url);
2306 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2307 loadUrl(view, url);
2308 }
2309 }
2310 }
2311
2312 /**
2313 * Load the URL into the given WebView and update the title bar
2314 * to reflect the new load. Call this instead of WebView.loadUrl
2315 * directly.
2316 * @param view The WebView used to load url.
2317 * @param url The URL to load.
2318 */
2319 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002320 view.loadUrl(url);
2321 }
2322
2323 /**
2324 * Load UrlData into a Tab and update the title bar to reflect the new
2325 * load. Call this instead of UrlData.loadIn directly.
2326 * @param t The Tab used to load.
2327 * @param data The UrlData being loaded.
2328 */
2329 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002330 data.loadIn(t);
2331 }
2332
John Reck30c714c2010-12-16 17:30:34 -08002333 @Override
2334 public void onUserCanceledSsl(Tab tab) {
2335 WebView web = tab.getWebView();
2336 // TODO: Figure out the "right" behavior
2337 if (web.canGoBack()) {
2338 web.goBack();
2339 } else {
2340 web.loadUrl(mSettings.getHomePage());
2341 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002342 }
2343
2344 void goBackOnePageOrQuit() {
2345 Tab current = mTabControl.getCurrentTab();
2346 if (current == null) {
2347 /*
2348 * Instead of finishing the activity, simply push this to the back
2349 * of the stack and let ActivityManager to choose the foreground
2350 * activity. As BrowserActivity is singleTask, it will be always the
2351 * root of the task. So we can use either true or false for
2352 * moveTaskToBack().
2353 */
2354 mActivity.moveTaskToBack(true);
2355 return;
2356 }
2357 WebView w = current.getWebView();
2358 if (w.canGoBack()) {
2359 w.goBack();
2360 } else {
2361 // Check to see if we are closing a window that was created by
2362 // another window. If so, we switch back to that window.
2363 Tab parent = current.getParentTab();
2364 if (parent != null) {
2365 switchToTab(mTabControl.getTabIndex(parent));
2366 // Now we close the other tab
2367 closeTab(current);
2368 } else {
2369 if (current.closeOnExit()) {
2370 // force the tab's inLoad() to be false as we are going to
2371 // either finish the activity or remove the tab. This will
2372 // ensure pauseWebViewTimers() taking action.
Michael Kolb70976932010-11-30 11:34:01 -08002373 current.clearInPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07002374 if (mTabControl.getTabCount() == 1) {
2375 mActivity.finish();
2376 return;
2377 }
2378 if (mActivityPaused) {
2379 Log.e(LOGTAG, "BrowserActivity is already paused "
2380 + "while handing goBackOnePageOrQuit.");
2381 }
Michael Kolb70976932010-11-30 11:34:01 -08002382 pauseWebViewTimers(current);
Michael Kolb96683f72011-02-15 14:24:35 -08002383 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002384 }
2385 /*
2386 * Instead of finishing the activity, simply push this to the back
2387 * of the stack and let ActivityManager to choose the foreground
2388 * activity. As BrowserActivity is singleTask, it will be always the
2389 * root of the task. So we can use either true or false for
2390 * moveTaskToBack().
2391 */
2392 mActivity.moveTaskToBack(true);
2393 }
2394 }
2395 }
2396
2397 /**
2398 * Feed the previously stored results strings to the BrowserProvider so that
2399 * the SearchDialog will show them instead of the standard searches.
2400 * @param result String to show on the editable line of the SearchDialog.
2401 */
2402 @Override
2403 public void showVoiceSearchResults(String result) {
2404 ContentProviderClient client = mActivity.getContentResolver()
2405 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2406 ContentProvider prov = client.getLocalContentProvider();
2407 BrowserProvider bp = (BrowserProvider) prov;
2408 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2409 client.release();
2410
2411 Bundle bundle = createGoogleSearchSourceBundle(
2412 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2413 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2414 startSearch(result, false, bundle, false);
2415 }
2416
2417 private void startSearch(String initialQuery, boolean selectInitialQuery,
2418 Bundle appSearchData, boolean globalSearch) {
2419 if (appSearchData == null) {
2420 appSearchData = createGoogleSearchSourceBundle(
2421 GOOGLE_SEARCH_SOURCE_TYPE);
2422 }
2423
2424 SearchEngine searchEngine = mSettings.getSearchEngine();
2425 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2426 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2427 }
2428 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2429 globalSearch);
2430 }
2431
2432 private Bundle createGoogleSearchSourceBundle(String source) {
2433 Bundle bundle = new Bundle();
2434 bundle.putString(Search.SOURCE, source);
2435 return bundle;
2436 }
2437
2438 /**
2439 * handle key events in browser
2440 *
2441 * @param keyCode
2442 * @param event
2443 * @return true if handled, false to pass to super
2444 */
2445 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002446 boolean noModifiers = event.hasNoModifiers();
2447
Michael Kolb8233fac2010-10-26 16:08:53 -07002448 // Even if MENU is already held down, we need to call to super to open
2449 // the IME on long press.
Cary Clark160bbb92011-01-10 11:17:07 -05002450 if (!noModifiers && KeyEvent.KEYCODE_MENU == keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002451 mMenuIsDown = true;
2452 return false;
2453 }
2454 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2455 // still down, we don't want to trigger the search. Pretend to consume
2456 // the key and do nothing.
2457 if (mMenuIsDown) return true;
2458
Cary Clark8ff8c662010-12-29 15:03:05 -05002459 WebView webView = getCurrentTopWebView();
2460 if (webView == null) return false;
2461
Cary Clark160bbb92011-01-10 11:17:07 -05002462 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2463 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002464
Michael Kolb8233fac2010-10-26 16:08:53 -07002465 switch(keyCode) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002466 case KeyEvent.KEYCODE_ESCAPE:
Cary Clark160bbb92011-01-10 11:17:07 -05002467 if (!noModifiers) break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002468 stopLoading();
2469 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07002470 case KeyEvent.KEYCODE_SPACE:
2471 // WebView/WebTextView handle the keys in the KeyDown. As
2472 // the Activity's shortcut keys are only handled when WebView
2473 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002474 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002475 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002476 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002477 pageDown();
2478 }
2479 return true;
2480 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002481 if (!noModifiers) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002482 if (event.getRepeatCount() == 0) {
2483 event.startTracking();
2484 return true;
2485 } else if (mUi.showsWeb()
2486 && event.isLongPress()) {
2487 bookmarksOrHistoryPicker(true);
2488 return true;
2489 }
2490 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002491 case KeyEvent.KEYCODE_DPAD_LEFT:
2492 if (ctrl) {
2493 webView.goBack();
2494 return true;
2495 }
2496 break;
2497 case KeyEvent.KEYCODE_DPAD_RIGHT:
2498 if (ctrl) {
2499 webView.goForward();
2500 return true;
2501 }
2502 break;
2503 case KeyEvent.KEYCODE_A:
2504 if (ctrl) {
2505 webView.selectAll();
2506 return true;
2507 }
2508 break;
Michael Kolba4183062011-01-16 10:43:21 -08002509// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002510 case KeyEvent.KEYCODE_C:
2511 if (ctrl) {
2512 webView.copySelection();
2513 return true;
2514 }
2515 break;
Michael Kolba4183062011-01-16 10:43:21 -08002516// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002517// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002518// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002519// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002520// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002521// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002522// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002523// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002524// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002525// case KeyEvent.KEYCODE_M: // unused
2526// case KeyEvent.KEYCODE_N: // in Chrome: new window
2527// case KeyEvent.KEYCODE_O: // in Chrome: open file
2528// case KeyEvent.KEYCODE_P: // in Chrome: print page
2529// case KeyEvent.KEYCODE_Q: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002530// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002531// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2532 case KeyEvent.KEYCODE_T:
2533 if (ctrl) {
2534 if (event.isShiftPressed()) {
2535 openIncognitoTab();
2536 } else {
2537 openTabToHomePage();
2538 }
2539 return true;
2540 }
2541 break;
2542// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2543// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolba4183062011-01-16 10:43:21 -08002544// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002545// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2546// case KeyEvent.KEYCODE_Y: // unused
2547// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002548 }
Michael Kolba4183062011-01-16 10:43:21 -08002549 // if we get here, it is a regular key and webview is not null
2550 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002551 }
2552
2553 boolean onKeyUp(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002554 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002555 switch(keyCode) {
2556 case KeyEvent.KEYCODE_MENU:
2557 mMenuIsDown = false;
2558 break;
2559 case KeyEvent.KEYCODE_BACK:
2560 if (event.isTracking() && !event.isCanceled()) {
2561 onBackKey();
2562 return true;
2563 }
2564 break;
2565 }
2566 return false;
2567 }
2568
2569 public boolean isMenuDown() {
2570 return mMenuIsDown;
2571 }
2572
Ben Murdoch8029a772010-11-16 11:58:21 +00002573 public void setupAutoFill(Message message) {
2574 // Open the settings activity at the AutoFill profile fragment so that
2575 // the user can create a new profile. When they return, we will dispatch
2576 // the message so that we can autofill the form using their new profile.
2577 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2578 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2579 AutoFillSettingsFragment.class.getName());
2580 mAutoFillSetupMessage = message;
2581 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2582 }
John Reckb3417f02011-01-14 11:01:05 -08002583
2584 @Override
2585 public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
2586 mOptionsMenuHandler = handler;
2587 }
2588
2589 @Override
2590 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
2591 if (mOptionsMenuHandler == handler) {
2592 mOptionsMenuHandler = null;
2593 }
2594 }
2595
Michael Kolb8233fac2010-10-26 16:08:53 -07002596}