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