blob: c1f13139a6632072f8fff5a434ef9de01ed36012 [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);
Cary Clarkba860522011-02-16 11:22:42 -05001471 String url = w != null ? w.getUrl() : null;
1472 archive.setVisible(url != null && !url.endsWith(".webarchivexml"));
Michael Kolb8233fac2010-10-26 16:08:53 -07001473 break;
1474 }
1475 mCurrentMenuState = mMenuState;
1476 return true;
1477 }
1478
1479 public boolean onOptionsItemSelected(MenuItem item) {
John Reckb3417f02011-01-14 11:01:05 -08001480 if (mOptionsMenuHandler != null &&
1481 mOptionsMenuHandler.onOptionsItemSelected(item)) {
1482 return true;
1483 }
1484
Michael Kolb8233fac2010-10-26 16:08:53 -07001485 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1486 // menu remains active, so ensure comboview is dismissed
1487 // if main menu option is selected
1488 removeComboView();
1489 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001490 if (!mCanChord) {
1491 // The user has already fired a shortcut with this hold down of the
1492 // menu key.
1493 return false;
1494 }
1495 if (null == getCurrentTopWebView()) {
1496 return false;
1497 }
1498 if (mMenuIsDown) {
1499 // The shortcut action consumes the MENU. Even if it is still down,
1500 // it won't trigger the next shortcut action. In the case of the
1501 // shortcut action triggering a new activity, like Bookmarks, we
1502 // won't get onKeyUp for MENU. So it is important to reset it here.
1503 mMenuIsDown = false;
1504 }
1505 switch (item.getItemId()) {
1506 // -- Main menu
1507 case R.id.new_tab_menu_id:
1508 openTabToHomePage();
1509 break;
1510
1511 case R.id.incognito_menu_id:
1512 openIncognitoTab();
1513 break;
1514
1515 case R.id.goto_menu_id:
1516 editUrl();
1517 break;
1518
1519 case R.id.bookmarks_menu_id:
1520 bookmarksOrHistoryPicker(false);
1521 break;
1522
1523 case R.id.active_tabs_menu_id:
1524 showActiveTabsPage();
1525 break;
1526
1527 case R.id.add_bookmark_menu_id:
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001528 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001529 break;
1530
1531 case R.id.stop_reload_menu_id:
1532 if (mInLoad) {
1533 stopLoading();
1534 } else {
1535 getCurrentTopWebView().reload();
1536 }
1537 break;
1538
1539 case R.id.back_menu_id:
1540 getCurrentTopWebView().goBack();
1541 break;
1542
1543 case R.id.forward_menu_id:
1544 getCurrentTopWebView().goForward();
1545 break;
1546
1547 case R.id.close_menu_id:
1548 // Close the subwindow if it exists.
1549 if (mTabControl.getCurrentSubWindow() != null) {
1550 dismissSubWindow(mTabControl.getCurrentTab());
1551 break;
1552 }
1553 closeCurrentTab();
1554 break;
1555
1556 case R.id.homepage_menu_id:
1557 Tab current = mTabControl.getCurrentTab();
1558 if (current != null) {
1559 dismissSubWindow(current);
1560 loadUrl(current.getWebView(), mSettings.getHomePage());
1561 }
1562 break;
1563
1564 case R.id.preferences_menu_id:
1565 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1566 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1567 getCurrentTopWebView().getUrl());
1568 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1569 break;
1570
1571 case R.id.find_menu_id:
Leon Scroggins1c00d5e2011-01-04 10:45:58 -05001572 getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001573 break;
1574
Leon Scrogginsac993842011-02-02 12:54:07 -05001575 case R.id.save_webarchive_menu_id:
1576 String state = Environment.getExternalStorageState();
1577 if (!Environment.MEDIA_MOUNTED.equals(state)) {
1578 Log.e(LOGTAG, "External storage not mounted");
1579 Toast.makeText(mActivity, R.string.webarchive_failed,
1580 Toast.LENGTH_SHORT).show();
1581 break;
1582 }
1583 final String directory = Environment.getExternalStoragePublicDirectory(
1584 Environment.DIRECTORY_DOWNLOADS) + File.separator;
1585 File dir = new File(directory);
1586 if (!dir.exists() && !dir.mkdirs()) {
1587 Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
1588 Toast.makeText(mActivity, R.string.webarchive_failed,
1589 Toast.LENGTH_SHORT).show();
1590 break;
1591 }
1592 WebView topWebView = getCurrentTopWebView();
1593 final String title = topWebView.getTitle();
1594 topWebView.saveWebArchive(directory, true,
1595 new ValueCallback<String>() {
1596 @Override
1597 public void onReceiveValue(final String value) {
1598 if (value != null) {
1599 File file = new File(value);
1600 final long length = file.length();
1601 if (file.exists() && length > 0) {
Leon Scroggins1cb96552011-02-11 14:22:57 -05001602 Toast.makeText(mActivity, R.string.webarchive_saved,
1603 Toast.LENGTH_SHORT).show();
Leon Scrogginsac993842011-02-02 12:54:07 -05001604 final DownloadManager manager = (DownloadManager) mActivity
1605 .getSystemService(Context.DOWNLOAD_SERVICE);
1606 new Thread("Add WebArchive to download manager") {
1607 @Override
1608 public void run() {
1609 manager.completedDownload(null == title ? value : title,
1610 value, true, "application/x-webarchive-xml",
1611 value, length, true);
1612 }
1613 }.start();
1614 return;
1615 }
1616 }
1617 Toast.makeText(mActivity,
1618 R.string.webarchive_failed, Toast.LENGTH_SHORT).show();
1619 }
1620 });
1621 break;
1622
Michael Kolb8233fac2010-10-26 16:08:53 -07001623 case R.id.page_info_menu_id:
1624 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1625 false);
1626 break;
1627
1628 case R.id.classic_history_menu_id:
1629 bookmarksOrHistoryPicker(true);
1630 break;
1631
1632 case R.id.title_bar_share_page_url:
1633 case R.id.share_page_menu_id:
1634 Tab currentTab = mTabControl.getCurrentTab();
1635 if (null == currentTab) {
1636 mCanChord = false;
1637 return false;
1638 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001639 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001640 break;
1641
1642 case R.id.dump_nav_menu_id:
1643 getCurrentTopWebView().debugDump();
1644 break;
1645
1646 case R.id.dump_counters_menu_id:
1647 getCurrentTopWebView().dumpV8Counters();
1648 break;
1649
1650 case R.id.zoom_in_menu_id:
1651 getCurrentTopWebView().zoomIn();
1652 break;
1653
1654 case R.id.zoom_out_menu_id:
1655 getCurrentTopWebView().zoomOut();
1656 break;
1657
1658 case R.id.view_downloads_menu_id:
1659 viewDownloads();
1660 break;
1661
1662 case R.id.window_one_menu_id:
1663 case R.id.window_two_menu_id:
1664 case R.id.window_three_menu_id:
1665 case R.id.window_four_menu_id:
1666 case R.id.window_five_menu_id:
1667 case R.id.window_six_menu_id:
1668 case R.id.window_seven_menu_id:
1669 case R.id.window_eight_menu_id:
1670 {
1671 int menuid = item.getItemId();
1672 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1673 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1674 Tab desiredTab = mTabControl.getTab(id);
1675 if (desiredTab != null &&
1676 desiredTab != mTabControl.getCurrentTab()) {
1677 switchToTab(id);
1678 }
1679 break;
1680 }
1681 }
1682 }
1683 break;
1684
1685 default:
1686 return false;
1687 }
1688 mCanChord = false;
1689 return true;
1690 }
1691
1692 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001693 // Let the History and Bookmark fragments handle menus they created.
1694 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1695 return false;
1696 }
1697
Michael Kolb8233fac2010-10-26 16:08:53 -07001698 // chording is not an issue with context menus, but we use the same
1699 // options selector, so set mCanChord to true so we can access them.
1700 mCanChord = true;
1701 int id = item.getItemId();
1702 boolean result = true;
1703 switch (id) {
1704 // For the context menu from the title bar
1705 case R.id.title_bar_copy_page_url:
1706 Tab currentTab = mTabControl.getCurrentTab();
1707 if (null == currentTab) {
1708 result = false;
1709 break;
1710 }
1711 WebView mainView = currentTab.getWebView();
1712 if (null == mainView) {
1713 result = false;
1714 break;
1715 }
1716 copy(mainView.getUrl());
1717 break;
1718 // -- Browser context menu
1719 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001720 case R.id.save_link_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07001721 case R.id.copy_link_context_menu_id:
1722 final WebView webView = getCurrentTopWebView();
1723 if (null == webView) {
1724 result = false;
1725 break;
1726 }
1727 final HashMap<String, WebView> hrefMap =
1728 new HashMap<String, WebView>();
1729 hrefMap.put("webview", webView);
1730 final Message msg = mHandler.obtainMessage(
1731 FOCUS_NODE_HREF, id, 0, hrefMap);
1732 webView.requestFocusNodeHref(msg);
1733 break;
1734
1735 default:
1736 // For other context menus
1737 result = onOptionsItemSelected(item);
1738 }
1739 mCanChord = false;
1740 return result;
1741 }
1742
1743 /**
1744 * support programmatically opening the context menu
1745 */
1746 public void openContextMenu(View view) {
1747 mActivity.openContextMenu(view);
1748 }
1749
1750 /**
1751 * programmatically open the options menu
1752 */
1753 public void openOptionsMenu() {
1754 mActivity.openOptionsMenu();
1755 }
1756
1757 public boolean onMenuOpened(int featureId, Menu menu) {
1758 if (mOptionsMenuOpen) {
1759 if (mConfigChanged) {
1760 // We do not need to make any changes to the state of the
1761 // title bar, since the only thing that happened was a
1762 // change in orientation
1763 mConfigChanged = false;
1764 } else {
1765 if (!mExtendedMenuOpen) {
1766 mExtendedMenuOpen = true;
1767 mUi.onExtendedMenuOpened();
1768 } else {
1769 // Switching the menu back to icon view, so show the
1770 // title bar once again.
1771 mExtendedMenuOpen = false;
1772 mUi.onExtendedMenuClosed(mInLoad);
1773 mUi.onOptionsMenuOpened();
1774 }
1775 }
1776 } else {
1777 // The options menu is closed, so open it, and show the title
1778 mOptionsMenuOpen = true;
1779 mConfigChanged = false;
1780 mExtendedMenuOpen = false;
1781 mUi.onOptionsMenuOpened();
1782 }
1783 return true;
1784 }
1785
1786 public void onOptionsMenuClosed(Menu menu) {
1787 mOptionsMenuOpen = false;
1788 mUi.onOptionsMenuClosed(mInLoad);
1789 }
1790
1791 public void onContextMenuClosed(Menu menu) {
1792 mUi.onContextMenuClosed(menu, mInLoad);
1793 }
1794
1795 // Helper method for getting the top window.
1796 @Override
1797 public WebView getCurrentTopWebView() {
1798 return mTabControl.getCurrentTopWebView();
1799 }
1800
1801 @Override
1802 public WebView getCurrentWebView() {
1803 return mTabControl.getCurrentWebView();
1804 }
1805
1806 /*
1807 * This method is called as a result of the user selecting the options
1808 * menu to see the download window. It shows the download window on top of
1809 * the current window.
1810 */
1811 void viewDownloads() {
1812 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1813 mActivity.startActivity(intent);
1814 }
1815
1816 // action mode
1817
1818 void onActionModeStarted(ActionMode mode) {
1819 mUi.onActionModeStarted(mode);
1820 mActionMode = mode;
1821 }
1822
1823 /*
1824 * True if a custom ActionMode (i.e. find or select) is in use.
1825 */
1826 @Override
1827 public boolean isInCustomActionMode() {
1828 return mActionMode != null;
1829 }
1830
1831 /*
1832 * End the current ActionMode.
1833 */
1834 @Override
1835 public void endActionMode() {
1836 if (mActionMode != null) {
1837 mActionMode.finish();
1838 }
1839 }
1840
1841 /*
1842 * Called by find and select when they are finished. Replace title bars
1843 * as necessary.
1844 */
1845 public void onActionModeFinished(ActionMode mode) {
1846 if (!isInCustomActionMode()) return;
1847 mUi.onActionModeFinished(mInLoad);
1848 mActionMode = null;
1849 }
1850
1851 boolean isInLoad() {
1852 return mInLoad;
1853 }
1854
1855 // bookmark handling
1856
1857 /**
1858 * add the current page as a bookmark to the given folder id
1859 * @param folderId use -1 for the default folder
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001860 * @param canBeAnEdit If true, check to see whether the site is already
1861 * bookmarked, and if it is, edit that bookmark. If false, and
1862 * the site is already bookmarked, do not attempt to edit the
1863 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07001864 */
1865 @Override
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001866 public void bookmarkCurrentPage(long folderId, boolean canBeAnEdit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001867 Intent i = new Intent(mActivity,
1868 AddBookmarkPage.class);
1869 WebView w = getCurrentTopWebView();
1870 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1871 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1872 String touchIconUrl = w.getTouchIconUrl();
1873 if (touchIconUrl != null) {
1874 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1875 WebSettings settings = w.getSettings();
1876 if (settings != null) {
1877 i.putExtra(AddBookmarkPage.USER_AGENT,
1878 settings.getUserAgentString());
1879 }
1880 }
1881 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1882 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1883 getDesiredThumbnailHeight(mActivity)));
1884 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1885 i.putExtra(BrowserContract.Bookmarks.PARENT,
1886 folderId);
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05001887 if (canBeAnEdit) {
1888 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
1889 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001890 // Put the dialog at the upper right of the screen, covering the
1891 // star on the title bar.
1892 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1893 mActivity.startActivity(i);
1894 }
1895
1896 // file chooser
1897 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1898 mUploadHandler = new UploadHandler(this);
1899 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1900 }
1901
1902 // thumbnails
1903
1904 /**
1905 * Return the desired width for thumbnail screenshots, which are stored in
1906 * the database, and used on the bookmarks screen.
1907 * @param context Context for finding out the density of the screen.
1908 * @return desired width for thumbnail screenshot.
1909 */
1910 static int getDesiredThumbnailWidth(Context context) {
1911 return context.getResources().getDimensionPixelOffset(
1912 R.dimen.bookmarkThumbnailWidth);
1913 }
1914
1915 /**
1916 * Return the desired height for thumbnail screenshots, which are stored in
1917 * the database, and used on the bookmarks screen.
1918 * @param context Context for finding out the density of the screen.
1919 * @return desired height for thumbnail screenshot.
1920 */
1921 static int getDesiredThumbnailHeight(Context context) {
1922 return context.getResources().getDimensionPixelOffset(
1923 R.dimen.bookmarkThumbnailHeight);
1924 }
1925
1926 private static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck5c6ac2f2011-01-05 10:18:03 -08001927 // We render to a bitmap 2x the desired size so that we can then
1928 // re-scale it with filtering since canvas.scale doesn't filter
1929 // This helps reduce aliasing at the cost of being slightly blurry
1930 final int filter_scale = 2;
Michael Kolb8233fac2010-10-26 16:08:53 -07001931 Picture thumbnail = view.capturePicture();
1932 if (thumbnail == null) {
1933 return null;
1934 }
John Reck5c6ac2f2011-01-05 10:18:03 -08001935 width *= filter_scale;
1936 height *= filter_scale;
Michael Kolb8233fac2010-10-26 16:08:53 -07001937 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1938 Canvas canvas = new Canvas(bm);
1939 // May need to tweak these values to determine what is the
1940 // best scale factor
1941 int thumbnailWidth = thumbnail.getWidth();
1942 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001943 float scaleFactor = 1.0f;
Michael Kolb8233fac2010-10-26 16:08:53 -07001944 if (thumbnailWidth > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001945 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001946 } else {
1947 return null;
1948 }
John Reckfe49ab42010-11-16 17:09:37 -08001949
Michael Kolb8233fac2010-10-26 16:08:53 -07001950 if (view.getWidth() > view.getHeight() &&
1951 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
1952 // If the device is in landscape and the page is shorter
John Reckfe49ab42010-11-16 17:09:37 -08001953 // than the height of the view, center the thumnail and crop the sides
1954 scaleFactor = (float) height / (float)thumbnailHeight;
1955 float wx = (thumbnailWidth * scaleFactor) - width;
1956 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001957 }
1958
John Reckfe49ab42010-11-16 17:09:37 -08001959 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001960
1961 thumbnail.draw(canvas);
John Reck5c6ac2f2011-01-05 10:18:03 -08001962 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
1963 height / filter_scale, true);
1964 bm.recycle();
1965 return ret;
Michael Kolb8233fac2010-10-26 16:08:53 -07001966 }
1967
John Reck34ef2672011-02-10 11:30:55 -08001968 private void updateScreenshot(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001969 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07001970 // FIXME: Would like to make sure there is actually something to
1971 // draw, but the API for that (WebViewCore.pictureReady()) is not
1972 // currently accessible here.
1973
John Reck34ef2672011-02-10 11:30:55 -08001974 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08001975 if (view == null) {
1976 // Tab was destroyed
1977 return;
1978 }
John Reck34ef2672011-02-10 11:30:55 -08001979 final String url = tab.getUrl();
1980 final String originalUrl = view.getOriginalUrl();
1981
1982 if (TextUtils.isEmpty(url)) {
1983 return;
1984 }
1985
1986 // Only update thumbnails for web urls (http(s)://), not for
1987 // about:, javascript:, data:, etc...
1988 // Unless it is a bookmarked site, then always update
1989 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
1990 return;
1991 }
1992
Michael Kolb8233fac2010-10-26 16:08:53 -07001993 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1994 getDesiredThumbnailHeight(mActivity));
1995 if (bm == null) {
1996 return;
1997 }
1998
1999 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002000 new AsyncTask<Void, Void, Void>() {
2001 @Override
2002 protected Void doInBackground(Void... unused) {
2003 Cursor cursor = null;
2004 try {
2005 // TODO: Clean this up
2006 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2007 if (cursor != null && cursor.moveToFirst()) {
2008 final ByteArrayOutputStream os =
2009 new ByteArrayOutputStream();
2010 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002011
John Reck34ef2672011-02-10 11:30:55 -08002012 ContentValues values = new ContentValues();
2013 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002014
John Reck34ef2672011-02-10 11:30:55 -08002015 do {
John Reck617fd832011-02-16 14:35:59 -08002016 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002017 cr.update(Images.CONTENT_URI, values, null, null);
2018 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002019 }
John Reck34ef2672011-02-10 11:30:55 -08002020 } catch (IllegalStateException e) {
2021 // Ignore
2022 } finally {
2023 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002024 }
John Reck34ef2672011-02-10 11:30:55 -08002025 return null;
2026 }
2027 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002028 }
2029
2030 private class Copy implements OnMenuItemClickListener {
2031 private CharSequence mText;
2032
2033 public boolean onMenuItemClick(MenuItem item) {
2034 copy(mText);
2035 return true;
2036 }
2037
2038 public Copy(CharSequence toCopy) {
2039 mText = toCopy;
2040 }
2041 }
2042
Leon Scroggins63c02662010-11-18 15:16:27 -05002043 private static class Download implements OnMenuItemClickListener {
2044 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002045 private String mText;
2046
2047 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002048 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
2049 null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07002050 return true;
2051 }
2052
Leon Scroggins63c02662010-11-18 15:16:27 -05002053 public Download(Activity activity, String toDownload) {
2054 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002055 mText = toDownload;
2056 }
2057 }
2058
Cary Clark8974d282010-11-22 10:46:05 -05002059 private static class SelectText implements OnMenuItemClickListener {
2060 private WebView mWebView;
2061
2062 public boolean onMenuItemClick(MenuItem item) {
2063 if (mWebView != null) {
2064 return mWebView.selectText();
2065 }
2066 return false;
2067 }
2068
2069 public SelectText(WebView webView) {
2070 mWebView = webView;
2071 }
2072
2073 }
2074
Michael Kolb8233fac2010-10-26 16:08:53 -07002075 /********************** TODO: UI stuff *****************************/
2076
2077 // these methods have been copied, they still need to be cleaned up
2078
2079 /****************** tabs ***************************************************/
2080
2081 // basic tab interactions:
2082
2083 // it is assumed that tabcontrol already knows about the tab
2084 protected void addTab(Tab tab) {
2085 mUi.addTab(tab);
2086 }
2087
2088 protected void removeTab(Tab tab) {
2089 mUi.removeTab(tab);
2090 mTabControl.removeTab(tab);
2091 }
2092
2093 protected void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002094 // monkey protection against delayed start
2095 if (tab != null) {
2096 mTabControl.setCurrentTab(tab);
2097 // the tab is guaranteed to have a webview after setCurrentTab
2098 mUi.setActiveTab(tab);
2099 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002100 }
2101
2102 protected void closeEmptyChildTab() {
2103 Tab current = mTabControl.getCurrentTab();
2104 if (current != null
2105 && current.getWebView().copyBackForwardList().getSize() == 0) {
2106 Tab parent = current.getParentTab();
2107 if (parent != null) {
2108 switchToTab(mTabControl.getTabIndex(parent));
2109 closeTab(current);
2110 }
2111 }
2112 }
2113
2114 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002115 // Dismiss the subwindow if applicable.
2116 dismissSubWindow(appTab);
2117 // Since we might kill the WebView, remove it from the
2118 // content view first.
2119 mUi.detachTab(appTab);
2120 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002121 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002122 // TODO: analyze why the remove and add are necessary
2123 mUi.attachTab(appTab);
2124 if (mTabControl.getCurrentTab() != appTab) {
2125 switchToTab(mTabControl.getTabIndex(appTab));
John Reck30c714c2010-12-16 17:30:34 -08002126 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002127 } else {
2128 // If the tab was the current tab, we have to attach
2129 // it to the view system again.
2130 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002131 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002132 }
2133 }
2134
2135 // Remove the sub window if it exists. Also called by TabControl when the
2136 // user clicks the 'X' to dismiss a sub window.
2137 public void dismissSubWindow(Tab tab) {
2138 removeSubWindow(tab);
2139 // dismiss the subwindow. This will destroy the WebView.
2140 tab.dismissSubWindow();
2141 getCurrentTopWebView().requestFocus();
2142 }
2143
2144 @Override
2145 public void removeSubWindow(Tab t) {
2146 if (t.getSubWebView() != null) {
2147 mUi.removeSubWindow(t.getSubViewContainer());
2148 }
2149 }
2150
2151 @Override
2152 public void attachSubWindow(Tab tab) {
2153 if (tab.getSubWebView() != null) {
2154 mUi.attachSubWindow(tab.getSubViewContainer());
2155 getCurrentTopWebView().requestFocus();
2156 }
2157 }
2158
Michael Kolb843510f2010-12-09 10:51:49 -08002159 @Override
2160 public Tab openTabToHomePage() {
2161 // check for max tabs
2162 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002163 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2164 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002165 } else {
2166 mUi.showMaxTabsWarning();
2167 return null;
2168 }
2169 }
2170
Michael Kolb18eb3772010-12-10 14:29:51 -08002171 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2172 if (mSettings.openInBackground() && !forceForeground) {
2173 Tab tab = mTabControl.createNewTab(false, null, null,
2174 (parent != null) && parent.isPrivateBrowsingEnabled());
2175 if (tab != null) {
2176 addTab(tab);
2177 WebView view = tab.getWebView();
2178 loadUrl(view, url);
2179 }
2180 return tab;
2181 } else {
2182 return openTabAndShow(parent, new UrlData(url), false, null);
2183 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002184 }
2185
Michael Kolb18eb3772010-12-10 14:29:51 -08002186
Michael Kolb8233fac2010-10-26 16:08:53 -07002187 // This method does a ton of stuff. It will attempt to create a new tab
2188 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2189 // url isn't null, it will load the given url.
Patrick Scottcd135082011-01-31 18:21:58 -05002190 public Tab openTabAndShow(Tab parent, final UrlData urlData,
2191 boolean closeOnExit, String appId) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002192 final Tab currentTab = mTabControl.getCurrentTab();
2193 if (mTabControl.canCreateNewTab()) {
2194 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Michael Kolb18eb3772010-12-10 14:29:51 -08002195 urlData.mUrl,
2196 (parent != null) && parent.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -07002197 WebView webview = tab.getWebView();
2198 // We must set the new tab as the current tab to reflect the old
2199 // animation behavior.
2200 addTab(tab);
2201 setActiveTab(tab);
Patrick Scottcd135082011-01-31 18:21:58 -05002202
2203 // Callback to load the url data.
2204 final Runnable load = new Runnable() {
2205 @Override public void run() {
2206 if (!urlData.isEmpty()) {
2207 loadUrlDataIn(tab, urlData);
2208 }
2209 }
2210 };
2211
2212 GoogleAccountLogin.startLoginIfNeeded(mActivity, mSettings, load);
Michael Kolb8233fac2010-10-26 16:08:53 -07002213 return tab;
2214 } else {
2215 // Get rid of the subwindow if it exists
2216 dismissSubWindow(currentTab);
2217 if (!urlData.isEmpty()) {
2218 // Load the given url.
2219 loadUrlDataIn(currentTab, urlData);
2220 }
2221 return currentTab;
2222 }
2223 }
2224
Michael Kolb8233fac2010-10-26 16:08:53 -07002225 @Override
2226 public Tab openIncognitoTab() {
2227 if (mTabControl.canCreateNewTab()) {
2228 Tab currentTab = mTabControl.getCurrentTab();
Michael Kolb8e7178d2011-01-26 19:13:36 -08002229 Tab tab = mTabControl.createNewTab(false, null,
John Reck4bfc0db2011-01-27 17:47:12 -08002230 null, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07002231 addTab(tab);
2232 setActiveTab(tab);
John Reck4bfc0db2011-01-27 17:47:12 -08002233 loadUrlDataIn(tab, new UrlData("browser:incognito"));
Michael Kolb8233fac2010-10-26 16:08:53 -07002234 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002235 } else {
2236 mUi.showMaxTabsWarning();
2237 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002238 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002239 }
2240
2241 /**
2242 * @param index Index of the tab to change to, as defined by
2243 * mTabControl.getTabIndex(Tab t).
2244 * @return boolean True if we successfully switched to a different tab. If
2245 * the indexth tab is null, or if that tab is the same as
2246 * the current one, return false.
2247 */
2248 @Override
2249 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002250 // hide combo view if open
2251 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002252 Tab tab = mTabControl.getTab(index);
2253 Tab currentTab = mTabControl.getCurrentTab();
2254 if (tab == null || tab == currentTab) {
2255 return false;
2256 }
2257 setActiveTab(tab);
2258 return true;
2259 }
2260
2261 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002262 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002263 // hide combo view if open
2264 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002265 final Tab current = mTabControl.getCurrentTab();
2266 if (mTabControl.getTabCount() == 1) {
John Reck958b2422010-12-03 17:56:17 -08002267 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07002268 return;
2269 }
2270 final Tab parent = current.getParentTab();
2271 int indexToShow = -1;
2272 if (parent != null) {
2273 indexToShow = mTabControl.getTabIndex(parent);
2274 } else {
2275 final int currentIndex = mTabControl.getCurrentIndex();
2276 // Try to move to the tab to the right
2277 indexToShow = currentIndex + 1;
2278 if (indexToShow > mTabControl.getTabCount() - 1) {
2279 // Try to move to the tab to the left
2280 indexToShow = currentIndex - 1;
2281 }
2282 }
2283 if (switchToTab(indexToShow)) {
2284 // Close window
2285 closeTab(current);
2286 }
2287 }
2288
2289 /**
2290 * Close the tab, remove its associated title bar, and adjust mTabControl's
2291 * current tab to a valid value.
2292 */
2293 @Override
2294 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002295 // hide combo view if open
2296 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002297 int currentIndex = mTabControl.getCurrentIndex();
2298 int removeIndex = mTabControl.getTabIndex(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002299 Tab newtab = mTabControl.getTab(currentIndex);
2300 setActiveTab(newtab);
Michael Kolb2d59c322011-01-25 13:18:55 -08002301 removeTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002302 }
2303
2304 /**************** TODO: Url loading clean up *******************************/
2305
2306 // Called when loading from context menu or LOAD_URL message
2307 protected void loadUrlFromContext(WebView view, String url) {
2308 // In case the user enters nothing.
2309 if (url != null && url.length() != 0 && view != null) {
2310 url = UrlUtils.smartUrlFilter(url);
2311 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2312 loadUrl(view, url);
2313 }
2314 }
2315 }
2316
2317 /**
2318 * Load the URL into the given WebView and update the title bar
2319 * to reflect the new load. Call this instead of WebView.loadUrl
2320 * directly.
2321 * @param view The WebView used to load url.
2322 * @param url The URL to load.
2323 */
2324 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002325 view.loadUrl(url);
2326 }
2327
2328 /**
2329 * Load UrlData into a Tab and update the title bar to reflect the new
2330 * load. Call this instead of UrlData.loadIn directly.
2331 * @param t The Tab used to load.
2332 * @param data The UrlData being loaded.
2333 */
2334 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002335 data.loadIn(t);
2336 }
2337
John Reck30c714c2010-12-16 17:30:34 -08002338 @Override
2339 public void onUserCanceledSsl(Tab tab) {
2340 WebView web = tab.getWebView();
2341 // TODO: Figure out the "right" behavior
2342 if (web.canGoBack()) {
2343 web.goBack();
2344 } else {
2345 web.loadUrl(mSettings.getHomePage());
2346 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002347 }
2348
2349 void goBackOnePageOrQuit() {
2350 Tab current = mTabControl.getCurrentTab();
2351 if (current == null) {
2352 /*
2353 * Instead of finishing the activity, simply push this to the back
2354 * of the stack and let ActivityManager to choose the foreground
2355 * activity. As BrowserActivity is singleTask, it will be always the
2356 * root of the task. So we can use either true or false for
2357 * moveTaskToBack().
2358 */
2359 mActivity.moveTaskToBack(true);
2360 return;
2361 }
2362 WebView w = current.getWebView();
2363 if (w.canGoBack()) {
2364 w.goBack();
2365 } else {
2366 // Check to see if we are closing a window that was created by
2367 // another window. If so, we switch back to that window.
2368 Tab parent = current.getParentTab();
2369 if (parent != null) {
2370 switchToTab(mTabControl.getTabIndex(parent));
2371 // Now we close the other tab
2372 closeTab(current);
2373 } else {
2374 if (current.closeOnExit()) {
2375 // force the tab's inLoad() to be false as we are going to
2376 // either finish the activity or remove the tab. This will
2377 // ensure pauseWebViewTimers() taking action.
Michael Kolb70976932010-11-30 11:34:01 -08002378 current.clearInPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07002379 if (mTabControl.getTabCount() == 1) {
2380 mActivity.finish();
2381 return;
2382 }
2383 if (mActivityPaused) {
2384 Log.e(LOGTAG, "BrowserActivity is already paused "
2385 + "while handing goBackOnePageOrQuit.");
2386 }
Michael Kolb70976932010-11-30 11:34:01 -08002387 pauseWebViewTimers(current);
Michael Kolb96683f72011-02-15 14:24:35 -08002388 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002389 }
2390 /*
2391 * Instead of finishing the activity, simply push this to the back
2392 * of the stack and let ActivityManager to choose the foreground
2393 * activity. As BrowserActivity is singleTask, it will be always the
2394 * root of the task. So we can use either true or false for
2395 * moveTaskToBack().
2396 */
2397 mActivity.moveTaskToBack(true);
2398 }
2399 }
2400 }
2401
2402 /**
2403 * Feed the previously stored results strings to the BrowserProvider so that
2404 * the SearchDialog will show them instead of the standard searches.
2405 * @param result String to show on the editable line of the SearchDialog.
2406 */
2407 @Override
2408 public void showVoiceSearchResults(String result) {
2409 ContentProviderClient client = mActivity.getContentResolver()
2410 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2411 ContentProvider prov = client.getLocalContentProvider();
2412 BrowserProvider bp = (BrowserProvider) prov;
2413 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2414 client.release();
2415
2416 Bundle bundle = createGoogleSearchSourceBundle(
2417 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2418 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2419 startSearch(result, false, bundle, false);
2420 }
2421
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002422 @Override
2423 public void startSearch(String url) {
2424 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
2425 null, false);
2426 }
2427
Michael Kolb8233fac2010-10-26 16:08:53 -07002428 private void startSearch(String initialQuery, boolean selectInitialQuery,
2429 Bundle appSearchData, boolean globalSearch) {
2430 if (appSearchData == null) {
2431 appSearchData = createGoogleSearchSourceBundle(
2432 GOOGLE_SEARCH_SOURCE_TYPE);
2433 }
2434
2435 SearchEngine searchEngine = mSettings.getSearchEngine();
2436 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2437 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2438 }
2439 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2440 globalSearch);
2441 }
2442
2443 private Bundle createGoogleSearchSourceBundle(String source) {
2444 Bundle bundle = new Bundle();
2445 bundle.putString(Search.SOURCE, source);
2446 return bundle;
2447 }
2448
2449 /**
2450 * handle key events in browser
2451 *
2452 * @param keyCode
2453 * @param event
2454 * @return true if handled, false to pass to super
2455 */
2456 boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002457 boolean noModifiers = event.hasNoModifiers();
2458
Michael Kolb8233fac2010-10-26 16:08:53 -07002459 // Even if MENU is already held down, we need to call to super to open
2460 // the IME on long press.
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002461 if (!noModifiers
2462 && ((KeyEvent.KEYCODE_MENU == keyCode)
2463 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
2464 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002465 mMenuIsDown = true;
2466 return false;
2467 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002468
Cary Clark8ff8c662010-12-29 15:03:05 -05002469 WebView webView = getCurrentTopWebView();
2470 if (webView == null) return false;
2471
Cary Clark160bbb92011-01-10 11:17:07 -05002472 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
2473 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05002474
Michael Kolb8233fac2010-10-26 16:08:53 -07002475 switch(keyCode) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002476 case KeyEvent.KEYCODE_ESCAPE:
Cary Clark160bbb92011-01-10 11:17:07 -05002477 if (!noModifiers) break;
Cary Clark8ff8c662010-12-29 15:03:05 -05002478 stopLoading();
2479 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07002480 case KeyEvent.KEYCODE_SPACE:
2481 // WebView/WebTextView handle the keys in the KeyDown. As
2482 // the Activity's shortcut keys are only handled when WebView
2483 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05002484 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002485 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05002486 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002487 pageDown();
2488 }
2489 return true;
2490 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05002491 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08002492 event.startTracking();
2493 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05002494 case KeyEvent.KEYCODE_DPAD_LEFT:
2495 if (ctrl) {
2496 webView.goBack();
2497 return true;
2498 }
2499 break;
2500 case KeyEvent.KEYCODE_DPAD_RIGHT:
2501 if (ctrl) {
2502 webView.goForward();
2503 return true;
2504 }
2505 break;
2506 case KeyEvent.KEYCODE_A:
2507 if (ctrl) {
2508 webView.selectAll();
2509 return true;
2510 }
2511 break;
Michael Kolba4183062011-01-16 10:43:21 -08002512// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002513 case KeyEvent.KEYCODE_C:
2514 if (ctrl) {
2515 webView.copySelection();
2516 return true;
2517 }
2518 break;
Michael Kolba4183062011-01-16 10:43:21 -08002519// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002520// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002521// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002522// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08002523// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002524// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08002525// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002526// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08002527// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002528// case KeyEvent.KEYCODE_M: // unused
2529// case KeyEvent.KEYCODE_N: // in Chrome: new window
2530// case KeyEvent.KEYCODE_O: // in Chrome: open file
2531// case KeyEvent.KEYCODE_P: // in Chrome: print page
2532// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002533// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05002534// case KeyEvent.KEYCODE_S: // in Chrome: saves page
2535 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002536 // we can't use the ctrl/shift flags, they check for
2537 // exclusive use of a modifier
2538 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05002539 if (event.isShiftPressed()) {
2540 openIncognitoTab();
2541 } else {
2542 openTabToHomePage();
2543 }
2544 return true;
2545 }
2546 break;
2547// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
2548// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolba4183062011-01-16 10:43:21 -08002549// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05002550// case KeyEvent.KEYCODE_X: // text view intercepts to cut
2551// case KeyEvent.KEYCODE_Y: // unused
2552// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07002553 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08002554 // it is a regular key and webview is not null
2555 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07002556 }
2557
John Recke6bf4ab2011-02-24 15:48:05 -08002558 boolean onKeyLongPress(int keyCode, KeyEvent event) {
2559 switch(keyCode) {
2560 case KeyEvent.KEYCODE_BACK:
2561 if (mUi.showsWeb()) {
2562 bookmarksOrHistoryPicker(true);
2563 return true;
2564 }
2565 break;
2566 }
2567 return false;
2568 }
2569
Michael Kolb8233fac2010-10-26 16:08:53 -07002570 boolean onKeyUp(int keyCode, KeyEvent event) {
Cary Clark160bbb92011-01-10 11:17:07 -05002571 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07002572 switch(keyCode) {
2573 case KeyEvent.KEYCODE_MENU:
2574 mMenuIsDown = false;
2575 break;
2576 case KeyEvent.KEYCODE_BACK:
2577 if (event.isTracking() && !event.isCanceled()) {
2578 onBackKey();
2579 return true;
2580 }
2581 break;
2582 }
2583 return false;
2584 }
2585
2586 public boolean isMenuDown() {
2587 return mMenuIsDown;
2588 }
2589
Ben Murdoch8029a772010-11-16 11:58:21 +00002590 public void setupAutoFill(Message message) {
2591 // Open the settings activity at the AutoFill profile fragment so that
2592 // the user can create a new profile. When they return, we will dispatch
2593 // the message so that we can autofill the form using their new profile.
2594 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2595 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2596 AutoFillSettingsFragment.class.getName());
2597 mAutoFillSetupMessage = message;
2598 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2599 }
John Reckb3417f02011-01-14 11:01:05 -08002600
2601 @Override
2602 public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
2603 mOptionsMenuHandler = handler;
2604 }
2605
2606 @Override
2607 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
2608 if (mOptionsMenuHandler == handler) {
2609 mOptionsMenuHandler = null;
2610 }
2611 }
2612
Michael Kolb8233fac2010-10-26 16:08:53 -07002613}