blob: 745a0f4ba5a8a3ead92563184237751c03b09ed6 [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
1470 break;
1471 }
1472 mCurrentMenuState = mMenuState;
1473 return true;
1474 }
1475
1476 public boolean onOptionsItemSelected(MenuItem item) {
John Reckb3417f02011-01-14 11:01:05 -08001477 if (mOptionsMenuHandler != null &&
1478 mOptionsMenuHandler.onOptionsItemSelected(item)) {
1479 return true;
1480 }
1481
Michael Kolb8233fac2010-10-26 16:08:53 -07001482 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1483 // menu remains active, so ensure comboview is dismissed
1484 // if main menu option is selected
1485 removeComboView();
1486 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001487 if (!mCanChord) {
1488 // The user has already fired a shortcut with this hold down of the
1489 // menu key.
1490 return false;
1491 }
1492 if (null == getCurrentTopWebView()) {
1493 return false;
1494 }
1495 if (mMenuIsDown) {
1496 // The shortcut action consumes the MENU. Even if it is still down,
1497 // it won't trigger the next shortcut action. In the case of the
1498 // shortcut action triggering a new activity, like Bookmarks, we
1499 // won't get onKeyUp for MENU. So it is important to reset it here.
1500 mMenuIsDown = false;
1501 }
1502 switch (item.getItemId()) {
1503 // -- Main menu
1504 case R.id.new_tab_menu_id:
1505 openTabToHomePage();
1506 break;
1507
1508 case R.id.incognito_menu_id:
1509 openIncognitoTab();
1510 break;
1511
1512 case R.id.goto_menu_id:
1513 editUrl();
1514 break;
1515
1516 case R.id.bookmarks_menu_id:
1517 bookmarksOrHistoryPicker(false);
1518 break;
1519
1520 case R.id.active_tabs_menu_id:
1521 showActiveTabsPage();
1522 break;
1523
1524 case R.id.add_bookmark_menu_id:
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001525 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001526 break;
1527
1528 case R.id.stop_reload_menu_id:
1529 if (mInLoad) {
1530 stopLoading();
1531 } else {
1532 getCurrentTopWebView().reload();
1533 }
1534 break;
1535
1536 case R.id.back_menu_id:
1537 getCurrentTopWebView().goBack();
1538 break;
1539
1540 case R.id.forward_menu_id:
1541 getCurrentTopWebView().goForward();
1542 break;
1543
1544 case R.id.close_menu_id:
1545 // Close the subwindow if it exists.
1546 if (mTabControl.getCurrentSubWindow() != null) {
1547 dismissSubWindow(mTabControl.getCurrentTab());
1548 break;
1549 }
1550 closeCurrentTab();
1551 break;
1552
1553 case R.id.homepage_menu_id:
1554 Tab current = mTabControl.getCurrentTab();
1555 if (current != null) {
1556 dismissSubWindow(current);
1557 loadUrl(current.getWebView(), mSettings.getHomePage());
1558 }
1559 break;
1560
1561 case R.id.preferences_menu_id:
1562 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1563 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1564 getCurrentTopWebView().getUrl());
1565 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1566 break;
1567
1568 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001569 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001570 break;
1571
Leon Scrogginsac993842011-02-02 12:54:07 -05001572 case R.id.save_webarchive_menu_id:
1573 String state = Environment.getExternalStorageState();
1574 if (!Environment.MEDIA_MOUNTED.equals(state)) {
1575 Log.e(LOGTAG, "External storage not mounted");
1576 Toast.makeText(mActivity, R.string.webarchive_failed,
1577 Toast.LENGTH_SHORT).show();
1578 break;
1579 }
1580 final String directory = Environment.getExternalStoragePublicDirectory(
1581 Environment.DIRECTORY_DOWNLOADS) + File.separator;
1582 File dir = new File(directory);
1583 if (!dir.exists() && !dir.mkdirs()) {
1584 Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
1585 Toast.makeText(mActivity, R.string.webarchive_failed,
1586 Toast.LENGTH_SHORT).show();
1587 break;
1588 }
1589 WebView topWebView = getCurrentTopWebView();
1590 final String title = topWebView.getTitle();
1591 topWebView.saveWebArchive(directory, true,
1592 new ValueCallback<String>() {
1593 @Override
1594 public void onReceiveValue(final String value) {
1595 if (value != null) {
1596 File file = new File(value);
1597 final long length = file.length();
1598 if (file.exists() && length > 0) {
Leon Scroggins1cb96552011-02-11 14:22:57 -05001599 Toast.makeText(mActivity, R.string.webarchive_saved,
1600 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001601 final DownloadManager manager = (DownloadManager) mActivity
1602 .getSystemService(Context.DOWNLOAD_SERVICE);
1603 new Thread("Add WebArchive to download manager") {
1604 @Override
1605 public void run() {
1606 manager.completedDownload(null == title ? value : title,
1607 value, true, "application/x-webarchive-xml",
1608 value, length, true);
1609 }
1610 }.start();
1611 return;
1612 }
1613 }
1614 Toast.makeText(mActivity,
1615 R.string.webarchive_failed, Toast.LENGTH_SHORT).show();
1616 }
1617 });
1618 break;
1619
Michael Kolb8233fac2010-10-26 16:08:53 -07001620 case R.id.page_info_menu_id:
1621 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1622 false);
1623 break;
1624
1625 case R.id.classic_history_menu_id:
1626 bookmarksOrHistoryPicker(true);
1627 break;
1628
1629 case R.id.title_bar_share_page_url:
1630 case R.id.share_page_menu_id:
1631 Tab currentTab = mTabControl.getCurrentTab();
1632 if (null == currentTab) {
1633 mCanChord = false;
1634 return false;
1635 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001636 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001637 break;
1638
1639 case R.id.dump_nav_menu_id:
1640 getCurrentTopWebView().debugDump();
1641 break;
1642
1643 case R.id.dump_counters_menu_id:
1644 getCurrentTopWebView().dumpV8Counters();
1645 break;
1646
1647 case R.id.zoom_in_menu_id:
1648 getCurrentTopWebView().zoomIn();
1649 break;
1650
1651 case R.id.zoom_out_menu_id:
1652 getCurrentTopWebView().zoomOut();
1653 break;
1654
1655 case R.id.view_downloads_menu_id:
1656 viewDownloads();
1657 break;
1658
1659 case R.id.window_one_menu_id:
1660 case R.id.window_two_menu_id:
1661 case R.id.window_three_menu_id:
1662 case R.id.window_four_menu_id:
1663 case R.id.window_five_menu_id:
1664 case R.id.window_six_menu_id:
1665 case R.id.window_seven_menu_id:
1666 case R.id.window_eight_menu_id:
1667 {
1668 int menuid = item.getItemId();
1669 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1670 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1671 Tab desiredTab = mTabControl.getTab(id);
1672 if (desiredTab != null &&
1673 desiredTab != mTabControl.getCurrentTab()) {
1674 switchToTab(id);
1675 }
1676 break;
1677 }
1678 }
1679 }
1680 break;
1681
1682 default:
1683 return false;
1684 }
1685 mCanChord = false;
1686 return true;
1687 }
1688
1689 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001690 // Let the History and Bookmark fragments handle menus they created.
1691 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1692 return false;
1693 }
1694
Michael Kolb8233fac2010-10-26 16:08:53 -07001695 // chording is not an issue with context menus, but we use the same
1696 // options selector, so set mCanChord to true so we can access them.
1697 mCanChord = true;
1698 int id = item.getItemId();
1699 boolean result = true;
1700 switch (id) {
1701 // For the context menu from the title bar
1702 case R.id.title_bar_copy_page_url:
1703 Tab currentTab = mTabControl.getCurrentTab();
1704 if (null == currentTab) {
1705 result = false;
1706 break;
1707 }
1708 WebView mainView = currentTab.getWebView();
1709 if (null == mainView) {
1710 result = false;
1711 break;
1712 }
1713 copy(mainView.getUrl());
1714 break;
1715 // -- Browser context menu
1716 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001717 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001718 case R.id.copy_link_context_menu_id:
1719 final WebView webView = getCurrentTopWebView();
1720 if (null == webView) {
1721 result = false;
1722 break;
1723 }
1724 final HashMap<String, WebView> hrefMap =
1725 new HashMap<String, WebView>();
1726 hrefMap.put("webview", webView);
1727 final Message msg = mHandler.obtainMessage(
1728 FOCUS_NODE_HREF, id, 0, hrefMap);
1729 webView.requestFocusNodeHref(msg);
1730 break;
1731
1732 default:
1733 // For other context menus
1734 result = onOptionsItemSelected(item);
1735 }
1736 mCanChord = false;
1737 return result;
1738 }
1739
1740 /**
1741 * support programmatically opening the context menu
1742 */
1743 public void openContextMenu(View view) {
1744 mActivity.openContextMenu(view);
1745 }
1746
1747 /**
1748 * programmatically open the options menu
1749 */
1750 public void openOptionsMenu() {
1751 mActivity.openOptionsMenu();
1752 }
1753
1754 public boolean onMenuOpened(int featureId, Menu menu) {
1755 if (mOptionsMenuOpen) {
1756 if (mConfigChanged) {
1757 // We do not need to make any changes to the state of the
1758 // title bar, since the only thing that happened was a
1759 // change in orientation
1760 mConfigChanged = false;
1761 } else {
1762 if (!mExtendedMenuOpen) {
1763 mExtendedMenuOpen = true;
1764 mUi.onExtendedMenuOpened();
1765 } else {
1766 // Switching the menu back to icon view, so show the
1767 // title bar once again.
1768 mExtendedMenuOpen = false;
1769 mUi.onExtendedMenuClosed(mInLoad);
1770 mUi.onOptionsMenuOpened();
1771 }
1772 }
1773 } else {
1774 // The options menu is closed, so open it, and show the title
1775 mOptionsMenuOpen = true;
1776 mConfigChanged = false;
1777 mExtendedMenuOpen = false;
1778 mUi.onOptionsMenuOpened();
1779 }
1780 return true;
1781 }
1782
1783 public void onOptionsMenuClosed(Menu menu) {
1784 mOptionsMenuOpen = false;
1785 mUi.onOptionsMenuClosed(mInLoad);
1786 }
1787
1788 public void onContextMenuClosed(Menu menu) {
1789 mUi.onContextMenuClosed(menu, mInLoad);
1790 }
1791
1792 // Helper method for getting the top window.
1793 @Override
1794 public WebView getCurrentTopWebView() {
1795 return mTabControl.getCurrentTopWebView();
1796 }
1797
1798 @Override
1799 public WebView getCurrentWebView() {
1800 return mTabControl.getCurrentWebView();
1801 }
1802
1803 /*
1804 * This method is called as a result of the user selecting the options
1805 * menu to see the download window. It shows the download window on top of
1806 * the current window.
1807 */
1808 void viewDownloads() {
1809 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1810 mActivity.startActivity(intent);
1811 }
1812
1813 // action mode
1814
1815 void onActionModeStarted(ActionMode mode) {
1816 mUi.onActionModeStarted(mode);
1817 mActionMode = mode;
1818 }
1819
1820 /*
1821 * True if a custom ActionMode (i.e. find or select) is in use.
1822 */
1823 @Override
1824 public boolean isInCustomActionMode() {
1825 return mActionMode != null;
1826 }
1827
1828 /*
1829 * End the current ActionMode.
1830 */
1831 @Override
1832 public void endActionMode() {
1833 if (mActionMode != null) {
1834 mActionMode.finish();
1835 }
1836 }
1837
1838 /*
1839 * Called by find and select when they are finished. Replace title bars
1840 * as necessary.
1841 */
1842 public void onActionModeFinished(ActionMode mode) {
1843 if (!isInCustomActionMode()) return;
1844 mUi.onActionModeFinished(mInLoad);
1845 mActionMode = null;
1846 }
1847
1848 boolean isInLoad() {
1849 return mInLoad;
1850 }
1851
1852 // bookmark handling
1853
1854 /**
1855 * add the current page as a bookmark to the given folder id
1856 * @param folderId use -1 for the default folder
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001857 * @param canBeAnEdit If true, check to see whether the site is already
1858 * bookmarked, and if it is, edit that bookmark. If false, and
1859 * the site is already bookmarked, do not attempt to edit the
1860 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001861 */
1862 @Override
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001863 public void bookmarkCurrentPage(long folderId, boolean canBeAnEdit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001864 Intent i = new Intent(mActivity,
1865 AddBookmarkPage.class);
1866 WebView w = getCurrentTopWebView();
1867 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1868 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1869 String touchIconUrl = w.getTouchIconUrl();
1870 if (touchIconUrl != null) {
1871 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1872 WebSettings settings = w.getSettings();
1873 if (settings != null) {
1874 i.putExtra(AddBookmarkPage.USER_AGENT,
1875 settings.getUserAgentString());
1876 }
1877 }
1878 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1879 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1880 getDesiredThumbnailHeight(mActivity)));
1881 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1882 i.putExtra(BrowserContract.Bookmarks.PARENT,
1883 folderId);
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001884 if (canBeAnEdit) {
1885 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1886 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001887 // Put the dialog at the upper right of the screen, covering the
1888 // star on the title bar.
1889 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1890 mActivity.startActivity(i);
1891 }
1892
1893 // file chooser
1894 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1895 mUploadHandler = new UploadHandler(this);
1896 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1897 }
1898
1899 // thumbnails
1900
1901 /**
1902 * Return the desired width for thumbnail screenshots, which are stored in
1903 * the database, and used on the bookmarks screen.
1904 * @param context Context for finding out the density of the screen.
1905 * @return desired width for thumbnail screenshot.
1906 */
1907 static int getDesiredThumbnailWidth(Context context) {
1908 return context.getResources().getDimensionPixelOffset(
1909 R.dimen.bookmarkThumbnailWidth);
1910 }
1911
1912 /**
1913 * Return the desired height for thumbnail screenshots, which are stored in
1914 * the database, and used on the bookmarks screen.
1915 * @param context Context for finding out the density of the screen.
1916 * @return desired height for thumbnail screenshot.
1917 */
1918 static int getDesiredThumbnailHeight(Context context) {
1919 return context.getResources().getDimensionPixelOffset(
1920 R.dimen.bookmarkThumbnailHeight);
1921 }
1922
1923 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001924 // We render to a bitmap 2x the desired size so that we can then
1925 // re-scale it with filtering since canvas.scale doesn't filter
1926 // This helps reduce aliasing at the cost of being slightly blurry
1927 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001928 Picture thumbnail = view.capturePicture();
1929 if (thumbnail == null) {
1930 return null;
1931 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001932 width *= filter_scale;
1933 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001934 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1935 Canvas canvas = new Canvas(bm);
1936 // May need to tweak these values to determine what is the
1937 // best scale factor
1938 int thumbnailWidth = thumbnail.getWidth();
1939 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001940 float scaleFactor = 1.0f;
Michael Kolb8233fac2010-10-26 16:08:53 -07001941 if (thumbnailWidth > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001942 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001943 } else {
1944 return null;
1945 }
John Reckfe49ab42010-11-16 17:09:37 -08001946
Michael Kolb8233fac2010-10-26 16:08:53 -07001947 if (view.getWidth() > view.getHeight() &&
1948 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
1949 // If the device is in landscape and the page is shorter
John Reckfe49ab42010-11-16 17:09:37 -08001950 // than the height of the view, center the thumnail and crop the sides
1951 scaleFactor = (float) height / (float)thumbnailHeight;
1952 float wx = (thumbnailWidth * scaleFactor) - width;
1953 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001954 }
1955
John Reckfe49ab42010-11-16 17:09:37 -08001956 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001957
1958 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001959 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
1960 height / filter_scale, true);
1961 bm.recycle();
1962 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001963 }
1964
John Reck34ef2672011-02-10 11:30:55 -08001965 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001966 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07001967 // FIXME: Would like to make sure there is actually something to
1968 // draw, but the API for that (WebViewCore.pictureReady()) is not
1969 // currently accessible here.
1970
John Reck34ef2672011-02-10 11:30:55 -08001971 WebView view = tab.getWebView();
1972 final String url = tab.getUrl();
1973 final String originalUrl = view.getOriginalUrl();
1974
1975 if (TextUtils.isEmpty(url)) {
1976 return;
1977 }
1978
1979 // Only update thumbnails for web urls (http(s)://), not for
1980 // about:, javascript:, data:, etc...
1981 // Unless it is a bookmarked site, then always update
1982 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
1983 return;
1984 }
1985
Michael Kolb8233fac2010-10-26 16:08:53 -07001986 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1987 getDesiredThumbnailHeight(mActivity));
1988 if (bm == null) {
1989 return;
1990 }
1991
1992 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08001993 new AsyncTask<Void, Void, Void>() {
1994 @Override
1995 protected Void doInBackground(Void... unused) {
1996 Cursor cursor = null;
1997 try {
1998 // TODO: Clean this up
1999 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2000 if (cursor != null && cursor.moveToFirst()) {
2001 final ByteArrayOutputStream os =
2002 new ByteArrayOutputStream();
2003 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002004
John Reck34ef2672011-02-10 11:30:55 -08002005 ContentValues values = new ContentValues();
2006 values.put(Images.THUMBNAIL, os.toByteArray());
2007 values.put(Images.URL, cursor.getString(0));
Michael Kolb8233fac2010-10-26 16:08:53 -07002008
John Reck34ef2672011-02-10 11:30:55 -08002009 do {
2010 cr.update(Images.CONTENT_URI, values, null, null);
2011 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002012 }
John Reck34ef2672011-02-10 11:30:55 -08002013 } catch (IllegalStateException e) {
2014 // Ignore
2015 } finally {
2016 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002017 }
John Reck34ef2672011-02-10 11:30:55 -08002018 return null;
2019 }
2020 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002021 }
2022
2023 private class Copy implements OnMenuItemClickListener {
2024 private CharSequence mText;
2025
2026 public boolean onMenuItemClick(MenuItem item) {
2027 copy(mText);
2028 return true;
2029 }
2030
2031 public Copy(CharSequence toCopy) {
2032 mText = toCopy;
2033 }
2034 }
2035
Leon Scroggins63c02662010-11-18 15:16:27 -05002036 private static class Download implements OnMenuItemClickListener {
2037 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002038 private String mText;
2039
2040 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002041 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
2042 null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07002043 return true;
2044 }
2045
Leon Scroggins63c02662010-11-18 15:16:27 -05002046 public Download(Activity activity, String toDownload) {
2047 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002048 mText = toDownload;
2049 }
2050 }
2051
Cary Clark8974d282010-11-22 10:46:05 -05002052 private static class SelectText implements OnMenuItemClickListener {
2053 private WebView mWebView;
2054
2055 public boolean onMenuItemClick(MenuItem item) {
2056 if (mWebView != null) {
2057 return mWebView.selectText();
2058 }
2059 return false;
2060 }
2061
2062 public SelectText(WebView webView) {
2063 mWebView = webView;
2064 }
2065
2066 }
2067
Michael Kolb8233fac2010-10-26 16:08:53 -07002068 /********************** TODO: UI stuff *****************************/
2069
2070 // these methods have been copied, they still need to be cleaned up
2071
2072 /****************** tabs ***************************************************/
2073
2074 // basic tab interactions:
2075
2076 // it is assumed that tabcontrol already knows about the tab
2077 protected void addTab(Tab tab) {
2078 mUi.addTab(tab);
2079 }
2080
2081 protected void removeTab(Tab tab) {
2082 mUi.removeTab(tab);
2083 mTabControl.removeTab(tab);
2084 }
2085
2086 protected void setActiveTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002087 mTabControl.setCurrentTab(tab);
Michael Kolb77df4562010-11-19 14:49:34 -08002088 // the tab is guaranteed to have a webview after setCurrentTab
2089 mUi.setActiveTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002090 }
2091
2092 protected void closeEmptyChildTab() {
2093 Tab current = mTabControl.getCurrentTab();
2094 if (current != null
2095 && current.getWebView().copyBackForwardList().getSize() == 0) {
2096 Tab parent = current.getParentTab();
2097 if (parent != null) {
2098 switchToTab(mTabControl.getTabIndex(parent));
2099 closeTab(current);
2100 }
2101 }
2102 }
2103
2104 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002105 // Dismiss the subwindow if applicable.
2106 dismissSubWindow(appTab);
2107 // Since we might kill the WebView, remove it from the
2108 // content view first.
2109 mUi.detachTab(appTab);
2110 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002111 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002112 // TODO: analyze why the remove and add are necessary
2113 mUi.attachTab(appTab);
2114 if (mTabControl.getCurrentTab() != appTab) {
2115 switchToTab(mTabControl.getTabIndex(appTab));
John Reck30c714c2010-12-16 17:30:34 -08002116 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002117 } else {
2118 // If the tab was the current tab, we have to attach
2119 // it to the view system again.
2120 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002121 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002122 }
2123 }
2124
2125 // Remove the sub window if it exists. Also called by TabControl when the
2126 // user clicks the 'X' to dismiss a sub window.
2127 public void dismissSubWindow(Tab tab) {
2128 removeSubWindow(tab);
2129 // dismiss the subwindow. This will destroy the WebView.
2130 tab.dismissSubWindow();
2131 getCurrentTopWebView().requestFocus();
2132 }
2133
2134 @Override
2135 public void removeSubWindow(Tab t) {
2136 if (t.getSubWebView() != null) {
2137 mUi.removeSubWindow(t.getSubViewContainer());
2138 }
2139 }
2140
2141 @Override
2142 public void attachSubWindow(Tab tab) {
2143 if (tab.getSubWebView() != null) {
2144 mUi.attachSubWindow(tab.getSubViewContainer());
2145 getCurrentTopWebView().requestFocus();
2146 }
2147 }
2148
Michael Kolb843510f2010-12-09 10:51:49 -08002149 @Override
2150 public Tab openTabToHomePage() {
2151 // check for max tabs
2152 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002153 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2154 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002155 } else {
2156 mUi.showMaxTabsWarning();
2157 return null;
2158 }
2159 }
2160
Michael Kolb18eb3772010-12-10 14:29:51 -08002161 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2162 if (mSettings.openInBackground() && !forceForeground) {
2163 Tab tab = mTabControl.createNewTab(false, null, null,
2164 (parent != null) && parent.isPrivateBrowsingEnabled());
2165 if (tab != null) {
2166 addTab(tab);
2167 WebView view = tab.getWebView();
2168 loadUrl(view, url);
2169 }
2170 return tab;
2171 } else {
2172 return openTabAndShow(parent, new UrlData(url), false, null);
2173 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002174 }
2175
Michael Kolb18eb3772010-12-10 14:29:51 -08002176
Michael Kolb8233fac2010-10-26 16:08:53 -07002177 // This method does a ton of stuff. It will attempt to create a new tab
2178 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2179 // url isn't null, it will load the given url.
Patrick Scottcd135082011-01-31 18:21:58 -05002180 public Tab openTabAndShow(Tab parent, final UrlData urlData,
2181 boolean closeOnExit, String appId) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002182 final Tab currentTab = mTabControl.getCurrentTab();
2183 if (mTabControl.canCreateNewTab()) {
2184 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Michael Kolb18eb3772010-12-10 14:29:51 -08002185 urlData.mUrl,
2186 (parent != null) && parent.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -07002187 WebView webview = tab.getWebView();
2188 // We must set the new tab as the current tab to reflect the old
2189 // animation behavior.
2190 addTab(tab);
2191 setActiveTab(tab);
Patrick Scottcd135082011-01-31 18:21:58 -05002192
2193 // Callback to load the url data.
2194 final Runnable load = new Runnable() {
2195 @Override public void run() {
2196 if (!urlData.isEmpty()) {
2197 loadUrlDataIn(tab, urlData);
2198 }
2199 }
2200 };
2201
2202 GoogleAccountLogin.startLoginIfNeeded(mActivity, mSettings, load);
Michael Kolb8233fac2010-10-26 16:08:53 -07002203 return tab;
2204 } else {
2205 // Get rid of the subwindow if it exists
2206 dismissSubWindow(currentTab);
2207 if (!urlData.isEmpty()) {
2208 // Load the given url.
2209 loadUrlDataIn(currentTab, urlData);
2210 }
2211 return currentTab;
2212 }
2213 }
2214
Michael Kolb8233fac2010-10-26 16:08:53 -07002215 @Override
2216 public Tab openIncognitoTab() {
2217 if (mTabControl.canCreateNewTab()) {
2218 Tab currentTab = mTabControl.getCurrentTab();
Michael Kolb8e7178d2011-01-26 19:13:36 -08002219 Tab tab = mTabControl.createNewTab(false, null,
John Reck4bfc0db2011-01-27 17:47:12 -08002220 null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07002221 addTab(tab);
2222 setActiveTab(tab);
John Reck4bfc0db2011-01-27 17:47:12 -08002223 loadUrlDataIn(tab, new UrlData("browser:incognito"));
Michael Kolb8233fac2010-10-26 16:08:53 -07002224 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002225 } else {
2226 mUi.showMaxTabsWarning();
2227 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002228 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002229 }
2230
2231 /**
2232 * @param index Index of the tab to change to, as defined by
2233 * mTabControl.getTabIndex(Tab t).
2234 * @return boolean True if we successfully switched to a different tab. If
2235 * the indexth tab is null, or if that tab is the same as
2236 * the current one, return false.
2237 */
2238 @Override
2239 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002240 // hide combo view if open
2241 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002242 Tab tab = mTabControl.getTab(index);
2243 Tab currentTab = mTabControl.getCurrentTab();
2244 if (tab == null || tab == currentTab) {
2245 return false;
2246 }
2247 setActiveTab(tab);
2248 return true;
2249 }
2250
2251 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002252 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002253 // hide combo view if open
2254 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002255 final Tab current = mTabControl.getCurrentTab();
2256 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002257 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002258 return;
2259 }
2260 final Tab parent = current.getParentTab();
2261 int indexToShow = -1;
2262 if (parent != null) {
2263 indexToShow = mTabControl.getTabIndex(parent);
2264 } else {
2265 final int currentIndex = mTabControl.getCurrentIndex();
2266 // Try to move to the tab to the right
2267 indexToShow = currentIndex + 1;
2268 if (indexToShow > mTabControl.getTabCount() - 1) {
2269 // Try to move to the tab to the left
2270 indexToShow = currentIndex - 1;
2271 }
2272 }
2273 if (switchToTab(indexToShow)) {
2274 // Close window
2275 closeTab(current);
2276 }
2277 }
2278
2279 /**
2280 * Close the tab, remove its associated title bar, and adjust mTabControl's
2281 * current tab to a valid value.
2282 */
2283 @Override
2284 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002285 // hide combo view if open
2286 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002287 int currentIndex = mTabControl.getCurrentIndex();
2288 int removeIndex = mTabControl.getTabIndex(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002289 Tab newtab = mTabControl.getTab(currentIndex);
2290 setActiveTab(newtab);
Michael Kolb2d59c322011-01-25 13:18:55 -08002291 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002292 }
2293
2294 /**************** TODO: Url loading clean up *******************************/
2295
2296 // Called when loading from context menu or LOAD_URL message
2297 protected void loadUrlFromContext(WebView view, String url) {
2298 // In case the user enters nothing.
2299 if (url != null && url.length() != 0 && view != null) {
2300 url = UrlUtils.smartUrlFilter(url);
2301 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2302 loadUrl(view, url);
2303 }
2304 }
2305 }
2306
2307 /**
2308 * Load the URL into the given WebView and update the title bar
2309 * to reflect the new load. Call this instead of WebView.loadUrl
2310 * directly.
2311 * @param view The WebView used to load url.
2312 * @param url The URL to load.
2313 */
2314 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002315 view.loadUrl(url);
2316 }
2317
2318 /**
2319 * Load UrlData into a Tab and update the title bar to reflect the new
2320 * load. Call this instead of UrlData.loadIn directly.
2321 * @param t The Tab used to load.
2322 * @param data The UrlData being loaded.
2323 */
2324 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002325 data.loadIn(t);
2326 }
2327
John Reck30c714c2010-12-16 17:30:34 -08002328 @Override
2329 public void onUserCanceledSsl(Tab tab) {
2330 WebView web = tab.getWebView();
2331 // TODO: Figure out the "right" behavior
2332 if (web.canGoBack()) {
2333 web.goBack();
2334 } else {
2335 web.loadUrl(mSettings.getHomePage());
2336 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002337 }
2338
2339 void goBackOnePageOrQuit() {
2340 Tab current = mTabControl.getCurrentTab();
2341 if (current == null) {
2342 /*
2343 * Instead of finishing the activity, simply push this to the back
2344 * of the stack and let ActivityManager to choose the foreground
2345 * activity. As BrowserActivity is singleTask, it will be always the
2346 * root of the task. So we can use either true or false for
2347 * moveTaskToBack().
2348 */
2349 mActivity.moveTaskToBack(true);
2350 return;
2351 }
2352 WebView w = current.getWebView();
2353 if (w.canGoBack()) {
2354 w.goBack();
2355 } else {
2356 // Check to see if we are closing a window that was created by
2357 // another window. If so, we switch back to that window.
2358 Tab parent = current.getParentTab();
2359 if (parent != null) {
2360 switchToTab(mTabControl.getTabIndex(parent));
2361 // Now we close the other tab
2362 closeTab(current);
2363 } else {
2364 if (current.closeOnExit()) {
2365 // force the tab's inLoad() to be false as we are going to
2366 // either finish the activity or remove the tab. This will
2367 // ensure pauseWebViewTimers() taking action.
Michael Kolb70976932010-11-30 11:34:01 -08002368 current.clearInPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07002369 if (mTabControl.getTabCount() == 1) {
2370 mActivity.finish();
2371 return;
2372 }
2373 if (mActivityPaused) {
2374 Log.e(LOGTAG, "BrowserActivity is already paused "
2375 + "while handing goBackOnePageOrQuit.");
2376 }
Michael Kolb70976932010-11-30 11:34:01 -08002377 pauseWebViewTimers(current);
Michael Kolb8233fac2010-10-26 16:08:53 -07002378 removeTab(current);
2379 }
2380 /*
2381 * Instead of finishing the activity, simply push this to the back
2382 * of the stack and let ActivityManager to choose the foreground
2383 * activity. As BrowserActivity is singleTask, it will be always the
2384 * root of the task. So we can use either true or false for
2385 * moveTaskToBack().
2386 */
2387 mActivity.moveTaskToBack(true);
2388 }
2389 }
2390 }
2391
2392 /**
2393 * Feed the previously stored results strings to the BrowserProvider so that
2394 * the SearchDialog will show them instead of the standard searches.
2395 * @param result String to show on the editable line of the SearchDialog.
2396 */
2397 @Override
2398 public void showVoiceSearchResults(String result) {
2399 ContentProviderClient client = mActivity.getContentResolver()
2400 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2401 ContentProvider prov = client.getLocalContentProvider();
2402 BrowserProvider bp = (BrowserProvider) prov;
2403 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2404 client.release();
2405
2406 Bundle bundle = createGoogleSearchSourceBundle(
2407 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2408 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2409 startSearch(result, false, bundle, false);
2410 }
2411
2412 private void startSearch(String initialQuery, boolean selectInitialQuery,
2413 Bundle appSearchData, boolean globalSearch) {
2414 if (appSearchData == null) {
2415 appSearchData = createGoogleSearchSourceBundle(
2416 GOOGLE_SEARCH_SOURCE_TYPE);
2417 }
2418
2419 SearchEngine searchEngine = mSettings.getSearchEngine();
2420 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2421 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2422 }
2423 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2424 globalSearch);
2425 }
2426
2427 private Bundle createGoogleSearchSourceBundle(String source) {
2428 Bundle bundle = new Bundle();
2429 bundle.putString(Search.SOURCE, source);
2430 return bundle;
2431 }
2432
2433 /**
2434 * handle key events in browser
2435 *
2436 * @param keyCode
2437 * @param event
2438 * @return true if handled, false to pass to super
2439 */
2440 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002441 boolean noModifiers = event.hasNoModifiers();
2442
Michael Kolb8233fac2010-10-26 16:08:53 -07002443 // Even if MENU is already held down, we need to call to super to open
2444 // the IME on long press.
Cary Clark160bbb92011-01-10 11:17:07 -05002445 if (!noModifiers && KeyEvent.KEYCODE_MENU == keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002446 mMenuIsDown = true;
2447 return false;
2448 }
2449 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2450 // still down, we don't want to trigger the search. Pretend to consume
2451 // the key and do nothing.
2452 if (mMenuIsDown) return true;
2453
Cary Clark8ff8c662010-12-29 15:03:05 -05002454 WebView webView = getCurrentTopWebView();
2455 if (webView == null) return false;
2456
Cary Clark160bbb92011-01-10 11:17:07 -05002457 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2458 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002459
Michael Kolb8233fac2010-10-26 16:08:53 -07002460 switch(keyCode) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002461 case KeyEvent.KEYCODE_ESCAPE:
Cary Clark160bbb92011-01-10 11:17:07 -05002462 if (!noModifiers) break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002463 stopLoading();
2464 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07002465 case KeyEvent.KEYCODE_SPACE:
2466 // WebView/WebTextView handle the keys in the KeyDown. As
2467 // the Activity's shortcut keys are only handled when WebView
2468 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002469 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002470 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002471 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002472 pageDown();
2473 }
2474 return true;
2475 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002476 if (!noModifiers) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07002477 if (event.getRepeatCount() == 0) {
2478 event.startTracking();
2479 return true;
2480 } else if (mUi.showsWeb()
2481 && event.isLongPress()) {
2482 bookmarksOrHistoryPicker(true);
2483 return true;
2484 }
2485 break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002486 case KeyEvent.KEYCODE_DPAD_LEFT:
2487 if (ctrl) {
2488 webView.goBack();
2489 return true;
2490 }
2491 break;
2492 case KeyEvent.KEYCODE_DPAD_RIGHT:
2493 if (ctrl) {
2494 webView.goForward();
2495 return true;
2496 }
2497 break;
2498 case KeyEvent.KEYCODE_A:
2499 if (ctrl) {
2500 webView.selectAll();
2501 return true;
2502 }
2503 break;
Michael Kolba4183062011-01-16 10:43:21 -08002504// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002505 case KeyEvent.KEYCODE_C:
2506 if (ctrl) {
2507 webView.copySelection();
2508 return true;
2509 }
2510 break;
Michael Kolba4183062011-01-16 10:43:21 -08002511// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002512// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002513// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002514// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002515// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002516// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002517// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002518// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002519// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002520// case KeyEvent.KEYCODE_M: // unused
2521// case KeyEvent.KEYCODE_N: // in Chrome: new window
2522// case KeyEvent.KEYCODE_O: // in Chrome: open file
2523// case KeyEvent.KEYCODE_P: // in Chrome: print page
2524// case KeyEvent.KEYCODE_Q: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002525// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002526// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2527 case KeyEvent.KEYCODE_T:
2528 if (ctrl) {
2529 if (event.isShiftPressed()) {
2530 openIncognitoTab();
2531 } else {
2532 openTabToHomePage();
2533 }
2534 return true;
2535 }
2536 break;
2537// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2538// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolba4183062011-01-16 10:43:21 -08002539// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002540// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2541// case KeyEvent.KEYCODE_Y: // unused
2542// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002543 }
Michael Kolba4183062011-01-16 10:43:21 -08002544 // if we get here, it is a regular key and webview is not null
2545 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002546 }
2547
2548 boolean onKeyUp(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002549 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002550 switch(keyCode) {
2551 case KeyEvent.KEYCODE_MENU:
2552 mMenuIsDown = false;
2553 break;
2554 case KeyEvent.KEYCODE_BACK:
2555 if (event.isTracking() && !event.isCanceled()) {
2556 onBackKey();
2557 return true;
2558 }
2559 break;
2560 }
2561 return false;
2562 }
2563
2564 public boolean isMenuDown() {
2565 return mMenuIsDown;
2566 }
2567
Ben Murdoch8029a772010-11-16 11:58:21 +00002568 public void setupAutoFill(Message message) {
2569 // Open the settings activity at the AutoFill profile fragment so that
2570 // the user can create a new profile. When they return, we will dispatch
2571 // the message so that we can autofill the form using their new profile.
2572 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2573 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2574 AutoFillSettingsFragment.class.getName());
2575 mAutoFillSetupMessage = message;
2576 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2577 }
John Reckb3417f02011-01-14 11:01:05 -08002578
2579 @Override
2580 public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
2581 mOptionsMenuHandler = handler;
2582 }
2583
2584 @Override
2585 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
2586 if (mOptionsMenuHandler == handler) {
2587 mOptionsMenuHandler = null;
2588 }
2589 }
2590
Michael Kolb8233fac2010-10-26 16:08:53 -07002591}