blob: fd966de3d5a28a3dbb09d687f8860b8b5fb05f87 [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 {
Michael Kolbcd424e92011-02-24 10:26:26 -0800320 // monkey protection against delayed start
321 if (t != null) {
322 loadUrlDataIn(t, urlData);
323 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700324 }
325 } else {
Patrick Scott7d50a932011-02-04 09:27:26 -0500326 mTabControl.restoreState(icicle, currentTab, restoreIncognitoTabs,
327 mUi.needsRestoreAllTabs());
Michael Kolb1bf23132010-11-19 12:55:12 -0800328 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700329 // TabControl.restoreState() will create a new tab even if
330 // restoring the state fails.
331 setActiveTab(mTabControl.getCurrentTab());
332 }
333 // clear up the thumbnail directory, which is no longer used;
334 // ideally this should only be run once after an upgrade from
335 // a previous version of the browser
336 new ClearThumbnails().execute(mTabControl.getThumbnailDir()
337 .listFiles());
338 // Read JavaScript flags if it exists.
339 String jsFlags = getSettings().getJsFlags();
340 if (jsFlags.trim().length() != 0) {
341 getCurrentWebView().setJsFlags(jsFlags);
342 }
John Reck439c9a52010-12-14 10:04:39 -0800343 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
344 bookmarksOrHistoryPicker(false);
345 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700346 }
347
348 void setWebViewFactory(WebViewFactory factory) {
349 mFactory = factory;
350 }
351
Michael Kolb1514bb72010-11-22 09:11:48 -0800352 @Override
353 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700354 return mFactory;
355 }
356
357 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800358 public void onSetWebView(Tab tab, WebView view) {
359 mUi.onSetWebView(tab, view);
360 }
361
362 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800363 public void createSubWindow(Tab tab) {
364 endActionMode();
365 WebView mainView = tab.getWebView();
366 WebView subView = mFactory.createWebView((mainView == null)
367 ? false
368 : mainView.isPrivateBrowsingEnabled());
369 mUi.createSubWindow(tab, subView);
370 }
371
372 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700373 public Activity getActivity() {
374 return mActivity;
375 }
376
377 void setUi(UI ui) {
378 mUi = ui;
379 }
380
381 BrowserSettings getSettings() {
382 return mSettings;
383 }
384
385 IntentHandler getIntentHandler() {
386 return mIntentHandler;
387 }
388
389 @Override
390 public UI getUi() {
391 return mUi;
392 }
393
394 int getMaxTabs() {
395 return mActivity.getResources().getInteger(R.integer.max_tabs);
396 }
397
398 @Override
399 public TabControl getTabControl() {
400 return mTabControl;
401 }
402
Michael Kolb1bf23132010-11-19 12:55:12 -0800403 @Override
404 public List<Tab> getTabs() {
405 return mTabControl.getTabs();
406 }
407
Michael Kolb8233fac2010-10-26 16:08:53 -0700408 // Open the icon database and retain all the icons for visited sites.
Ben Murdoch9446b932010-11-25 16:20:14 +0000409 // This is done on a background thread so as not to stall startup.
Michael Kolb8233fac2010-10-26 16:08:53 -0700410 private void retainIconsOnStartup() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000411 // WebIconDatabase needs to be retrieved on the UI thread so that if
412 // it has not been created successfully yet the Handler is started on the
413 // UI thread.
414 new RetainIconsOnStartupTask(WebIconDatabase.getInstance()).execute();
415 }
416
417 private class RetainIconsOnStartupTask extends AsyncTask<Void, Void, Void> {
418 private WebIconDatabase mDb;
419
420 public RetainIconsOnStartupTask(WebIconDatabase db) {
421 mDb = db;
422 }
423
John Recka00cbbd2010-12-16 12:38:19 -0800424 @Override
Ben Murdoch9446b932010-11-25 16:20:14 +0000425 protected Void doInBackground(Void... unused) {
426 mDb.open(mActivity.getDir("icons", 0).getPath());
427 Cursor c = null;
428 try {
429 c = Browser.getAllBookmarks(mActivity.getContentResolver());
430 if (c.moveToFirst()) {
431 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
432 do {
433 String url = c.getString(urlIndex);
434 mDb.retainIconForPageUrl(url);
435 } while (c.moveToNext());
436 }
437 } catch (IllegalStateException e) {
438 Log.e(LOGTAG, "retainIconsOnStartup", e);
439 } finally {
440 if (c != null) c.close();
Michael Kolb8233fac2010-10-26 16:08:53 -0700441 }
Ben Murdoch9446b932010-11-25 16:20:14 +0000442
443 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700444 }
445 }
446
447 private void startHandler() {
448 mHandler = new Handler() {
449
450 @Override
451 public void handleMessage(Message msg) {
452 switch (msg.what) {
453 case OPEN_BOOKMARKS:
454 bookmarksOrHistoryPicker(false);
455 break;
456 case FOCUS_NODE_HREF:
457 {
458 String url = (String) msg.getData().get("url");
459 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500460 String src = (String) msg.getData().get("src");
461 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700462 if (TextUtils.isEmpty(url)) {
463 break;
464 }
465 HashMap focusNodeMap = (HashMap) msg.obj;
466 WebView view = (WebView) focusNodeMap.get("webview");
467 // Only apply the action if the top window did not change.
468 if (getCurrentTopWebView() != view) {
469 break;
470 }
471 switch (msg.arg1) {
472 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -0700473 loadUrlFromContext(getCurrentTopWebView(), url);
474 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500475 case R.id.view_image_context_menu_id:
476 loadUrlFromContext(getCurrentTopWebView(), src);
477 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500478 case R.id.open_newtab_context_menu_id:
479 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -0800480 final Tab newTab = openTab(parent, url, false);
Leon Scroggins026f2542010-11-22 13:26:12 -0500481 if (newTab != null && newTab != parent) {
482 parent.addChildTab(newTab);
483 }
484 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700485 case R.id.copy_link_context_menu_id:
486 copy(url);
487 break;
488 case R.id.save_link_context_menu_id:
489 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500490 DownloadHandler.onDownloadStartNoStream(
491 mActivity, url, null, null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -0700492 break;
493 }
494 break;
495 }
496
497 case LOAD_URL:
498 loadUrlFromContext(getCurrentTopWebView(), (String) msg.obj);
499 break;
500
501 case STOP_LOAD:
502 stopLoading();
503 break;
504
505 case RELEASE_WAKELOCK:
506 if (mWakeLock.isHeld()) {
507 mWakeLock.release();
508 // if we reach here, Browser should be still in the
509 // background loading after WAKELOCK_TIMEOUT (5-min).
510 // To avoid burning the battery, stop loading.
511 mTabControl.stopAllLoading();
512 }
513 break;
514
515 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800516 Tab tab = (Tab) msg.obj;
517 if (tab != null) {
518 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700519 }
520 break;
521 }
522 }
523 };
524
525 }
526
Michael Kolbba99c5d2010-11-29 14:57:41 -0800527 @Override
528 public void shareCurrentPage() {
529 shareCurrentPage(mTabControl.getCurrentTab());
530 }
531
532 private void shareCurrentPage(Tab tab) {
533 if (tab != null) {
Michael Kolbba99c5d2010-11-29 14:57:41 -0800534 sharePage(mActivity, tab.getTitle(),
535 tab.getUrl(), tab.getFavicon(),
536 createScreenshot(tab.getWebView(),
537 getDesiredThumbnailWidth(mActivity),
538 getDesiredThumbnailHeight(mActivity)));
539 }
540 }
541
Michael Kolb8233fac2010-10-26 16:08:53 -0700542 /**
543 * Share a page, providing the title, url, favicon, and a screenshot. Uses
544 * an {@link Intent} to launch the Activity chooser.
545 * @param c Context used to launch a new Activity.
546 * @param title Title of the page. Stored in the Intent with
547 * {@link Intent#EXTRA_SUBJECT}
548 * @param url URL of the page. Stored in the Intent with
549 * {@link Intent#EXTRA_TEXT}
550 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
551 * with {@link Browser#EXTRA_SHARE_FAVICON}
552 * @param screenshot Bitmap of a screenshot of the page. Stored in the
553 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
554 */
555 static final void sharePage(Context c, String title, String url,
556 Bitmap favicon, Bitmap screenshot) {
557 Intent send = new Intent(Intent.ACTION_SEND);
558 send.setType("text/plain");
559 send.putExtra(Intent.EXTRA_TEXT, url);
560 send.putExtra(Intent.EXTRA_SUBJECT, title);
561 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
562 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
563 try {
564 c.startActivity(Intent.createChooser(send, c.getString(
565 R.string.choosertitle_sharevia)));
566 } catch(android.content.ActivityNotFoundException ex) {
567 // if no app handles it, do nothing
568 }
569 }
570
571 private void copy(CharSequence text) {
572 ClipboardManager cm = (ClipboardManager) mActivity
573 .getSystemService(Context.CLIPBOARD_SERVICE);
574 cm.setText(text);
575 }
576
577 // lifecycle
578
579 protected void onConfgurationChanged(Configuration config) {
580 mConfigChanged = true;
581 if (mPageDialogsHandler != null) {
582 mPageDialogsHandler.onConfigurationChanged(config);
583 }
584 mUi.onConfigurationChanged(config);
585 }
586
587 @Override
588 public void handleNewIntent(Intent intent) {
589 mIntentHandler.onNewIntent(intent);
590 }
591
592 protected void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800593 if (mUi.isCustomViewShowing()) {
594 hideCustomView();
595 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700596 if (mActivityPaused) {
597 Log.e(LOGTAG, "BrowserActivity is already paused.");
598 return;
599 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700600 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800601 Tab tab = mTabControl.getCurrentTab();
602 if (tab != null) {
603 tab.pause();
604 if (!pauseWebViewTimers(tab)) {
605 mWakeLock.acquire();
606 mHandler.sendMessageDelayed(mHandler
607 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
608 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700609 }
610 mUi.onPause();
611 mNetworkHandler.onPause();
612
613 WebView.disablePlatformNotifications();
614 }
615
616 void onSaveInstanceState(Bundle outState) {
617 // the default implementation requires each view to have an id. As the
618 // browser handles the state itself and it doesn't use id for the views,
619 // don't call the default implementation. Otherwise it will trigger the
620 // warning like this, "couldn't save which view has focus because the
621 // focused view XXX has no id".
622
623 // Save all the tabs
624 mTabControl.saveState(outState);
625 // Save time so that we know how old incognito tabs (if any) are.
626 outState.putSerializable("lastActiveDate", Calendar.getInstance());
627 }
628
629 void onResume() {
630 if (!mActivityPaused) {
631 Log.e(LOGTAG, "BrowserActivity is already resumed.");
632 return;
633 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700634 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800635 Tab current = mTabControl.getCurrentTab();
636 if (current != null) {
637 current.resume();
638 resumeWebViewTimers(current);
639 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700640 if (mWakeLock.isHeld()) {
641 mHandler.removeMessages(RELEASE_WAKELOCK);
642 mWakeLock.release();
643 }
644 mUi.onResume();
645 mNetworkHandler.onResume();
646 WebView.enablePlatformNotifications();
647 }
648
Michael Kolb70976932010-11-30 11:34:01 -0800649 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800650 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800651 * @param tab guaranteed non-null
652 */
653 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700654 boolean inLoad = tab.inPageLoad();
655 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
656 CookieSyncManager.getInstance().startSync();
657 WebView w = tab.getWebView();
658 if (w != null) {
659 w.resumeTimers();
660 }
661 }
662 }
663
Michael Kolb70976932010-11-30 11:34:01 -0800664 /**
665 * Pause all WebView timers using the WebView of the given tab
666 * @param tab
667 * @return true if the timers are paused or tab is null
668 */
669 private boolean pauseWebViewTimers(Tab tab) {
670 if (tab == null) {
671 return true;
672 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700673 CookieSyncManager.getInstance().stopSync();
674 WebView w = getCurrentWebView();
675 if (w != null) {
676 w.pauseTimers();
677 }
678 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700679 }
Michael Kolb70976932010-11-30 11:34:01 -0800680 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700681 }
682
683 void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800684 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700685 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
686 mUploadHandler = null;
687 }
688 if (mTabControl == null) return;
689 mUi.onDestroy();
690 // Remove the current tab and sub window
691 Tab t = mTabControl.getCurrentTab();
692 if (t != null) {
693 dismissSubWindow(t);
694 removeTab(t);
695 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500696 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700697 // Destroy all the tabs
698 mTabControl.destroy();
699 WebIconDatabase.getInstance().close();
700 // Stop watching the default geolocation permissions
701 mSystemAllowGeolocationOrigins.stop();
702 mSystemAllowGeolocationOrigins = null;
703 }
704
705 protected boolean isActivityPaused() {
706 return mActivityPaused;
707 }
708
709 protected void onLowMemory() {
710 mTabControl.freeMemory();
711 }
712
713 @Override
714 public boolean shouldShowErrorConsole() {
715 return mShouldShowErrorConsole;
716 }
717
718 protected void setShouldShowErrorConsole(boolean show) {
719 if (show == mShouldShowErrorConsole) {
720 // Nothing to do.
721 return;
722 }
723 mShouldShowErrorConsole = show;
724 Tab t = mTabControl.getCurrentTab();
725 if (t == null) {
726 // There is no current tab so we cannot toggle the error console
727 return;
728 }
729 mUi.setShouldShowErrorConsole(t, show);
730 }
731
732 @Override
733 public void stopLoading() {
734 mLoadStopped = true;
735 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700736 WebView w = getCurrentTopWebView();
737 w.stopLoading();
Michael Kolb8233fac2010-10-26 16:08:53 -0700738 mUi.onPageStopped(tab);
739 }
740
741 boolean didUserStopLoading() {
742 return mLoadStopped;
743 }
744
745 // WebViewController
746
747 @Override
John Reck324d4402011-01-11 16:56:42 -0800748 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700749
750 // We've started to load a new page. If there was a pending message
751 // to save a screenshot then we will now take the new page and save
752 // an incorrect screenshot. Therefore, remove any pending thumbnail
753 // messages from the queue.
754 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
John Reck34ef2672011-02-10 11:30:55 -0800755 tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700756
757 // reset sync timer to avoid sync starts during loading a page
758 CookieSyncManager.getInstance().resetSync();
759
760 if (!mNetworkHandler.isNetworkUp()) {
761 view.setNetworkAvailable(false);
762 }
763
764 // when BrowserActivity just starts, onPageStarted may be called before
765 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
766 // to start the timer. As we won't switch tabs while an activity is in
767 // pause state, we can ensure calling resume and pause in pair.
768 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800769 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700770 }
771 mLoadStopped = false;
772 if (!mNetworkHandler.isNetworkUp()) {
773 mNetworkHandler.createAndShowNetworkDialog();
774 }
775 endActionMode();
776
John Reck30c714c2010-12-16 17:30:34 -0800777 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700778
John Reck324d4402011-01-11 16:56:42 -0800779 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700780 // update the bookmark database for favicon
781 maybeUpdateFavicon(tab, null, url, favicon);
782
783 Performance.tracePageStart(url);
784
785 // Performance probe
786 if (false) {
787 Performance.onPageStarted();
788 }
789
790 }
791
792 @Override
John Reck324d4402011-01-11 16:56:42 -0800793 public void onPageFinished(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -0800794 mUi.onTabDataChanged(tab);
John Reck324d4402011-01-11 16:56:42 -0800795 if (!tab.isPrivateBrowsingEnabled()
796 && !TextUtils.isEmpty(tab.getUrl())) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700797 if (tab.inForeground() && !didUserStopLoading()
798 || !tab.inForeground()) {
799 // Only update the bookmark screenshot if the user did not
800 // cancel the load early.
801 mHandler.sendMessageDelayed(mHandler.obtainMessage(
John Reck34ef2672011-02-10 11:30:55 -0800802 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
Michael Kolb8233fac2010-10-26 16:08:53 -0700803 500);
804 }
805 }
806 // pause the WebView timer and release the wake lock if it is finished
807 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800808 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700809 if (mWakeLock.isHeld()) {
810 mHandler.removeMessages(RELEASE_WAKELOCK);
811 mWakeLock.release();
812 }
813 }
814 // Performance probe
815 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800816 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700817 }
818
819 Performance.tracePageFinished();
820 }
821
822 @Override
John Reck30c714c2010-12-16 17:30:34 -0800823 public void onProgressChanged(Tab tab) {
824 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700825
826 if (newProgress == 100) {
827 CookieSyncManager.getInstance().sync();
828 // onProgressChanged() may continue to be called after the main
829 // frame has finished loading, as any remaining sub frames continue
830 // to load. We'll only get called once though with newProgress as
831 // 100 when everything is loaded. (onPageFinished is called once
832 // when the main frame completes loading regardless of the state of
833 // any sub frames so calls to onProgressChanges may continue after
834 // onPageFinished has executed)
835 if (mInLoad) {
836 mInLoad = false;
837 updateInLoadMenuItems(mCachedMenu);
838 }
839 } else {
840 if (!mInLoad) {
841 // onPageFinished may have already been called but a subframe is
842 // still loading and updating the progress. Reset mInLoad and
843 // update the menu items.
844 mInLoad = true;
845 updateInLoadMenuItems(mCachedMenu);
846 }
847 }
John Reck30c714c2010-12-16 17:30:34 -0800848 mUi.onProgressChanged(tab);
849 }
850
851 @Override
852 public void onUpdatedLockIcon(Tab tab) {
853 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700854 }
855
856 @Override
857 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -0800858 mUi.onTabDataChanged(tab);
859 final String pageUrl = tab.getUrl();
John Reck324d4402011-01-11 16:56:42 -0800860 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -0700861 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
862 return;
863 }
864 // Update the title in the history database if not in private browsing mode
865 if (!tab.isPrivateBrowsingEnabled()) {
John Reck0ebd3ac2010-12-09 11:14:04 -0800866 mDataController.updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700867 }
868 }
869
870 @Override
871 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -0800872 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700873 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
874 }
875
876 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800877 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
878 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700879 }
880
881 @Override
882 public boolean shouldOverrideKeyEvent(KeyEvent event) {
883 if (mMenuIsDown) {
884 // only check shortcut key when MENU is held
885 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
886 event);
887 } else {
888 return false;
889 }
890 }
891
892 @Override
893 public void onUnhandledKeyEvent(KeyEvent event) {
894 if (!isActivityPaused()) {
895 if (event.getAction() == KeyEvent.ACTION_DOWN) {
896 mActivity.onKeyDown(event.getKeyCode(), event);
897 } else {
898 mActivity.onKeyUp(event.getKeyCode(), event);
899 }
900 }
901 }
902
903 @Override
John Reck324d4402011-01-11 16:56:42 -0800904 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700905 // Don't save anything in private browsing mode
906 if (tab.isPrivateBrowsingEnabled()) return;
John Reck324d4402011-01-11 16:56:42 -0800907 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700908
John Reck324d4402011-01-11 16:56:42 -0800909 if (TextUtils.isEmpty(url)
910 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700911 return;
912 }
John Reck0ebd3ac2010-12-09 11:14:04 -0800913 mDataController.updateVisitedHistory(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700914 WebIconDatabase.getInstance().retainIconForPageUrl(url);
915 }
916
917 @Override
918 public void getVisitedHistory(final ValueCallback<String[]> callback) {
919 AsyncTask<Void, Void, String[]> task =
920 new AsyncTask<Void, Void, String[]>() {
921 @Override
922 public String[] doInBackground(Void... unused) {
923 return Browser.getVisitedHistory(mActivity.getContentResolver());
924 }
925 @Override
926 public void onPostExecute(String[] result) {
927 callback.onReceiveValue(result);
928 }
929 };
930 task.execute();
931 }
932
933 @Override
934 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
935 final HttpAuthHandler handler, final String host,
936 final String realm) {
937 String username = null;
938 String password = null;
939
940 boolean reuseHttpAuthUsernamePassword
941 = handler.useHttpAuthUsernamePassword();
942
943 if (reuseHttpAuthUsernamePassword && view != null) {
944 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
945 if (credentials != null && credentials.length == 2) {
946 username = credentials[0];
947 password = credentials[1];
948 }
949 }
950
951 if (username != null && password != null) {
952 handler.proceed(username, password);
953 } else {
954 if (tab.inForeground()) {
955 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
956 } else {
957 handler.cancel();
958 }
959 }
960 }
961
962 @Override
963 public void onDownloadStart(Tab tab, String url, String userAgent,
964 String contentDisposition, String mimetype, long contentLength) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500965 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
966 contentDisposition, mimetype);
Michael Kolb8233fac2010-10-26 16:08:53 -0700967 if (tab.getWebView().copyBackForwardList().getSize() == 0) {
968 // This Tab was opened for the sole purpose of downloading a
969 // file. Remove it.
970 if (tab == mTabControl.getCurrentTab()) {
971 // In this case, the Tab is still on top.
972 goBackOnePageOrQuit();
973 } else {
974 // In this case, it is not.
975 closeTab(tab);
976 }
977 }
978 }
979
980 @Override
981 public Bitmap getDefaultVideoPoster() {
982 return mUi.getDefaultVideoPoster();
983 }
984
985 @Override
986 public View getVideoLoadingProgressView() {
987 return mUi.getVideoLoadingProgressView();
988 }
989
990 @Override
991 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
992 SslError error) {
993 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
994 }
995
996 // helper method
997
998 /*
999 * Update the favorites icon if the private browsing isn't enabled and the
1000 * icon is valid.
1001 */
1002 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1003 final String url, Bitmap favicon) {
1004 if (favicon == null) {
1005 return;
1006 }
1007 if (!tab.isPrivateBrowsingEnabled()) {
1008 Bookmarks.updateFavicon(mActivity
1009 .getContentResolver(), originalUrl, url, favicon);
1010 }
1011 }
1012
Leon Scroggins4cd97792010-12-03 15:31:56 -05001013 @Override
1014 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001015 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001016 mUi.bookmarkedStatusHasChanged(tab);
1017 }
1018
Michael Kolb8233fac2010-10-26 16:08:53 -07001019 // end WebViewController
1020
1021 protected void pageUp() {
1022 getCurrentTopWebView().pageUp(false);
1023 }
1024
1025 protected void pageDown() {
1026 getCurrentTopWebView().pageDown(false);
1027 }
1028
1029 // callback from phone title bar
1030 public void editUrl() {
1031 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08001032 mUi.editUrl(false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001033 }
1034
Michael Kolbcfa3af52010-12-14 10:36:11 -08001035 public void startVoiceSearch() {
1036 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1037 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
1038 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
1039 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
1040 mActivity.getComponentName().flattenToString());
1041 intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb17c4eba2011-01-10 13:10:07 -08001042 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolbcfa3af52010-12-14 10:36:11 -08001043 mActivity.startActivity(intent);
1044 }
1045
Michael Kolb8233fac2010-10-26 16:08:53 -07001046 public void activateVoiceSearchMode(String title) {
1047 mUi.showVoiceTitleBar(title);
1048 }
1049
1050 public void revertVoiceSearchMode(Tab tab) {
1051 mUi.revertVoiceTitleBar(tab);
1052 }
1053
1054 public void showCustomView(Tab tab, View view,
1055 WebChromeClient.CustomViewCallback callback) {
1056 if (tab.inForeground()) {
1057 if (mUi.isCustomViewShowing()) {
1058 callback.onCustomViewHidden();
1059 return;
1060 }
1061 mUi.showCustomView(view, callback);
1062 // Save the menu state and set it to empty while the custom
1063 // view is showing.
1064 mOldMenuState = mMenuState;
1065 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001066 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001067 }
1068 }
1069
1070 @Override
1071 public void hideCustomView() {
1072 if (mUi.isCustomViewShowing()) {
1073 mUi.onHideCustomView();
1074 // Reset the old menu state.
1075 mMenuState = mOldMenuState;
1076 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001077 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001078 }
1079 }
1080
1081 protected void onActivityResult(int requestCode, int resultCode,
1082 Intent intent) {
1083 if (getCurrentTopWebView() == null) return;
1084 switch (requestCode) {
1085 case PREFERENCES_PAGE:
1086 if (resultCode == Activity.RESULT_OK && intent != null) {
1087 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
1088 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
1089 mTabControl.removeParentChildRelationShips();
1090 }
1091 }
1092 break;
1093 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001094 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001095 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001096 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001097 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));
John Reck3527dd12011-02-22 10:35:29 -08001375 menu.findItem(R.id.set_wallpaper_context_menu_id).
1376 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1377 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001378 break;
1379
1380 default:
1381 Log.w(LOGTAG, "We should not get here.");
1382 break;
1383 }
1384 //update the ui
1385 mUi.onContextMenuCreated(menu);
1386 }
1387
1388 /**
1389 * As the menu can be open when loading state changes
1390 * we must manually update the state of the stop/reload menu
1391 * item
1392 */
1393 private void updateInLoadMenuItems(Menu menu) {
1394 if (menu == null) {
1395 return;
1396 }
1397 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1398 MenuItem src = mInLoad ?
1399 menu.findItem(R.id.stop_menu_id):
1400 menu.findItem(R.id.reload_menu_id);
1401 if (src != null) {
1402 dest.setIcon(src.getIcon());
1403 dest.setTitle(src.getTitle());
1404 }
1405 }
1406
John Reckb3417f02011-01-14 11:01:05 -08001407 boolean onPrepareOptionsMenu(Menu menu) {
1408 if (mOptionsMenuHandler != null) {
1409 return mOptionsMenuHandler.onPrepareOptionsMenu(menu);
1410 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001411 // This happens when the user begins to hold down the menu key, so
1412 // allow them to chord to get a shortcut.
1413 mCanChord = true;
1414 // Note: setVisible will decide whether an item is visible; while
1415 // setEnabled() will decide whether an item is enabled, which also means
1416 // whether the matching shortcut key will function.
1417 switch (mMenuState) {
1418 case EMPTY_MENU:
1419 if (mCurrentMenuState != mMenuState) {
1420 menu.setGroupVisible(R.id.MAIN_MENU, false);
1421 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1422 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1423 }
1424 break;
1425 default:
1426 if (mCurrentMenuState != mMenuState) {
1427 menu.setGroupVisible(R.id.MAIN_MENU, true);
1428 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1429 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1430 }
1431 final WebView w = getCurrentTopWebView();
1432 boolean canGoBack = false;
1433 boolean canGoForward = false;
1434 boolean isHome = false;
1435 if (w != null) {
1436 canGoBack = w.canGoBack();
1437 canGoForward = w.canGoForward();
1438 isHome = mSettings.getHomePage().equals(w.getUrl());
1439 }
1440 final MenuItem back = menu.findItem(R.id.back_menu_id);
1441 back.setEnabled(canGoBack);
1442
1443 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1444 home.setEnabled(!isHome);
1445
1446 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1447 forward.setEnabled(canGoForward);
1448
1449 // decide whether to show the share link option
1450 PackageManager pm = mActivity.getPackageManager();
1451 Intent send = new Intent(Intent.ACTION_SEND);
1452 send.setType("text/plain");
1453 ResolveInfo ri = pm.resolveActivity(send,
1454 PackageManager.MATCH_DEFAULT_ONLY);
1455 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1456
1457 boolean isNavDump = mSettings.isNavDump();
1458 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1459 nav.setVisible(isNavDump);
1460 nav.setEnabled(isNavDump);
1461
1462 boolean showDebugSettings = mSettings.showDebugSettings();
1463 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1464 counter.setVisible(showDebugSettings);
1465 counter.setEnabled(showDebugSettings);
1466
John Reckb3417f02011-01-14 11:01:05 -08001467 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1468 newtab.setEnabled(getTabControl().canCreateNewTab());
Michael Kolb8233fac2010-10-26 16:08:53 -07001469
Leon Scroggins81983762011-02-11 15:17:36 -05001470 MenuItem archive = menu.findItem(R.id.save_webarchive_menu_id);
John Reck51d8bad2011-02-28 15:47:47 -08001471 Tab tab = getTabControl().getCurrentTab();
1472 String url = tab != null ? tab.getUrl() : null;
1473 archive.setVisible(!TextUtils.isEmpty(url)
1474 && !url.endsWith(".webarchivexml"));
Michael Kolb8233fac2010-10-26 16:08:53 -07001475 break;
1476 }
1477 mCurrentMenuState = mMenuState;
1478 return true;
1479 }
1480
1481 public boolean onOptionsItemSelected(MenuItem item) {
John Reckb3417f02011-01-14 11:01:05 -08001482 if (mOptionsMenuHandler != null &&
1483 mOptionsMenuHandler.onOptionsItemSelected(item)) {
1484 return true;
1485 }
1486
Michael Kolb8233fac2010-10-26 16:08:53 -07001487 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1488 // menu remains active, so ensure comboview is dismissed
1489 // if main menu option is selected
1490 removeComboView();
1491 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001492 if (!mCanChord) {
1493 // The user has already fired a shortcut with this hold down of the
1494 // menu key.
1495 return false;
1496 }
1497 if (null == getCurrentTopWebView()) {
1498 return false;
1499 }
1500 if (mMenuIsDown) {
1501 // The shortcut action consumes the MENU. Even if it is still down,
1502 // it won't trigger the next shortcut action. In the case of the
1503 // shortcut action triggering a new activity, like Bookmarks, we
1504 // won't get onKeyUp for MENU. So it is important to reset it here.
1505 mMenuIsDown = false;
1506 }
1507 switch (item.getItemId()) {
1508 // -- Main menu
1509 case R.id.new_tab_menu_id:
1510 openTabToHomePage();
1511 break;
1512
1513 case R.id.incognito_menu_id:
1514 openIncognitoTab();
1515 break;
1516
1517 case R.id.goto_menu_id:
1518 editUrl();
1519 break;
1520
1521 case R.id.bookmarks_menu_id:
1522 bookmarksOrHistoryPicker(false);
1523 break;
1524
1525 case R.id.active_tabs_menu_id:
1526 showActiveTabsPage();
1527 break;
1528
1529 case R.id.add_bookmark_menu_id:
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001530 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001531 break;
1532
1533 case R.id.stop_reload_menu_id:
1534 if (mInLoad) {
1535 stopLoading();
1536 } else {
1537 getCurrentTopWebView().reload();
1538 }
1539 break;
1540
1541 case R.id.back_menu_id:
1542 getCurrentTopWebView().goBack();
1543 break;
1544
1545 case R.id.forward_menu_id:
1546 getCurrentTopWebView().goForward();
1547 break;
1548
1549 case R.id.close_menu_id:
1550 // Close the subwindow if it exists.
1551 if (mTabControl.getCurrentSubWindow() != null) {
1552 dismissSubWindow(mTabControl.getCurrentTab());
1553 break;
1554 }
1555 closeCurrentTab();
1556 break;
1557
1558 case R.id.homepage_menu_id:
1559 Tab current = mTabControl.getCurrentTab();
1560 if (current != null) {
1561 dismissSubWindow(current);
1562 loadUrl(current.getWebView(), mSettings.getHomePage());
1563 }
1564 break;
1565
1566 case R.id.preferences_menu_id:
1567 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1568 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1569 getCurrentTopWebView().getUrl());
1570 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1571 break;
1572
1573 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001574 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001575 break;
1576
Leon Scrogginsac993842011-02-02 12:54:07 -05001577 case R.id.save_webarchive_menu_id:
1578 String state = Environment.getExternalStorageState();
1579 if (!Environment.MEDIA_MOUNTED.equals(state)) {
1580 Log.e(LOGTAG, "External storage not mounted");
1581 Toast.makeText(mActivity, R.string.webarchive_failed,
1582 Toast.LENGTH_SHORT).show();
1583 break;
1584 }
1585 final String directory = Environment.getExternalStoragePublicDirectory(
1586 Environment.DIRECTORY_DOWNLOADS) + File.separator;
1587 File dir = new File(directory);
1588 if (!dir.exists() && !dir.mkdirs()) {
1589 Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
1590 Toast.makeText(mActivity, R.string.webarchive_failed,
1591 Toast.LENGTH_SHORT).show();
1592 break;
1593 }
1594 WebView topWebView = getCurrentTopWebView();
1595 final String title = topWebView.getTitle();
John Reck51d8bad2011-02-28 15:47:47 -08001596 final String url = topWebView.getUrl();
Leon Scrogginsac993842011-02-02 12:54:07 -05001597 topWebView.saveWebArchive(directory, true,
1598 new ValueCallback<String>() {
1599 @Override
1600 public void onReceiveValue(final String value) {
1601 if (value != null) {
1602 File file = new File(value);
1603 final long length = file.length();
1604 if (file.exists() && length > 0) {
Leon Scroggins1cb96552011-02-11 14:22:57 -05001605 Toast.makeText(mActivity, R.string.webarchive_saved,
1606 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001607 final DownloadManager manager = (DownloadManager) mActivity
1608 .getSystemService(Context.DOWNLOAD_SERVICE);
1609 new Thread("Add WebArchive to download manager") {
1610 @Override
1611 public void run() {
1612 manager.completedDownload(null == title ? value : title,
1613 value, true, "application/x-webarchive-xml",
1614 value, length, true);
1615 }
1616 }.start();
1617 return;
1618 }
1619 }
John Reck51d8bad2011-02-28 15:47:47 -08001620 DownloadHandler.onDownloadStartNoStream(mActivity,
1621 url, null, null, null);
Leon Scrogginsac993842011-02-02 12:54:07 -05001622 }
1623 });
1624 break;
1625
Michael Kolb8233fac2010-10-26 16:08:53 -07001626 case R.id.page_info_menu_id:
1627 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1628 false);
1629 break;
1630
1631 case R.id.classic_history_menu_id:
1632 bookmarksOrHistoryPicker(true);
1633 break;
1634
1635 case R.id.title_bar_share_page_url:
1636 case R.id.share_page_menu_id:
1637 Tab currentTab = mTabControl.getCurrentTab();
1638 if (null == currentTab) {
1639 mCanChord = false;
1640 return false;
1641 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001642 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001643 break;
1644
1645 case R.id.dump_nav_menu_id:
1646 getCurrentTopWebView().debugDump();
1647 break;
1648
1649 case R.id.dump_counters_menu_id:
1650 getCurrentTopWebView().dumpV8Counters();
1651 break;
1652
1653 case R.id.zoom_in_menu_id:
1654 getCurrentTopWebView().zoomIn();
1655 break;
1656
1657 case R.id.zoom_out_menu_id:
1658 getCurrentTopWebView().zoomOut();
1659 break;
1660
1661 case R.id.view_downloads_menu_id:
1662 viewDownloads();
1663 break;
1664
1665 case R.id.window_one_menu_id:
1666 case R.id.window_two_menu_id:
1667 case R.id.window_three_menu_id:
1668 case R.id.window_four_menu_id:
1669 case R.id.window_five_menu_id:
1670 case R.id.window_six_menu_id:
1671 case R.id.window_seven_menu_id:
1672 case R.id.window_eight_menu_id:
1673 {
1674 int menuid = item.getItemId();
1675 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1676 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1677 Tab desiredTab = mTabControl.getTab(id);
1678 if (desiredTab != null &&
1679 desiredTab != mTabControl.getCurrentTab()) {
1680 switchToTab(id);
1681 }
1682 break;
1683 }
1684 }
1685 }
1686 break;
1687
1688 default:
1689 return false;
1690 }
1691 mCanChord = false;
1692 return true;
1693 }
1694
1695 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001696 // Let the History and Bookmark fragments handle menus they created.
1697 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1698 return false;
1699 }
1700
Michael Kolb8233fac2010-10-26 16:08:53 -07001701 // chording is not an issue with context menus, but we use the same
1702 // options selector, so set mCanChord to true so we can access them.
1703 mCanChord = true;
1704 int id = item.getItemId();
1705 boolean result = true;
1706 switch (id) {
1707 // For the context menu from the title bar
1708 case R.id.title_bar_copy_page_url:
1709 Tab currentTab = mTabControl.getCurrentTab();
1710 if (null == currentTab) {
1711 result = false;
1712 break;
1713 }
1714 WebView mainView = currentTab.getWebView();
1715 if (null == mainView) {
1716 result = false;
1717 break;
1718 }
1719 copy(mainView.getUrl());
1720 break;
1721 // -- Browser context menu
1722 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001723 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001724 case R.id.copy_link_context_menu_id:
1725 final WebView webView = getCurrentTopWebView();
1726 if (null == webView) {
1727 result = false;
1728 break;
1729 }
1730 final HashMap<String, WebView> hrefMap =
1731 new HashMap<String, WebView>();
1732 hrefMap.put("webview", webView);
1733 final Message msg = mHandler.obtainMessage(
1734 FOCUS_NODE_HREF, id, 0, hrefMap);
1735 webView.requestFocusNodeHref(msg);
1736 break;
1737
1738 default:
1739 // For other context menus
1740 result = onOptionsItemSelected(item);
1741 }
1742 mCanChord = false;
1743 return result;
1744 }
1745
1746 /**
1747 * support programmatically opening the context menu
1748 */
1749 public void openContextMenu(View view) {
1750 mActivity.openContextMenu(view);
1751 }
1752
1753 /**
1754 * programmatically open the options menu
1755 */
1756 public void openOptionsMenu() {
1757 mActivity.openOptionsMenu();
1758 }
1759
1760 public boolean onMenuOpened(int featureId, Menu menu) {
1761 if (mOptionsMenuOpen) {
1762 if (mConfigChanged) {
1763 // We do not need to make any changes to the state of the
1764 // title bar, since the only thing that happened was a
1765 // change in orientation
1766 mConfigChanged = false;
1767 } else {
1768 if (!mExtendedMenuOpen) {
1769 mExtendedMenuOpen = true;
1770 mUi.onExtendedMenuOpened();
1771 } else {
1772 // Switching the menu back to icon view, so show the
1773 // title bar once again.
1774 mExtendedMenuOpen = false;
1775 mUi.onExtendedMenuClosed(mInLoad);
1776 mUi.onOptionsMenuOpened();
1777 }
1778 }
1779 } else {
1780 // The options menu is closed, so open it, and show the title
1781 mOptionsMenuOpen = true;
1782 mConfigChanged = false;
1783 mExtendedMenuOpen = false;
1784 mUi.onOptionsMenuOpened();
1785 }
1786 return true;
1787 }
1788
1789 public void onOptionsMenuClosed(Menu menu) {
1790 mOptionsMenuOpen = false;
1791 mUi.onOptionsMenuClosed(mInLoad);
1792 }
1793
1794 public void onContextMenuClosed(Menu menu) {
1795 mUi.onContextMenuClosed(menu, mInLoad);
1796 }
1797
1798 // Helper method for getting the top window.
1799 @Override
1800 public WebView getCurrentTopWebView() {
1801 return mTabControl.getCurrentTopWebView();
1802 }
1803
1804 @Override
1805 public WebView getCurrentWebView() {
1806 return mTabControl.getCurrentWebView();
1807 }
1808
1809 /*
1810 * This method is called as a result of the user selecting the options
1811 * menu to see the download window. It shows the download window on top of
1812 * the current window.
1813 */
1814 void viewDownloads() {
1815 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1816 mActivity.startActivity(intent);
1817 }
1818
1819 // action mode
1820
1821 void onActionModeStarted(ActionMode mode) {
1822 mUi.onActionModeStarted(mode);
1823 mActionMode = mode;
1824 }
1825
1826 /*
1827 * True if a custom ActionMode (i.e. find or select) is in use.
1828 */
1829 @Override
1830 public boolean isInCustomActionMode() {
1831 return mActionMode != null;
1832 }
1833
1834 /*
1835 * End the current ActionMode.
1836 */
1837 @Override
1838 public void endActionMode() {
1839 if (mActionMode != null) {
1840 mActionMode.finish();
1841 }
1842 }
1843
1844 /*
1845 * Called by find and select when they are finished. Replace title bars
1846 * as necessary.
1847 */
1848 public void onActionModeFinished(ActionMode mode) {
1849 if (!isInCustomActionMode()) return;
1850 mUi.onActionModeFinished(mInLoad);
1851 mActionMode = null;
1852 }
1853
1854 boolean isInLoad() {
1855 return mInLoad;
1856 }
1857
1858 // bookmark handling
1859
1860 /**
1861 * add the current page as a bookmark to the given folder id
1862 * @param folderId use -1 for the default folder
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001863 * @param canBeAnEdit If true, check to see whether the site is already
1864 * bookmarked, and if it is, edit that bookmark. If false, and
1865 * the site is already bookmarked, do not attempt to edit the
1866 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001867 */
1868 @Override
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001869 public void bookmarkCurrentPage(long folderId, boolean canBeAnEdit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001870 Intent i = new Intent(mActivity,
1871 AddBookmarkPage.class);
1872 WebView w = getCurrentTopWebView();
1873 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1874 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1875 String touchIconUrl = w.getTouchIconUrl();
1876 if (touchIconUrl != null) {
1877 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1878 WebSettings settings = w.getSettings();
1879 if (settings != null) {
1880 i.putExtra(AddBookmarkPage.USER_AGENT,
1881 settings.getUserAgentString());
1882 }
1883 }
1884 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1885 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1886 getDesiredThumbnailHeight(mActivity)));
1887 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1888 i.putExtra(BrowserContract.Bookmarks.PARENT,
1889 folderId);
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001890 if (canBeAnEdit) {
1891 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1892 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001893 // Put the dialog at the upper right of the screen, covering the
1894 // star on the title bar.
1895 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1896 mActivity.startActivity(i);
1897 }
1898
1899 // file chooser
1900 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1901 mUploadHandler = new UploadHandler(this);
1902 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1903 }
1904
1905 // thumbnails
1906
1907 /**
1908 * Return the desired width for thumbnail screenshots, which are stored in
1909 * the database, and used on the bookmarks screen.
1910 * @param context Context for finding out the density of the screen.
1911 * @return desired width for thumbnail screenshot.
1912 */
1913 static int getDesiredThumbnailWidth(Context context) {
1914 return context.getResources().getDimensionPixelOffset(
1915 R.dimen.bookmarkThumbnailWidth);
1916 }
1917
1918 /**
1919 * Return the desired height for thumbnail screenshots, which are stored in
1920 * the database, and used on the bookmarks screen.
1921 * @param context Context for finding out the density of the screen.
1922 * @return desired height for thumbnail screenshot.
1923 */
1924 static int getDesiredThumbnailHeight(Context context) {
1925 return context.getResources().getDimensionPixelOffset(
1926 R.dimen.bookmarkThumbnailHeight);
1927 }
1928
1929 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001930 // We render to a bitmap 2x the desired size so that we can then
1931 // re-scale it with filtering since canvas.scale doesn't filter
1932 // This helps reduce aliasing at the cost of being slightly blurry
1933 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001934 Picture thumbnail = view.capturePicture();
1935 if (thumbnail == null) {
1936 return null;
1937 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001938 width *= filter_scale;
1939 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001940 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1941 Canvas canvas = new Canvas(bm);
1942 // May need to tweak these values to determine what is the
1943 // best scale factor
1944 int thumbnailWidth = thumbnail.getWidth();
1945 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001946 float scaleFactor = 1.0f;
Michael Kolb8233fac2010-10-26 16:08:53 -07001947 if (thumbnailWidth > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001948 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001949 } else {
1950 return null;
1951 }
John Reckfe49ab42010-11-16 17:09:37 -08001952
Michael Kolb8233fac2010-10-26 16:08:53 -07001953 if (view.getWidth() > view.getHeight() &&
1954 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
1955 // If the device is in landscape and the page is shorter
John Reckfe49ab42010-11-16 17:09:37 -08001956 // than the height of the view, center the thumnail and crop the sides
1957 scaleFactor = (float) height / (float)thumbnailHeight;
1958 float wx = (thumbnailWidth * scaleFactor) - width;
1959 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001960 }
1961
John Reckfe49ab42010-11-16 17:09:37 -08001962 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001963
1964 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001965 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
1966 height / filter_scale, true);
1967 bm.recycle();
1968 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001969 }
1970
John Reck34ef2672011-02-10 11:30:55 -08001971 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001972 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07001973 // FIXME: Would like to make sure there is actually something to
1974 // draw, but the API for that (WebViewCore.pictureReady()) is not
1975 // currently accessible here.
1976
John Reck34ef2672011-02-10 11:30:55 -08001977 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08001978 if (view == null) {
1979 // Tab was destroyed
1980 return;
1981 }
John Reck34ef2672011-02-10 11:30:55 -08001982 final String url = tab.getUrl();
1983 final String originalUrl = view.getOriginalUrl();
1984
1985 if (TextUtils.isEmpty(url)) {
1986 return;
1987 }
1988
1989 // Only update thumbnails for web urls (http(s)://), not for
1990 // about:, javascript:, data:, etc...
1991 // Unless it is a bookmarked site, then always update
1992 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
1993 return;
1994 }
1995
Michael Kolb8233fac2010-10-26 16:08:53 -07001996 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1997 getDesiredThumbnailHeight(mActivity));
1998 if (bm == null) {
1999 return;
2000 }
2001
2002 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002003 new AsyncTask<Void, Void, Void>() {
2004 @Override
2005 protected Void doInBackground(Void... unused) {
2006 Cursor cursor = null;
2007 try {
2008 // TODO: Clean this up
2009 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2010 if (cursor != null && cursor.moveToFirst()) {
2011 final ByteArrayOutputStream os =
2012 new ByteArrayOutputStream();
2013 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002014
John Reck34ef2672011-02-10 11:30:55 -08002015 ContentValues values = new ContentValues();
2016 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002017
John Reck34ef2672011-02-10 11:30:55 -08002018 do {
John Reck617fd832011-02-16 14:35:59 -08002019 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002020 cr.update(Images.CONTENT_URI, values, null, null);
2021 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002022 }
John Reck34ef2672011-02-10 11:30:55 -08002023 } catch (IllegalStateException e) {
2024 // Ignore
2025 } finally {
2026 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002027 }
John Reck34ef2672011-02-10 11:30:55 -08002028 return null;
2029 }
2030 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002031 }
2032
2033 private class Copy implements OnMenuItemClickListener {
2034 private CharSequence mText;
2035
2036 public boolean onMenuItemClick(MenuItem item) {
2037 copy(mText);
2038 return true;
2039 }
2040
2041 public Copy(CharSequence toCopy) {
2042 mText = toCopy;
2043 }
2044 }
2045
Leon Scroggins63c02662010-11-18 15:16:27 -05002046 private static class Download implements OnMenuItemClickListener {
2047 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002048 private String mText;
2049
2050 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002051 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
2052 null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07002053 return true;
2054 }
2055
Leon Scroggins63c02662010-11-18 15:16:27 -05002056 public Download(Activity activity, String toDownload) {
2057 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002058 mText = toDownload;
2059 }
2060 }
2061
Cary Clark8974d282010-11-22 10:46:05 -05002062 private static class SelectText implements OnMenuItemClickListener {
2063 private WebView mWebView;
2064
2065 public boolean onMenuItemClick(MenuItem item) {
2066 if (mWebView != null) {
2067 return mWebView.selectText();
2068 }
2069 return false;
2070 }
2071
2072 public SelectText(WebView webView) {
2073 mWebView = webView;
2074 }
2075
2076 }
2077
Michael Kolb8233fac2010-10-26 16:08:53 -07002078 /********************** TODO: UI stuff *****************************/
2079
2080 // these methods have been copied, they still need to be cleaned up
2081
2082 /****************** tabs ***************************************************/
2083
2084 // basic tab interactions:
2085
2086 // it is assumed that tabcontrol already knows about the tab
2087 protected void addTab(Tab tab) {
2088 mUi.addTab(tab);
2089 }
2090
2091 protected void removeTab(Tab tab) {
2092 mUi.removeTab(tab);
2093 mTabControl.removeTab(tab);
2094 }
2095
2096 protected void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002097 // monkey protection against delayed start
2098 if (tab != null) {
2099 mTabControl.setCurrentTab(tab);
2100 // the tab is guaranteed to have a webview after setCurrentTab
2101 mUi.setActiveTab(tab);
2102 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002103 }
2104
2105 protected void closeEmptyChildTab() {
2106 Tab current = mTabControl.getCurrentTab();
2107 if (current != null
2108 && current.getWebView().copyBackForwardList().getSize() == 0) {
2109 Tab parent = current.getParentTab();
2110 if (parent != null) {
2111 switchToTab(mTabControl.getTabIndex(parent));
2112 closeTab(current);
2113 }
2114 }
2115 }
2116
2117 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002118 // Dismiss the subwindow if applicable.
2119 dismissSubWindow(appTab);
2120 // Since we might kill the WebView, remove it from the
2121 // content view first.
2122 mUi.detachTab(appTab);
2123 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002124 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002125 // TODO: analyze why the remove and add are necessary
2126 mUi.attachTab(appTab);
2127 if (mTabControl.getCurrentTab() != appTab) {
2128 switchToTab(mTabControl.getTabIndex(appTab));
John Reck30c714c2010-12-16 17:30:34 -08002129 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002130 } else {
2131 // If the tab was the current tab, we have to attach
2132 // it to the view system again.
2133 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002134 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002135 }
2136 }
2137
2138 // Remove the sub window if it exists. Also called by TabControl when the
2139 // user clicks the 'X' to dismiss a sub window.
2140 public void dismissSubWindow(Tab tab) {
2141 removeSubWindow(tab);
2142 // dismiss the subwindow. This will destroy the WebView.
2143 tab.dismissSubWindow();
2144 getCurrentTopWebView().requestFocus();
2145 }
2146
2147 @Override
2148 public void removeSubWindow(Tab t) {
2149 if (t.getSubWebView() != null) {
2150 mUi.removeSubWindow(t.getSubViewContainer());
2151 }
2152 }
2153
2154 @Override
2155 public void attachSubWindow(Tab tab) {
2156 if (tab.getSubWebView() != null) {
2157 mUi.attachSubWindow(tab.getSubViewContainer());
2158 getCurrentTopWebView().requestFocus();
2159 }
2160 }
2161
Michael Kolb843510f2010-12-09 10:51:49 -08002162 @Override
2163 public Tab openTabToHomePage() {
2164 // check for max tabs
2165 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002166 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2167 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002168 } else {
2169 mUi.showMaxTabsWarning();
2170 return null;
2171 }
2172 }
2173
Michael Kolb18eb3772010-12-10 14:29:51 -08002174 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2175 if (mSettings.openInBackground() && !forceForeground) {
2176 Tab tab = mTabControl.createNewTab(false, null, null,
2177 (parent != null) && parent.isPrivateBrowsingEnabled());
2178 if (tab != null) {
2179 addTab(tab);
2180 WebView view = tab.getWebView();
2181 loadUrl(view, url);
2182 }
2183 return tab;
2184 } else {
2185 return openTabAndShow(parent, new UrlData(url), false, null);
2186 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002187 }
2188
Michael Kolb18eb3772010-12-10 14:29:51 -08002189
Michael Kolb8233fac2010-10-26 16:08:53 -07002190 // This method does a ton of stuff. It will attempt to create a new tab
2191 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2192 // url isn't null, it will load the given url.
Patrick Scottcd135082011-01-31 18:21:58 -05002193 public Tab openTabAndShow(Tab parent, final UrlData urlData,
2194 boolean closeOnExit, String appId) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002195 final Tab currentTab = mTabControl.getCurrentTab();
2196 if (mTabControl.canCreateNewTab()) {
2197 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Michael Kolb18eb3772010-12-10 14:29:51 -08002198 urlData.mUrl,
2199 (parent != null) && parent.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -07002200 WebView webview = tab.getWebView();
2201 // We must set the new tab as the current tab to reflect the old
2202 // animation behavior.
2203 addTab(tab);
2204 setActiveTab(tab);
Patrick Scottcd135082011-01-31 18:21:58 -05002205
2206 // Callback to load the url data.
2207 final Runnable load = new Runnable() {
2208 @Override public void run() {
2209 if (!urlData.isEmpty()) {
2210 loadUrlDataIn(tab, urlData);
2211 }
2212 }
2213 };
2214
2215 GoogleAccountLogin.startLoginIfNeeded(mActivity, mSettings, load);
Michael Kolb8233fac2010-10-26 16:08:53 -07002216 return tab;
2217 } else {
2218 // Get rid of the subwindow if it exists
2219 dismissSubWindow(currentTab);
2220 if (!urlData.isEmpty()) {
2221 // Load the given url.
2222 loadUrlDataIn(currentTab, urlData);
2223 }
2224 return currentTab;
2225 }
2226 }
2227
Michael Kolb8233fac2010-10-26 16:08:53 -07002228 @Override
2229 public Tab openIncognitoTab() {
2230 if (mTabControl.canCreateNewTab()) {
2231 Tab currentTab = mTabControl.getCurrentTab();
Michael Kolb8e7178d2011-01-26 19:13:36 -08002232 Tab tab = mTabControl.createNewTab(false, null,
John Reck4bfc0db2011-01-27 17:47:12 -08002233 null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07002234 addTab(tab);
2235 setActiveTab(tab);
John Reck4bfc0db2011-01-27 17:47:12 -08002236 loadUrlDataIn(tab, new UrlData("browser:incognito"));
Michael Kolb8233fac2010-10-26 16:08:53 -07002237 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002238 } else {
2239 mUi.showMaxTabsWarning();
2240 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002241 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002242 }
2243
2244 /**
2245 * @param index Index of the tab to change to, as defined by
2246 * mTabControl.getTabIndex(Tab t).
2247 * @return boolean True if we successfully switched to a different tab. If
2248 * the indexth tab is null, or if that tab is the same as
2249 * the current one, return false.
2250 */
2251 @Override
2252 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002253 // hide combo view if open
2254 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002255 Tab tab = mTabControl.getTab(index);
2256 Tab currentTab = mTabControl.getCurrentTab();
2257 if (tab == null || tab == currentTab) {
2258 return false;
2259 }
2260 setActiveTab(tab);
2261 return true;
2262 }
2263
2264 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002265 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002266 // hide combo view if open
2267 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002268 final Tab current = mTabControl.getCurrentTab();
2269 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002270 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002271 return;
2272 }
2273 final Tab parent = current.getParentTab();
2274 int indexToShow = -1;
2275 if (parent != null) {
2276 indexToShow = mTabControl.getTabIndex(parent);
2277 } else {
2278 final int currentIndex = mTabControl.getCurrentIndex();
2279 // Try to move to the tab to the right
2280 indexToShow = currentIndex + 1;
2281 if (indexToShow > mTabControl.getTabCount() - 1) {
2282 // Try to move to the tab to the left
2283 indexToShow = currentIndex - 1;
2284 }
2285 }
2286 if (switchToTab(indexToShow)) {
2287 // Close window
2288 closeTab(current);
2289 }
2290 }
2291
2292 /**
2293 * Close the tab, remove its associated title bar, and adjust mTabControl's
2294 * current tab to a valid value.
2295 */
2296 @Override
2297 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002298 // hide combo view if open
2299 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002300 int currentIndex = mTabControl.getCurrentIndex();
2301 int removeIndex = mTabControl.getTabIndex(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002302 Tab newtab = mTabControl.getTab(currentIndex);
2303 setActiveTab(newtab);
Michael Kolb2d59c322011-01-25 13:18:55 -08002304 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002305 }
2306
2307 /**************** TODO: Url loading clean up *******************************/
2308
2309 // Called when loading from context menu or LOAD_URL message
2310 protected void loadUrlFromContext(WebView view, String url) {
2311 // In case the user enters nothing.
2312 if (url != null && url.length() != 0 && view != null) {
2313 url = UrlUtils.smartUrlFilter(url);
2314 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2315 loadUrl(view, url);
2316 }
2317 }
2318 }
2319
2320 /**
2321 * Load the URL into the given WebView and update the title bar
2322 * to reflect the new load. Call this instead of WebView.loadUrl
2323 * directly.
2324 * @param view The WebView used to load url.
2325 * @param url The URL to load.
2326 */
2327 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002328 view.loadUrl(url);
2329 }
2330
2331 /**
2332 * Load UrlData into a Tab and update the title bar to reflect the new
2333 * load. Call this instead of UrlData.loadIn directly.
2334 * @param t The Tab used to load.
2335 * @param data The UrlData being loaded.
2336 */
2337 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002338 data.loadIn(t);
2339 }
2340
John Reck30c714c2010-12-16 17:30:34 -08002341 @Override
2342 public void onUserCanceledSsl(Tab tab) {
2343 WebView web = tab.getWebView();
2344 // TODO: Figure out the "right" behavior
2345 if (web.canGoBack()) {
2346 web.goBack();
2347 } else {
2348 web.loadUrl(mSettings.getHomePage());
2349 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002350 }
2351
2352 void goBackOnePageOrQuit() {
2353 Tab current = mTabControl.getCurrentTab();
2354 if (current == null) {
2355 /*
2356 * Instead of finishing the activity, simply push this to the back
2357 * of the stack and let ActivityManager to choose the foreground
2358 * activity. As BrowserActivity is singleTask, it will be always the
2359 * root of the task. So we can use either true or false for
2360 * moveTaskToBack().
2361 */
2362 mActivity.moveTaskToBack(true);
2363 return;
2364 }
2365 WebView w = current.getWebView();
2366 if (w.canGoBack()) {
2367 w.goBack();
2368 } else {
2369 // Check to see if we are closing a window that was created by
2370 // another window. If so, we switch back to that window.
2371 Tab parent = current.getParentTab();
2372 if (parent != null) {
2373 switchToTab(mTabControl.getTabIndex(parent));
2374 // Now we close the other tab
2375 closeTab(current);
2376 } else {
2377 if (current.closeOnExit()) {
2378 // force the tab's inLoad() to be false as we are going to
2379 // either finish the activity or remove the tab. This will
2380 // ensure pauseWebViewTimers() taking action.
Michael Kolb70976932010-11-30 11:34:01 -08002381 current.clearInPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07002382 if (mTabControl.getTabCount() == 1) {
2383 mActivity.finish();
2384 return;
2385 }
2386 if (mActivityPaused) {
2387 Log.e(LOGTAG, "BrowserActivity is already paused "
2388 + "while handing goBackOnePageOrQuit.");
2389 }
Michael Kolb70976932010-11-30 11:34:01 -08002390 pauseWebViewTimers(current);
Michael Kolb96683f72011-02-15 14:24:35 -08002391 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002392 }
2393 /*
2394 * Instead of finishing the activity, simply push this to the back
2395 * of the stack and let ActivityManager to choose the foreground
2396 * activity. As BrowserActivity is singleTask, it will be always the
2397 * root of the task. So we can use either true or false for
2398 * moveTaskToBack().
2399 */
2400 mActivity.moveTaskToBack(true);
2401 }
2402 }
2403 }
2404
2405 /**
2406 * Feed the previously stored results strings to the BrowserProvider so that
2407 * the SearchDialog will show them instead of the standard searches.
2408 * @param result String to show on the editable line of the SearchDialog.
2409 */
2410 @Override
2411 public void showVoiceSearchResults(String result) {
2412 ContentProviderClient client = mActivity.getContentResolver()
2413 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2414 ContentProvider prov = client.getLocalContentProvider();
2415 BrowserProvider bp = (BrowserProvider) prov;
2416 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2417 client.release();
2418
2419 Bundle bundle = createGoogleSearchSourceBundle(
2420 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2421 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2422 startSearch(result, false, bundle, false);
2423 }
2424
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002425 @Override
2426 public void startSearch(String url) {
2427 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
2428 null, false);
2429 }
2430
Michael Kolb8233fac2010-10-26 16:08:53 -07002431 private void startSearch(String initialQuery, boolean selectInitialQuery,
2432 Bundle appSearchData, boolean globalSearch) {
2433 if (appSearchData == null) {
2434 appSearchData = createGoogleSearchSourceBundle(
2435 GOOGLE_SEARCH_SOURCE_TYPE);
2436 }
2437
2438 SearchEngine searchEngine = mSettings.getSearchEngine();
2439 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2440 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2441 }
2442 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2443 globalSearch);
2444 }
2445
2446 private Bundle createGoogleSearchSourceBundle(String source) {
2447 Bundle bundle = new Bundle();
2448 bundle.putString(Search.SOURCE, source);
2449 return bundle;
2450 }
2451
2452 /**
2453 * handle key events in browser
2454 *
2455 * @param keyCode
2456 * @param event
2457 * @return true if handled, false to pass to super
2458 */
2459 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002460 boolean noModifiers = event.hasNoModifiers();
2461
Michael Kolb8233fac2010-10-26 16:08:53 -07002462 // Even if MENU is already held down, we need to call to super to open
2463 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002464 if (!noModifiers
2465 && ((KeyEvent.KEYCODE_MENU == keyCode)
2466 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2467 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002468 mMenuIsDown = true;
2469 return false;
2470 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002471
Cary Clark8ff8c662010-12-29 15:03:05 -05002472 WebView webView = getCurrentTopWebView();
2473 if (webView == null) return false;
2474
Cary Clark160bbb92011-01-10 11:17:07 -05002475 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2476 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002477
Michael Kolb8233fac2010-10-26 16:08:53 -07002478 switch(keyCode) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002479 case KeyEvent.KEYCODE_ESCAPE:
Cary Clark160bbb92011-01-10 11:17:07 -05002480 if (!noModifiers) break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002481 stopLoading();
2482 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07002483 case KeyEvent.KEYCODE_SPACE:
2484 // WebView/WebTextView handle the keys in the KeyDown. As
2485 // the Activity's shortcut keys are only handled when WebView
2486 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002487 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002488 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002489 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002490 pageDown();
2491 }
2492 return true;
2493 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002494 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002495 event.startTracking();
2496 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002497 case KeyEvent.KEYCODE_DPAD_LEFT:
2498 if (ctrl) {
2499 webView.goBack();
2500 return true;
2501 }
2502 break;
2503 case KeyEvent.KEYCODE_DPAD_RIGHT:
2504 if (ctrl) {
2505 webView.goForward();
2506 return true;
2507 }
2508 break;
2509 case KeyEvent.KEYCODE_A:
2510 if (ctrl) {
2511 webView.selectAll();
2512 return true;
2513 }
2514 break;
Michael Kolba4183062011-01-16 10:43:21 -08002515// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002516 case KeyEvent.KEYCODE_C:
2517 if (ctrl) {
2518 webView.copySelection();
2519 return true;
2520 }
2521 break;
Michael Kolba4183062011-01-16 10:43:21 -08002522// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002523// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002524// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002525// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002526// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002527// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002528// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002529// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002530// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002531// case KeyEvent.KEYCODE_M: // unused
2532// case KeyEvent.KEYCODE_N: // in Chrome: new window
2533// case KeyEvent.KEYCODE_O: // in Chrome: open file
2534// case KeyEvent.KEYCODE_P: // in Chrome: print page
2535// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002536// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002537// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2538 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002539 // we can't use the ctrl/shift flags, they check for
2540 // exclusive use of a modifier
2541 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002542 if (event.isShiftPressed()) {
2543 openIncognitoTab();
2544 } else {
2545 openTabToHomePage();
2546 }
2547 return true;
2548 }
2549 break;
2550// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2551// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolba4183062011-01-16 10:43:21 -08002552// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002553// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2554// case KeyEvent.KEYCODE_Y: // unused
2555// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002556 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002557 // it is a regular key and webview is not null
2558 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002559 }
2560
John Recke6bf4ab2011-02-24 15:48:05 -08002561 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2562 switch(keyCode) {
2563 case KeyEvent.KEYCODE_BACK:
2564 if (mUi.showsWeb()) {
2565 bookmarksOrHistoryPicker(true);
2566 return true;
2567 }
2568 break;
2569 }
2570 return false;
2571 }
2572
Michael Kolb8233fac2010-10-26 16:08:53 -07002573 boolean onKeyUp(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002574 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002575 switch(keyCode) {
2576 case KeyEvent.KEYCODE_MENU:
2577 mMenuIsDown = false;
2578 break;
2579 case KeyEvent.KEYCODE_BACK:
2580 if (event.isTracking() && !event.isCanceled()) {
2581 onBackKey();
2582 return true;
2583 }
2584 break;
2585 }
2586 return false;
2587 }
2588
2589 public boolean isMenuDown() {
2590 return mMenuIsDown;
2591 }
2592
Ben Murdoch8029a772010-11-16 11:58:21 +00002593 public void setupAutoFill(Message message) {
2594 // Open the settings activity at the AutoFill profile fragment so that
2595 // the user can create a new profile. When they return, we will dispatch
2596 // the message so that we can autofill the form using their new profile.
2597 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2598 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2599 AutoFillSettingsFragment.class.getName());
2600 mAutoFillSetupMessage = message;
2601 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2602 }
John Reckb3417f02011-01-14 11:01:05 -08002603
2604 @Override
2605 public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
2606 mOptionsMenuHandler = handler;
2607 }
2608
2609 @Override
2610 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
2611 if (mOptionsMenuHandler == handler) {
2612 mOptionsMenuHandler = null;
2613 }
2614 }
2615
Michael Kolb8233fac2010-10-26 16:08:53 -07002616}