blob: 422fdffc9753053177629890fc3599983e1f9205 [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;
39import android.database.sqlite.SQLiteException;
40import android.graphics.Bitmap;
41import android.graphics.Canvas;
42import android.graphics.Picture;
43import android.net.Uri;
44import android.net.http.SslError;
45import android.os.AsyncTask;
46import android.os.Bundle;
47import 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;
54import android.provider.BrowserContract.History;
55import android.provider.BrowserContract.Images;
56import android.provider.ContactsContract;
57import android.provider.ContactsContract.Intents.Insert;
58import android.speech.RecognizerResultsIntent;
59import android.text.TextUtils;
60import android.util.Log;
61import android.view.ActionMode;
62import android.view.ContextMenu;
63import android.view.ContextMenu.ContextMenuInfo;
64import android.view.Gravity;
65import android.view.KeyEvent;
66import android.view.LayoutInflater;
67import 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;
81import android.widget.TextView;
82
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";
97
98 // public message ids
99 public final static int LOAD_URL = 1001;
100 public final static int STOP_LOAD = 1002;
101
102 // Message Ids
103 private static final int FOCUS_NODE_HREF = 102;
104 private static final int RELEASE_WAKELOCK = 107;
105
106 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
107
108 private static final int OPEN_BOOKMARKS = 201;
109
110 private static final int EMPTY_MENU = -1;
111
Michael Kolb8233fac2010-10-26 16:08:53 -0700112 // activity requestCode
113 final static int PREFERENCES_PAGE = 3;
114 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000115 final static int AUTOFILL_SETUP = 5;
116
Michael Kolb8233fac2010-10-26 16:08:53 -0700117 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
118
119 // As the ids are dynamically created, we can't guarantee that they will
120 // be in sequence, so this static array maps ids to a window number.
121 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
122 { R.id.window_one_menu_id, R.id.window_two_menu_id,
123 R.id.window_three_menu_id, R.id.window_four_menu_id,
124 R.id.window_five_menu_id, R.id.window_six_menu_id,
125 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
126
127 // "source" parameter for Google search through search key
128 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
129 // "source" parameter for Google search through simplily type
130 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
131
132 private Activity mActivity;
133 private UI mUi;
134 private TabControl mTabControl;
135 private BrowserSettings mSettings;
136 private WebViewFactory mFactory;
137
138 private WakeLock mWakeLock;
139
140 private UrlHandler mUrlHandler;
141 private UploadHandler mUploadHandler;
142 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700143 private PageDialogsHandler mPageDialogsHandler;
144 private NetworkStateHandler mNetworkHandler;
145
Ben Murdoch8029a772010-11-16 11:58:21 +0000146 private Message mAutoFillSetupMessage;
147
Michael Kolb8233fac2010-10-26 16:08:53 -0700148 private boolean mShouldShowErrorConsole;
149
150 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
151
152 // FIXME, temp address onPrepareMenu performance problem.
153 // When we move everything out of view, we should rewrite this.
154 private int mCurrentMenuState = 0;
155 private int mMenuState = R.id.MAIN_MENU;
156 private int mOldMenuState = EMPTY_MENU;
157 private Menu mCachedMenu;
158
159 // Used to prevent chording to result in firing two shortcuts immediately
160 // one after another. Fixes bug 1211714.
161 boolean mCanChord;
162 private boolean mMenuIsDown;
163
164 // For select and find, we keep track of the ActionMode so that
165 // finish() can be called as desired.
166 private ActionMode mActionMode;
167
168 /**
169 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
170 * of whether the configuration has changed. The first onMenuOpened call
171 * after a configuration change is simply a reopening of the same menu
172 * (i.e. mIconView did not change).
173 */
174 private boolean mConfigChanged;
175
176 /**
177 * Keeps track of whether the options menu is open. This is important in
178 * determining whether to show or hide the title bar overlay
179 */
180 private boolean mOptionsMenuOpen;
181
182 /**
183 * Whether or not the options menu is in its bigger, popup menu form. When
184 * true, we want the title bar overlay to be gone. When false, we do not.
185 * Only meaningful if mOptionsMenuOpen is true.
186 */
187 private boolean mExtendedMenuOpen;
188
189 private boolean mInLoad;
190
191 private boolean mActivityPaused = true;
192 private boolean mLoadStopped;
193
194 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500195 // Checks to see when the bookmarks database has changed, and updates the
196 // Tabs' notion of whether they represent bookmarked sites.
197 private ContentObserver mBookmarksObserver;
John Reck0ebd3ac2010-12-09 11:14:04 -0800198 private DataController mDataController;
Michael Kolb8233fac2010-10-26 16:08:53 -0700199
200 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
201 @Override
202 public Void doInBackground(File... files) {
203 if (files != null) {
204 for (File f : files) {
205 if (!f.delete()) {
206 Log.e(LOGTAG, f.getPath() + " was not deleted");
207 }
208 }
209 }
210 return null;
211 }
212 }
213
214 public Controller(Activity browser) {
215 mActivity = browser;
216 mSettings = BrowserSettings.getInstance();
John Reck0ebd3ac2010-12-09 11:14:04 -0800217 mDataController = DataController.getInstance(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700218 mTabControl = new TabControl(this);
219 mSettings.setController(this);
220
221 mUrlHandler = new UrlHandler(this);
222 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700223 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
224
225 PowerManager pm = (PowerManager) mActivity
226 .getSystemService(Context.POWER_SERVICE);
227 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
228
229 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500230 mBookmarksObserver = new ContentObserver(mHandler) {
231 @Override
232 public void onChange(boolean selfChange) {
233 int size = mTabControl.getTabCount();
234 for (int i = 0; i < size; i++) {
235 mTabControl.getTab(i).updateBookmarkedStatus();
236 }
237 }
238
239 };
240 browser.getContentResolver().registerContentObserver(
241 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700242
243 mNetworkHandler = new NetworkStateHandler(mActivity, this);
244 // Start watching the default geolocation permissions
245 mSystemAllowGeolocationOrigins =
246 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
247 mSystemAllowGeolocationOrigins.start();
248
249 retainIconsOnStartup();
250 }
251
252 void start(Bundle icicle, Intent intent) {
253 // Unless the last browser usage was within 24 hours, destroy any
254 // remaining incognito tabs.
255
256 Calendar lastActiveDate = icicle != null ?
257 (Calendar) icicle.getSerializable("lastActiveDate") : null;
258 Calendar today = Calendar.getInstance();
259 Calendar yesterday = Calendar.getInstance();
260 yesterday.add(Calendar.DATE, -1);
261
Michael Kolb1bf23132010-11-19 12:55:12 -0800262 boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb8233fac2010-10-26 16:08:53 -0700263 || lastActiveDate.before(yesterday)
Michael Kolb1bf23132010-11-19 12:55:12 -0800264 || lastActiveDate.after(today));
Michael Kolb8233fac2010-10-26 16:08:53 -0700265
Michael Kolb1bf23132010-11-19 12:55:12 -0800266 if (!mTabControl.restoreState(icicle, restoreIncognitoTabs,
267 mUi.needsRestoreAllTabs())) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700268 // there is no quit on Android. But if we can't restore the state,
269 // we can treat it as a new Browser, remove the old session cookies.
Kristian Monsen3a4e8092010-12-08 11:09:25 +0000270 // This is done async in the CookieManager.
271 CookieManager.getInstance().removeSessionCookie();
Kristian Monsen2cd97012010-12-07 11:11:40 +0000272
Michael Kolb8233fac2010-10-26 16:08:53 -0700273 final Bundle extra = intent.getExtras();
274 // Create an initial tab.
275 // If the intent is ACTION_VIEW and data is not null, the Browser is
276 // invoked to view the content by another application. In this case,
277 // the tab will be close when exit.
278 UrlData urlData = mIntentHandler.getUrlDataFromIntent(intent);
279
280 String action = intent.getAction();
281 final Tab t = mTabControl.createNewTab(
282 (Intent.ACTION_VIEW.equals(action) &&
283 intent.getData() != null)
284 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
285 .equals(action),
286 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
287 urlData.mUrl, false);
288 addTab(t);
289 setActiveTab(t);
290 WebView webView = t.getWebView();
291 if (extra != null) {
292 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
293 if (scale > 0 && scale <= 1000) {
294 webView.setInitialScale(scale);
295 }
296 }
297
298 if (urlData.isEmpty()) {
299 loadUrl(webView, mSettings.getHomePage());
300 } else {
301 loadUrlDataIn(t, urlData);
302 }
303 } else {
Michael Kolb1bf23132010-11-19 12:55:12 -0800304 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700305 // TabControl.restoreState() will create a new tab even if
306 // restoring the state fails.
307 setActiveTab(mTabControl.getCurrentTab());
308 }
309 // clear up the thumbnail directory, which is no longer used;
310 // ideally this should only be run once after an upgrade from
311 // a previous version of the browser
312 new ClearThumbnails().execute(mTabControl.getThumbnailDir()
313 .listFiles());
314 // Read JavaScript flags if it exists.
315 String jsFlags = getSettings().getJsFlags();
316 if (jsFlags.trim().length() != 0) {
317 getCurrentWebView().setJsFlags(jsFlags);
318 }
319 }
320
321 void setWebViewFactory(WebViewFactory factory) {
322 mFactory = factory;
323 }
324
Michael Kolb1514bb72010-11-22 09:11:48 -0800325 @Override
326 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700327 return mFactory;
328 }
329
330 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800331 public void onSetWebView(Tab tab, WebView view) {
332 mUi.onSetWebView(tab, view);
333 }
334
335 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800336 public void createSubWindow(Tab tab) {
337 endActionMode();
338 WebView mainView = tab.getWebView();
339 WebView subView = mFactory.createWebView((mainView == null)
340 ? false
341 : mainView.isPrivateBrowsingEnabled());
342 mUi.createSubWindow(tab, subView);
343 }
344
345 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700346 public Activity getActivity() {
347 return mActivity;
348 }
349
350 void setUi(UI ui) {
351 mUi = ui;
352 }
353
354 BrowserSettings getSettings() {
355 return mSettings;
356 }
357
358 IntentHandler getIntentHandler() {
359 return mIntentHandler;
360 }
361
362 @Override
363 public UI getUi() {
364 return mUi;
365 }
366
367 int getMaxTabs() {
368 return mActivity.getResources().getInteger(R.integer.max_tabs);
369 }
370
371 @Override
372 public TabControl getTabControl() {
373 return mTabControl;
374 }
375
Michael Kolb1bf23132010-11-19 12:55:12 -0800376 @Override
377 public List<Tab> getTabs() {
378 return mTabControl.getTabs();
379 }
380
Michael Kolb8233fac2010-10-26 16:08:53 -0700381 // Open the icon database and retain all the icons for visited sites.
Ben Murdoch9446b932010-11-25 16:20:14 +0000382 // This is done on a background thread so as not to stall startup.
Michael Kolb8233fac2010-10-26 16:08:53 -0700383 private void retainIconsOnStartup() {
Ben Murdoch9446b932010-11-25 16:20:14 +0000384 // WebIconDatabase needs to be retrieved on the UI thread so that if
385 // it has not been created successfully yet the Handler is started on the
386 // UI thread.
387 new RetainIconsOnStartupTask(WebIconDatabase.getInstance()).execute();
388 }
389
390 private class RetainIconsOnStartupTask extends AsyncTask<Void, Void, Void> {
391 private WebIconDatabase mDb;
392
393 public RetainIconsOnStartupTask(WebIconDatabase db) {
394 mDb = db;
395 }
396
397 protected Void doInBackground(Void... unused) {
398 mDb.open(mActivity.getDir("icons", 0).getPath());
399 Cursor c = null;
400 try {
401 c = Browser.getAllBookmarks(mActivity.getContentResolver());
402 if (c.moveToFirst()) {
403 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
404 do {
405 String url = c.getString(urlIndex);
406 mDb.retainIconForPageUrl(url);
407 } while (c.moveToNext());
408 }
409 } catch (IllegalStateException e) {
410 Log.e(LOGTAG, "retainIconsOnStartup", e);
411 } finally {
412 if (c != null) c.close();
Michael Kolb8233fac2010-10-26 16:08:53 -0700413 }
Ben Murdoch9446b932010-11-25 16:20:14 +0000414
415 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -0700416 }
417 }
418
419 private void startHandler() {
420 mHandler = new Handler() {
421
422 @Override
423 public void handleMessage(Message msg) {
424 switch (msg.what) {
425 case OPEN_BOOKMARKS:
426 bookmarksOrHistoryPicker(false);
427 break;
428 case FOCUS_NODE_HREF:
429 {
430 String url = (String) msg.getData().get("url");
431 String title = (String) msg.getData().get("title");
432 if (TextUtils.isEmpty(url)) {
433 break;
434 }
435 HashMap focusNodeMap = (HashMap) msg.obj;
436 WebView view = (WebView) focusNodeMap.get("webview");
437 // Only apply the action if the top window did not change.
438 if (getCurrentTopWebView() != view) {
439 break;
440 }
441 switch (msg.arg1) {
442 case R.id.open_context_menu_id:
443 case R.id.view_image_context_menu_id:
444 loadUrlFromContext(getCurrentTopWebView(), url);
445 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500446 case R.id.open_newtab_context_menu_id:
447 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -0800448 final Tab newTab = openTab(parent, url, false);
Leon Scroggins026f2542010-11-22 13:26:12 -0500449 if (newTab != null && newTab != parent) {
450 parent.addChildTab(newTab);
451 }
452 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700453 case R.id.bookmark_context_menu_id:
454 Intent intent = new Intent(mActivity,
455 AddBookmarkPage.class);
456 intent.putExtra(BrowserContract.Bookmarks.URL, url);
457 intent.putExtra(BrowserContract.Bookmarks.TITLE,
458 title);
459 mActivity.startActivity(intent);
460 break;
461 case R.id.share_link_context_menu_id:
462 sharePage(mActivity, title, url, null,
463 null);
464 break;
465 case R.id.copy_link_context_menu_id:
466 copy(url);
467 break;
468 case R.id.save_link_context_menu_id:
469 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500470 DownloadHandler.onDownloadStartNoStream(
471 mActivity, url, null, null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -0700472 break;
473 }
474 break;
475 }
476
477 case LOAD_URL:
478 loadUrlFromContext(getCurrentTopWebView(), (String) msg.obj);
479 break;
480
481 case STOP_LOAD:
482 stopLoading();
483 break;
484
485 case RELEASE_WAKELOCK:
486 if (mWakeLock.isHeld()) {
487 mWakeLock.release();
488 // if we reach here, Browser should be still in the
489 // background loading after WAKELOCK_TIMEOUT (5-min).
490 // To avoid burning the battery, stop loading.
491 mTabControl.stopAllLoading();
492 }
493 break;
494
495 case UPDATE_BOOKMARK_THUMBNAIL:
496 WebView view = (WebView) msg.obj;
497 if (view != null) {
498 updateScreenshot(view);
499 }
500 break;
501 }
502 }
503 };
504
505 }
506
Michael Kolbba99c5d2010-11-29 14:57:41 -0800507 @Override
508 public void shareCurrentPage() {
509 shareCurrentPage(mTabControl.getCurrentTab());
510 }
511
512 private void shareCurrentPage(Tab tab) {
513 if (tab != null) {
514 tab.populatePickerData();
515 sharePage(mActivity, tab.getTitle(),
516 tab.getUrl(), tab.getFavicon(),
517 createScreenshot(tab.getWebView(),
518 getDesiredThumbnailWidth(mActivity),
519 getDesiredThumbnailHeight(mActivity)));
520 }
521 }
522
Michael Kolb8233fac2010-10-26 16:08:53 -0700523 /**
524 * Share a page, providing the title, url, favicon, and a screenshot. Uses
525 * an {@link Intent} to launch the Activity chooser.
526 * @param c Context used to launch a new Activity.
527 * @param title Title of the page. Stored in the Intent with
528 * {@link Intent#EXTRA_SUBJECT}
529 * @param url URL of the page. Stored in the Intent with
530 * {@link Intent#EXTRA_TEXT}
531 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
532 * with {@link Browser#EXTRA_SHARE_FAVICON}
533 * @param screenshot Bitmap of a screenshot of the page. Stored in the
534 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
535 */
536 static final void sharePage(Context c, String title, String url,
537 Bitmap favicon, Bitmap screenshot) {
538 Intent send = new Intent(Intent.ACTION_SEND);
539 send.setType("text/plain");
540 send.putExtra(Intent.EXTRA_TEXT, url);
541 send.putExtra(Intent.EXTRA_SUBJECT, title);
542 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
543 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
544 try {
545 c.startActivity(Intent.createChooser(send, c.getString(
546 R.string.choosertitle_sharevia)));
547 } catch(android.content.ActivityNotFoundException ex) {
548 // if no app handles it, do nothing
549 }
550 }
551
552 private void copy(CharSequence text) {
553 ClipboardManager cm = (ClipboardManager) mActivity
554 .getSystemService(Context.CLIPBOARD_SERVICE);
555 cm.setText(text);
556 }
557
558 // lifecycle
559
560 protected void onConfgurationChanged(Configuration config) {
561 mConfigChanged = true;
562 if (mPageDialogsHandler != null) {
563 mPageDialogsHandler.onConfigurationChanged(config);
564 }
565 mUi.onConfigurationChanged(config);
566 }
567
568 @Override
569 public void handleNewIntent(Intent intent) {
570 mIntentHandler.onNewIntent(intent);
571 }
572
573 protected void onPause() {
574 if (mActivityPaused) {
575 Log.e(LOGTAG, "BrowserActivity is already paused.");
576 return;
577 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700578 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800579 Tab tab = mTabControl.getCurrentTab();
580 if (tab != null) {
581 tab.pause();
582 if (!pauseWebViewTimers(tab)) {
583 mWakeLock.acquire();
584 mHandler.sendMessageDelayed(mHandler
585 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
586 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700587 }
588 mUi.onPause();
589 mNetworkHandler.onPause();
590
591 WebView.disablePlatformNotifications();
592 }
593
594 void onSaveInstanceState(Bundle outState) {
595 // the default implementation requires each view to have an id. As the
596 // browser handles the state itself and it doesn't use id for the views,
597 // don't call the default implementation. Otherwise it will trigger the
598 // warning like this, "couldn't save which view has focus because the
599 // focused view XXX has no id".
600
601 // Save all the tabs
602 mTabControl.saveState(outState);
603 // Save time so that we know how old incognito tabs (if any) are.
604 outState.putSerializable("lastActiveDate", Calendar.getInstance());
605 }
606
607 void onResume() {
608 if (!mActivityPaused) {
609 Log.e(LOGTAG, "BrowserActivity is already resumed.");
610 return;
611 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700612 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800613 Tab current = mTabControl.getCurrentTab();
614 if (current != null) {
615 current.resume();
616 resumeWebViewTimers(current);
617 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700618 if (mWakeLock.isHeld()) {
619 mHandler.removeMessages(RELEASE_WAKELOCK);
620 mWakeLock.release();
621 }
622 mUi.onResume();
623 mNetworkHandler.onResume();
624 WebView.enablePlatformNotifications();
625 }
626
Michael Kolb70976932010-11-30 11:34:01 -0800627 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800628 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800629 * @param tab guaranteed non-null
630 */
631 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700632 boolean inLoad = tab.inPageLoad();
633 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
634 CookieSyncManager.getInstance().startSync();
635 WebView w = tab.getWebView();
636 if (w != null) {
637 w.resumeTimers();
638 }
639 }
640 }
641
Michael Kolb70976932010-11-30 11:34:01 -0800642 /**
643 * Pause all WebView timers using the WebView of the given tab
644 * @param tab
645 * @return true if the timers are paused or tab is null
646 */
647 private boolean pauseWebViewTimers(Tab tab) {
648 if (tab == null) {
649 return true;
650 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700651 CookieSyncManager.getInstance().stopSync();
652 WebView w = getCurrentWebView();
653 if (w != null) {
654 w.pauseTimers();
655 }
656 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700657 }
Michael Kolb70976932010-11-30 11:34:01 -0800658 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700659 }
660
661 void onDestroy() {
662 if (mUploadHandler != null) {
663 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
664 mUploadHandler = null;
665 }
666 if (mTabControl == null) return;
667 mUi.onDestroy();
668 // Remove the current tab and sub window
669 Tab t = mTabControl.getCurrentTab();
670 if (t != null) {
671 dismissSubWindow(t);
672 removeTab(t);
673 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500674 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700675 // Destroy all the tabs
676 mTabControl.destroy();
677 WebIconDatabase.getInstance().close();
678 // Stop watching the default geolocation permissions
679 mSystemAllowGeolocationOrigins.stop();
680 mSystemAllowGeolocationOrigins = null;
681 }
682
683 protected boolean isActivityPaused() {
684 return mActivityPaused;
685 }
686
687 protected void onLowMemory() {
688 mTabControl.freeMemory();
689 }
690
691 @Override
692 public boolean shouldShowErrorConsole() {
693 return mShouldShowErrorConsole;
694 }
695
696 protected void setShouldShowErrorConsole(boolean show) {
697 if (show == mShouldShowErrorConsole) {
698 // Nothing to do.
699 return;
700 }
701 mShouldShowErrorConsole = show;
702 Tab t = mTabControl.getCurrentTab();
703 if (t == null) {
704 // There is no current tab so we cannot toggle the error console
705 return;
706 }
707 mUi.setShouldShowErrorConsole(t, show);
708 }
709
710 @Override
711 public void stopLoading() {
712 mLoadStopped = true;
713 Tab tab = mTabControl.getCurrentTab();
714 resetTitleAndRevertLockIcon(tab);
715 WebView w = getCurrentTopWebView();
716 w.stopLoading();
717 // FIXME: before refactor, it is using mWebViewClient. So I keep the
718 // same logic here. But for subwindow case, should we call into the main
719 // WebView's onPageFinished as we never call its onPageStarted and if
720 // the page finishes itself, we don't call onPageFinished.
721 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
722 w.getUrl());
723 mUi.onPageStopped(tab);
724 }
725
726 boolean didUserStopLoading() {
727 return mLoadStopped;
728 }
729
730 // WebViewController
731
732 @Override
733 public void onPageStarted(Tab tab, WebView view, String url, Bitmap favicon) {
734
735 // We've started to load a new page. If there was a pending message
736 // to save a screenshot then we will now take the new page and save
737 // an incorrect screenshot. Therefore, remove any pending thumbnail
738 // messages from the queue.
739 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
740 view);
741
742 // reset sync timer to avoid sync starts during loading a page
743 CookieSyncManager.getInstance().resetSync();
744
745 if (!mNetworkHandler.isNetworkUp()) {
746 view.setNetworkAvailable(false);
747 }
748
749 // when BrowserActivity just starts, onPageStarted may be called before
750 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
751 // to start the timer. As we won't switch tabs while an activity is in
752 // pause state, we can ensure calling resume and pause in pair.
753 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800754 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700755 }
756 mLoadStopped = false;
757 if (!mNetworkHandler.isNetworkUp()) {
758 mNetworkHandler.createAndShowNetworkDialog();
759 }
760 endActionMode();
761
762 mUi.onPageStarted(tab, url, favicon);
763
Michael Kolb8233fac2010-10-26 16:08:53 -0700764 // update the bookmark database for favicon
765 maybeUpdateFavicon(tab, null, url, favicon);
766
767 Performance.tracePageStart(url);
768
769 // Performance probe
770 if (false) {
771 Performance.onPageStarted();
772 }
773
774 }
775
776 @Override
777 public void onPageFinished(Tab tab, String url) {
778 mUi.onPageFinished(tab, url);
779 if (!tab.isPrivateBrowsingEnabled()) {
780 if (tab.inForeground() && !didUserStopLoading()
781 || !tab.inForeground()) {
782 // Only update the bookmark screenshot if the user did not
783 // cancel the load early.
784 mHandler.sendMessageDelayed(mHandler.obtainMessage(
785 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab.getWebView()),
786 500);
787 }
788 }
789 // pause the WebView timer and release the wake lock if it is finished
790 // while BrowserActivity is in pause state.
Michael Kolb70976932010-11-30 11:34:01 -0800791 if (mActivityPaused && pauseWebViewTimers(tab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700792 if (mWakeLock.isHeld()) {
793 mHandler.removeMessages(RELEASE_WAKELOCK);
794 mWakeLock.release();
795 }
796 }
797 // Performance probe
798 if (false) {
799 Performance.onPageFinished(url);
800 }
801
802 Performance.tracePageFinished();
803 }
804
805 @Override
806 public void onProgressChanged(Tab tab, int newProgress) {
807
808 if (newProgress == 100) {
809 CookieSyncManager.getInstance().sync();
810 // onProgressChanged() may continue to be called after the main
811 // frame has finished loading, as any remaining sub frames continue
812 // to load. We'll only get called once though with newProgress as
813 // 100 when everything is loaded. (onPageFinished is called once
814 // when the main frame completes loading regardless of the state of
815 // any sub frames so calls to onProgressChanges may continue after
816 // onPageFinished has executed)
817 if (mInLoad) {
818 mInLoad = false;
819 updateInLoadMenuItems(mCachedMenu);
820 }
821 } else {
822 if (!mInLoad) {
823 // onPageFinished may have already been called but a subframe is
824 // still loading and updating the progress. Reset mInLoad and
825 // update the menu items.
826 mInLoad = true;
827 updateInLoadMenuItems(mCachedMenu);
828 }
829 }
830 mUi.onProgressChanged(tab, newProgress);
831 }
832
833 @Override
834 public void onReceivedTitle(Tab tab, final String title) {
835 final String pageUrl = tab.getWebView().getUrl();
836 setUrlTitle(tab, pageUrl, title);
837 if (pageUrl == null || pageUrl.length()
838 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
839 return;
840 }
841 // Update the title in the history database if not in private browsing mode
842 if (!tab.isPrivateBrowsingEnabled()) {
John Reck0ebd3ac2010-12-09 11:14:04 -0800843 mDataController.updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -0700844 }
845 }
846
847 @Override
848 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
849 mUi.setFavicon(tab, icon);
850 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
851 }
852
853 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -0800854 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
855 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700856 }
857
858 @Override
859 public boolean shouldOverrideKeyEvent(KeyEvent event) {
860 if (mMenuIsDown) {
861 // only check shortcut key when MENU is held
862 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
863 event);
864 } else {
865 return false;
866 }
867 }
868
869 @Override
870 public void onUnhandledKeyEvent(KeyEvent event) {
871 if (!isActivityPaused()) {
872 if (event.getAction() == KeyEvent.ACTION_DOWN) {
873 mActivity.onKeyDown(event.getKeyCode(), event);
874 } else {
875 mActivity.onKeyUp(event.getKeyCode(), event);
876 }
877 }
878 }
879
880 @Override
881 public void doUpdateVisitedHistory(Tab tab, String url,
882 boolean isReload) {
883 // Don't save anything in private browsing mode
884 if (tab.isPrivateBrowsingEnabled()) return;
885
886 if (url.regionMatches(true, 0, "about:", 0, 6)) {
887 return;
888 }
John Reck0ebd3ac2010-12-09 11:14:04 -0800889 mDataController.updateVisitedHistory(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700890 WebIconDatabase.getInstance().retainIconForPageUrl(url);
891 }
892
893 @Override
894 public void getVisitedHistory(final ValueCallback<String[]> callback) {
895 AsyncTask<Void, Void, String[]> task =
896 new AsyncTask<Void, Void, String[]>() {
897 @Override
898 public String[] doInBackground(Void... unused) {
899 return Browser.getVisitedHistory(mActivity.getContentResolver());
900 }
901 @Override
902 public void onPostExecute(String[] result) {
903 callback.onReceiveValue(result);
904 }
905 };
906 task.execute();
907 }
908
909 @Override
910 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
911 final HttpAuthHandler handler, final String host,
912 final String realm) {
913 String username = null;
914 String password = null;
915
916 boolean reuseHttpAuthUsernamePassword
917 = handler.useHttpAuthUsernamePassword();
918
919 if (reuseHttpAuthUsernamePassword && view != null) {
920 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
921 if (credentials != null && credentials.length == 2) {
922 username = credentials[0];
923 password = credentials[1];
924 }
925 }
926
927 if (username != null && password != null) {
928 handler.proceed(username, password);
929 } else {
930 if (tab.inForeground()) {
931 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
932 } else {
933 handler.cancel();
934 }
935 }
936 }
937
938 @Override
939 public void onDownloadStart(Tab tab, String url, String userAgent,
940 String contentDisposition, String mimetype, long contentLength) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500941 DownloadHandler.onDownloadStart(mActivity, url, userAgent,
942 contentDisposition, mimetype);
Michael Kolb8233fac2010-10-26 16:08:53 -0700943 if (tab.getWebView().copyBackForwardList().getSize() == 0) {
944 // This Tab was opened for the sole purpose of downloading a
945 // file. Remove it.
946 if (tab == mTabControl.getCurrentTab()) {
947 // In this case, the Tab is still on top.
948 goBackOnePageOrQuit();
949 } else {
950 // In this case, it is not.
951 closeTab(tab);
952 }
953 }
954 }
955
956 @Override
957 public Bitmap getDefaultVideoPoster() {
958 return mUi.getDefaultVideoPoster();
959 }
960
961 @Override
962 public View getVideoLoadingProgressView() {
963 return mUi.getVideoLoadingProgressView();
964 }
965
966 @Override
967 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
968 SslError error) {
969 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
970 }
971
972 // helper method
973
974 /*
975 * Update the favorites icon if the private browsing isn't enabled and the
976 * icon is valid.
977 */
978 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
979 final String url, Bitmap favicon) {
980 if (favicon == null) {
981 return;
982 }
983 if (!tab.isPrivateBrowsingEnabled()) {
984 Bookmarks.updateFavicon(mActivity
985 .getContentResolver(), originalUrl, url, favicon);
986 }
987 }
988
Leon Scroggins4cd97792010-12-03 15:31:56 -0500989 @Override
990 public void bookmarkedStatusHasChanged(Tab tab) {
991 mUi.bookmarkedStatusHasChanged(tab);
992 }
993
Michael Kolb8233fac2010-10-26 16:08:53 -0700994 // end WebViewController
995
996 protected void pageUp() {
997 getCurrentTopWebView().pageUp(false);
998 }
999
1000 protected void pageDown() {
1001 getCurrentTopWebView().pageDown(false);
1002 }
1003
1004 // callback from phone title bar
1005 public void editUrl() {
1006 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
1007 String url = (getCurrentTopWebView() == null) ? null : getCurrentTopWebView().getUrl();
1008 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1009 null, false);
1010 }
1011
1012 public void activateVoiceSearchMode(String title) {
1013 mUi.showVoiceTitleBar(title);
1014 }
1015
1016 public void revertVoiceSearchMode(Tab tab) {
1017 mUi.revertVoiceTitleBar(tab);
1018 }
1019
1020 public void showCustomView(Tab tab, View view,
1021 WebChromeClient.CustomViewCallback callback) {
1022 if (tab.inForeground()) {
1023 if (mUi.isCustomViewShowing()) {
1024 callback.onCustomViewHidden();
1025 return;
1026 }
1027 mUi.showCustomView(view, callback);
1028 // Save the menu state and set it to empty while the custom
1029 // view is showing.
1030 mOldMenuState = mMenuState;
1031 mMenuState = EMPTY_MENU;
1032 }
1033 }
1034
1035 @Override
1036 public void hideCustomView() {
1037 if (mUi.isCustomViewShowing()) {
1038 mUi.onHideCustomView();
1039 // Reset the old menu state.
1040 mMenuState = mOldMenuState;
1041 mOldMenuState = EMPTY_MENU;
1042 }
1043 }
1044
1045 protected void onActivityResult(int requestCode, int resultCode,
1046 Intent intent) {
1047 if (getCurrentTopWebView() == null) return;
1048 switch (requestCode) {
1049 case PREFERENCES_PAGE:
1050 if (resultCode == Activity.RESULT_OK && intent != null) {
1051 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
1052 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
1053 mTabControl.removeParentChildRelationShips();
1054 }
1055 }
1056 break;
1057 case FILE_SELECTED:
1058 // Choose a file from the file picker.
1059 if (null == mUploadHandler) break;
1060 mUploadHandler.onResult(resultCode, intent);
1061 mUploadHandler = null;
1062 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001063 case AUTOFILL_SETUP:
1064 // Determine whether a profile was actually set up or not
1065 // and if so, send the message back to the WebTextView to
1066 // fill the form with the new profile.
1067 if (getSettings().getAutoFillProfile() != null) {
1068 mAutoFillSetupMessage.sendToTarget();
1069 mAutoFillSetupMessage = null;
1070 }
1071 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001072 default:
1073 break;
1074 }
1075 getCurrentTopWebView().requestFocus();
1076 }
1077
1078 /**
1079 * Open the Go page.
1080 * @param startWithHistory If true, open starting on the history tab.
1081 * Otherwise, start with the bookmarks tab.
1082 */
1083 @Override
1084 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1085 if (mTabControl.getCurrentWebView() == null) {
1086 return;
1087 }
1088 Bundle extras = new Bundle();
1089 // Disable opening in a new window if we have maxed out the windows
1090 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1091 !mTabControl.canCreateNewTab());
1092 mUi.showComboView(startWithHistory, extras);
1093 }
1094
1095 // combo view callbacks
1096
1097 /**
1098 * callback from ComboPage when clear history is requested
1099 */
1100 public void onRemoveParentChildRelationships() {
1101 mTabControl.removeParentChildRelationShips();
1102 }
1103
1104 /**
1105 * callback from ComboPage when bookmark/history selection
1106 */
1107 @Override
1108 public void onUrlSelected(String url, boolean newTab) {
1109 removeComboView();
1110 if (!TextUtils.isEmpty(url)) {
1111 if (newTab) {
Michael Kolb18eb3772010-12-10 14:29:51 -08001112 openTab(mTabControl.getCurrentTab(), url, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07001113 } else {
1114 final Tab currentTab = mTabControl.getCurrentTab();
1115 dismissSubWindow(currentTab);
1116 loadUrl(getCurrentTopWebView(), url);
1117 }
1118 }
1119 }
1120
1121 /**
1122 * callback from ComboPage when dismissed
1123 */
1124 @Override
1125 public void onComboCanceled() {
1126 removeComboView();
1127 }
1128
1129 /**
1130 * dismiss the ComboPage
1131 */
1132 @Override
1133 public void removeComboView() {
1134 mUi.hideComboView();
1135 }
1136
1137 // active tabs page handling
1138
1139 protected void showActiveTabsPage() {
1140 mMenuState = EMPTY_MENU;
1141 mUi.showActiveTabsPage();
1142 }
1143
1144 /**
1145 * Remove the active tabs page.
1146 * @param needToAttach If true, the active tabs page did not attach a tab
1147 * to the content view, so we need to do that here.
1148 */
1149 @Override
1150 public void removeActiveTabsPage(boolean needToAttach) {
1151 mMenuState = R.id.MAIN_MENU;
1152 mUi.removeActiveTabsPage();
1153 if (needToAttach) {
1154 setActiveTab(mTabControl.getCurrentTab());
1155 }
1156 getCurrentTopWebView().requestFocus();
1157 }
1158
1159 // key handling
1160 protected void onBackKey() {
1161 if (!mUi.onBackKey()) {
1162 WebView subwindow = mTabControl.getCurrentSubWindow();
1163 if (subwindow != null) {
1164 if (subwindow.canGoBack()) {
1165 subwindow.goBack();
1166 } else {
1167 dismissSubWindow(mTabControl.getCurrentTab());
1168 }
1169 } else {
1170 goBackOnePageOrQuit();
1171 }
1172 }
1173 }
1174
1175 // menu handling and state
1176 // TODO: maybe put into separate handler
1177
1178 protected boolean onCreateOptionsMenu(Menu menu) {
1179 MenuInflater inflater = mActivity.getMenuInflater();
1180 inflater.inflate(R.menu.browser, menu);
1181 updateInLoadMenuItems(menu);
1182 // hold on to the menu reference here; it is used by the page callbacks
1183 // to update the menu based on loading state
1184 mCachedMenu = menu;
1185 return true;
1186 }
1187
1188 protected void onCreateContextMenu(ContextMenu menu, View v,
1189 ContextMenuInfo menuInfo) {
1190 if (v instanceof TitleBarBase) {
1191 return;
1192 }
1193 if (!(v instanceof WebView)) {
1194 return;
1195 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001196 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001197 WebView.HitTestResult result = webview.getHitTestResult();
1198 if (result == null) {
1199 return;
1200 }
1201
1202 int type = result.getType();
1203 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1204 Log.w(LOGTAG,
1205 "We should not show context menu when nothing is touched");
1206 return;
1207 }
1208 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1209 // let TextView handles context menu
1210 return;
1211 }
1212
1213 // Note, http://b/issue?id=1106666 is requesting that
1214 // an inflated menu can be used again. This is not available
1215 // yet, so inflate each time (yuk!)
1216 MenuInflater inflater = mActivity.getMenuInflater();
1217 inflater.inflate(R.menu.browsercontext, menu);
1218
1219 // Show the correct menu group
1220 final String extra = result.getExtra();
1221 menu.setGroupVisible(R.id.PHONE_MENU,
1222 type == WebView.HitTestResult.PHONE_TYPE);
1223 menu.setGroupVisible(R.id.EMAIL_MENU,
1224 type == WebView.HitTestResult.EMAIL_TYPE);
1225 menu.setGroupVisible(R.id.GEO_MENU,
1226 type == WebView.HitTestResult.GEO_TYPE);
1227 menu.setGroupVisible(R.id.IMAGE_MENU,
1228 type == WebView.HitTestResult.IMAGE_TYPE
1229 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1230 menu.setGroupVisible(R.id.ANCHOR_MENU,
1231 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1232 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001233 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1234 || type == WebView.HitTestResult.PHONE_TYPE
1235 || type == WebView.HitTestResult.EMAIL_TYPE
1236 || type == WebView.HitTestResult.GEO_TYPE;
1237 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1238 if (hitText) {
1239 menu.findItem(R.id.select_text_menu_id)
1240 .setOnMenuItemClickListener(new SelectText(webview));
1241 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001242 // Setup custom handling depending on the type
1243 switch (type) {
1244 case WebView.HitTestResult.PHONE_TYPE:
1245 menu.setHeaderTitle(Uri.decode(extra));
1246 menu.findItem(R.id.dial_context_menu_id).setIntent(
1247 new Intent(Intent.ACTION_VIEW, Uri
1248 .parse(WebView.SCHEME_TEL + extra)));
1249 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1250 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1251 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1252 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1253 addIntent);
1254 menu.findItem(R.id.copy_phone_context_menu_id)
1255 .setOnMenuItemClickListener(
1256 new Copy(extra));
1257 break;
1258
1259 case WebView.HitTestResult.EMAIL_TYPE:
1260 menu.setHeaderTitle(extra);
1261 menu.findItem(R.id.email_context_menu_id).setIntent(
1262 new Intent(Intent.ACTION_VIEW, Uri
1263 .parse(WebView.SCHEME_MAILTO + extra)));
1264 menu.findItem(R.id.copy_mail_context_menu_id)
1265 .setOnMenuItemClickListener(
1266 new Copy(extra));
1267 break;
1268
1269 case WebView.HitTestResult.GEO_TYPE:
1270 menu.setHeaderTitle(extra);
1271 menu.findItem(R.id.map_context_menu_id).setIntent(
1272 new Intent(Intent.ACTION_VIEW, Uri
1273 .parse(WebView.SCHEME_GEO
1274 + URLEncoder.encode(extra))));
1275 menu.findItem(R.id.copy_geo_context_menu_id)
1276 .setOnMenuItemClickListener(
1277 new Copy(extra));
1278 break;
1279
1280 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1281 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1282 TextView titleView = (TextView) LayoutInflater.from(mActivity)
1283 .inflate(android.R.layout.browser_link_context_header,
1284 null);
1285 titleView.setText(extra);
1286 menu.setHeaderView(titleView);
1287 // decide whether to show the open link in new tab option
1288 boolean showNewTab = mTabControl.canCreateNewTab();
1289 MenuItem newTabItem
1290 = menu.findItem(R.id.open_newtab_context_menu_id);
1291 newTabItem.setVisible(showNewTab);
1292 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001293 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1294 newTabItem.setOnMenuItemClickListener(
1295 new MenuItem.OnMenuItemClickListener() {
1296 @Override
1297 public boolean onMenuItemClick(MenuItem item) {
1298 final HashMap<String, WebView> hrefMap =
1299 new HashMap<String, WebView>();
1300 hrefMap.put("webview", webview);
1301 final Message msg = mHandler.obtainMessage(
1302 FOCUS_NODE_HREF,
1303 R.id.open_newtab_context_menu_id,
1304 0, hrefMap);
1305 webview.requestFocusNodeHref(msg);
1306 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001307 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001308 });
1309 } else {
1310 newTabItem.setOnMenuItemClickListener(
1311 new MenuItem.OnMenuItemClickListener() {
1312 @Override
1313 public boolean onMenuItemClick(MenuItem item) {
1314 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb18eb3772010-12-10 14:29:51 -08001315 final Tab newTab = openTab(parent,
1316 extra, false);
Leon Scroggins026f2542010-11-22 13:26:12 -05001317 if (newTab != parent) {
1318 parent.addChildTab(newTab);
1319 }
1320 return true;
1321 }
1322 });
1323 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001324 }
1325 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1326 Bookmarks.urlHasAcceptableScheme(extra));
1327 PackageManager pm = mActivity.getPackageManager();
1328 Intent send = new Intent(Intent.ACTION_SEND);
1329 send.setType("text/plain");
1330 ResolveInfo ri = pm.resolveActivity(send,
1331 PackageManager.MATCH_DEFAULT_ONLY);
1332 menu.findItem(R.id.share_link_context_menu_id)
1333 .setVisible(ri != null);
1334 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1335 break;
1336 }
1337 // otherwise fall through to handle image part
1338 case WebView.HitTestResult.IMAGE_TYPE:
1339 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1340 menu.setHeaderTitle(extra);
1341 }
1342 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1343 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1344 menu.findItem(R.id.download_context_menu_id).
Leon Scroggins63c02662010-11-18 15:16:27 -05001345 setOnMenuItemClickListener(new Download(mActivity, extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001346 menu.findItem(R.id.set_wallpaper_context_menu_id).
1347 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1348 extra));
1349 break;
1350
1351 default:
1352 Log.w(LOGTAG, "We should not get here.");
1353 break;
1354 }
1355 //update the ui
1356 mUi.onContextMenuCreated(menu);
1357 }
1358
1359 /**
1360 * As the menu can be open when loading state changes
1361 * we must manually update the state of the stop/reload menu
1362 * item
1363 */
1364 private void updateInLoadMenuItems(Menu menu) {
1365 if (menu == null) {
1366 return;
1367 }
1368 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1369 MenuItem src = mInLoad ?
1370 menu.findItem(R.id.stop_menu_id):
1371 menu.findItem(R.id.reload_menu_id);
1372 if (src != null) {
1373 dest.setIcon(src.getIcon());
1374 dest.setTitle(src.getTitle());
1375 }
1376 }
1377
1378 boolean prepareOptionsMenu(Menu menu) {
1379 // This happens when the user begins to hold down the menu key, so
1380 // allow them to chord to get a shortcut.
1381 mCanChord = true;
1382 // Note: setVisible will decide whether an item is visible; while
1383 // setEnabled() will decide whether an item is enabled, which also means
1384 // whether the matching shortcut key will function.
1385 switch (mMenuState) {
1386 case EMPTY_MENU:
1387 if (mCurrentMenuState != mMenuState) {
1388 menu.setGroupVisible(R.id.MAIN_MENU, false);
1389 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1390 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1391 }
1392 break;
1393 default:
1394 if (mCurrentMenuState != mMenuState) {
1395 menu.setGroupVisible(R.id.MAIN_MENU, true);
1396 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1397 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1398 }
1399 final WebView w = getCurrentTopWebView();
1400 boolean canGoBack = false;
1401 boolean canGoForward = false;
1402 boolean isHome = false;
1403 if (w != null) {
1404 canGoBack = w.canGoBack();
1405 canGoForward = w.canGoForward();
1406 isHome = mSettings.getHomePage().equals(w.getUrl());
1407 }
1408 final MenuItem back = menu.findItem(R.id.back_menu_id);
1409 back.setEnabled(canGoBack);
1410
1411 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1412 home.setEnabled(!isHome);
1413
1414 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1415 forward.setEnabled(canGoForward);
1416
1417 // decide whether to show the share link option
1418 PackageManager pm = mActivity.getPackageManager();
1419 Intent send = new Intent(Intent.ACTION_SEND);
1420 send.setType("text/plain");
1421 ResolveInfo ri = pm.resolveActivity(send,
1422 PackageManager.MATCH_DEFAULT_ONLY);
1423 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1424
1425 boolean isNavDump = mSettings.isNavDump();
1426 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1427 nav.setVisible(isNavDump);
1428 nav.setEnabled(isNavDump);
1429
1430 boolean showDebugSettings = mSettings.showDebugSettings();
1431 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1432 counter.setVisible(showDebugSettings);
1433 counter.setEnabled(showDebugSettings);
1434
1435 // allow the ui to adjust state based settings
1436 mUi.onPrepareOptionsMenu(menu);
1437
1438 break;
1439 }
1440 mCurrentMenuState = mMenuState;
1441 return true;
1442 }
1443
1444 public boolean onOptionsItemSelected(MenuItem item) {
1445 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1446 // menu remains active, so ensure comboview is dismissed
1447 // if main menu option is selected
1448 removeComboView();
1449 }
1450 // check the action bar button before mCanChord check, as the prepare call
1451 // doesn't come for action bar buttons
1452 if (item.getItemId() == R.id.newtab) {
1453 openTabToHomePage();
1454 return true;
1455 }
1456 if (!mCanChord) {
1457 // The user has already fired a shortcut with this hold down of the
1458 // menu key.
1459 return false;
1460 }
1461 if (null == getCurrentTopWebView()) {
1462 return false;
1463 }
1464 if (mMenuIsDown) {
1465 // The shortcut action consumes the MENU. Even if it is still down,
1466 // it won't trigger the next shortcut action. In the case of the
1467 // shortcut action triggering a new activity, like Bookmarks, we
1468 // won't get onKeyUp for MENU. So it is important to reset it here.
1469 mMenuIsDown = false;
1470 }
1471 switch (item.getItemId()) {
1472 // -- Main menu
1473 case R.id.new_tab_menu_id:
1474 openTabToHomePage();
1475 break;
1476
1477 case R.id.incognito_menu_id:
1478 openIncognitoTab();
1479 break;
1480
1481 case R.id.goto_menu_id:
1482 editUrl();
1483 break;
1484
1485 case R.id.bookmarks_menu_id:
1486 bookmarksOrHistoryPicker(false);
1487 break;
1488
1489 case R.id.active_tabs_menu_id:
1490 showActiveTabsPage();
1491 break;
1492
1493 case R.id.add_bookmark_menu_id:
1494 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
1495 break;
1496
1497 case R.id.stop_reload_menu_id:
1498 if (mInLoad) {
1499 stopLoading();
1500 } else {
1501 getCurrentTopWebView().reload();
1502 }
1503 break;
1504
1505 case R.id.back_menu_id:
1506 getCurrentTopWebView().goBack();
1507 break;
1508
1509 case R.id.forward_menu_id:
1510 getCurrentTopWebView().goForward();
1511 break;
1512
1513 case R.id.close_menu_id:
1514 // Close the subwindow if it exists.
1515 if (mTabControl.getCurrentSubWindow() != null) {
1516 dismissSubWindow(mTabControl.getCurrentTab());
1517 break;
1518 }
1519 closeCurrentTab();
1520 break;
1521
1522 case R.id.homepage_menu_id:
1523 Tab current = mTabControl.getCurrentTab();
1524 if (current != null) {
1525 dismissSubWindow(current);
1526 loadUrl(current.getWebView(), mSettings.getHomePage());
1527 }
1528 break;
1529
1530 case R.id.preferences_menu_id:
1531 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1532 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1533 getCurrentTopWebView().getUrl());
1534 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1535 break;
1536
1537 case R.id.find_menu_id:
1538 getCurrentTopWebView().showFindDialog(null);
1539 break;
1540
1541 case R.id.page_info_menu_id:
1542 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1543 false);
1544 break;
1545
1546 case R.id.classic_history_menu_id:
1547 bookmarksOrHistoryPicker(true);
1548 break;
1549
1550 case R.id.title_bar_share_page_url:
1551 case R.id.share_page_menu_id:
1552 Tab currentTab = mTabControl.getCurrentTab();
1553 if (null == currentTab) {
1554 mCanChord = false;
1555 return false;
1556 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001557 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001558 break;
1559
1560 case R.id.dump_nav_menu_id:
1561 getCurrentTopWebView().debugDump();
1562 break;
1563
1564 case R.id.dump_counters_menu_id:
1565 getCurrentTopWebView().dumpV8Counters();
1566 break;
1567
1568 case R.id.zoom_in_menu_id:
1569 getCurrentTopWebView().zoomIn();
1570 break;
1571
1572 case R.id.zoom_out_menu_id:
1573 getCurrentTopWebView().zoomOut();
1574 break;
1575
1576 case R.id.view_downloads_menu_id:
1577 viewDownloads();
1578 break;
1579
1580 case R.id.window_one_menu_id:
1581 case R.id.window_two_menu_id:
1582 case R.id.window_three_menu_id:
1583 case R.id.window_four_menu_id:
1584 case R.id.window_five_menu_id:
1585 case R.id.window_six_menu_id:
1586 case R.id.window_seven_menu_id:
1587 case R.id.window_eight_menu_id:
1588 {
1589 int menuid = item.getItemId();
1590 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1591 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1592 Tab desiredTab = mTabControl.getTab(id);
1593 if (desiredTab != null &&
1594 desiredTab != mTabControl.getCurrentTab()) {
1595 switchToTab(id);
1596 }
1597 break;
1598 }
1599 }
1600 }
1601 break;
1602
1603 default:
1604 return false;
1605 }
1606 mCanChord = false;
1607 return true;
1608 }
1609
1610 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001611 // Let the History and Bookmark fragments handle menus they created.
1612 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1613 return false;
1614 }
1615
Michael Kolb8233fac2010-10-26 16:08:53 -07001616 // chording is not an issue with context menus, but we use the same
1617 // options selector, so set mCanChord to true so we can access them.
1618 mCanChord = true;
1619 int id = item.getItemId();
1620 boolean result = true;
1621 switch (id) {
1622 // For the context menu from the title bar
1623 case R.id.title_bar_copy_page_url:
1624 Tab currentTab = mTabControl.getCurrentTab();
1625 if (null == currentTab) {
1626 result = false;
1627 break;
1628 }
1629 WebView mainView = currentTab.getWebView();
1630 if (null == mainView) {
1631 result = false;
1632 break;
1633 }
1634 copy(mainView.getUrl());
1635 break;
1636 // -- Browser context menu
1637 case R.id.open_context_menu_id:
1638 case R.id.bookmark_context_menu_id:
1639 case R.id.save_link_context_menu_id:
1640 case R.id.share_link_context_menu_id:
1641 case R.id.copy_link_context_menu_id:
1642 final WebView webView = getCurrentTopWebView();
1643 if (null == webView) {
1644 result = false;
1645 break;
1646 }
1647 final HashMap<String, WebView> hrefMap =
1648 new HashMap<String, WebView>();
1649 hrefMap.put("webview", webView);
1650 final Message msg = mHandler.obtainMessage(
1651 FOCUS_NODE_HREF, id, 0, hrefMap);
1652 webView.requestFocusNodeHref(msg);
1653 break;
1654
1655 default:
1656 // For other context menus
1657 result = onOptionsItemSelected(item);
1658 }
1659 mCanChord = false;
1660 return result;
1661 }
1662
1663 /**
1664 * support programmatically opening the context menu
1665 */
1666 public void openContextMenu(View view) {
1667 mActivity.openContextMenu(view);
1668 }
1669
1670 /**
1671 * programmatically open the options menu
1672 */
1673 public void openOptionsMenu() {
1674 mActivity.openOptionsMenu();
1675 }
1676
1677 public boolean onMenuOpened(int featureId, Menu menu) {
1678 if (mOptionsMenuOpen) {
1679 if (mConfigChanged) {
1680 // We do not need to make any changes to the state of the
1681 // title bar, since the only thing that happened was a
1682 // change in orientation
1683 mConfigChanged = false;
1684 } else {
1685 if (!mExtendedMenuOpen) {
1686 mExtendedMenuOpen = true;
1687 mUi.onExtendedMenuOpened();
1688 } else {
1689 // Switching the menu back to icon view, so show the
1690 // title bar once again.
1691 mExtendedMenuOpen = false;
1692 mUi.onExtendedMenuClosed(mInLoad);
1693 mUi.onOptionsMenuOpened();
1694 }
1695 }
1696 } else {
1697 // The options menu is closed, so open it, and show the title
1698 mOptionsMenuOpen = true;
1699 mConfigChanged = false;
1700 mExtendedMenuOpen = false;
1701 mUi.onOptionsMenuOpened();
1702 }
1703 return true;
1704 }
1705
1706 public void onOptionsMenuClosed(Menu menu) {
1707 mOptionsMenuOpen = false;
1708 mUi.onOptionsMenuClosed(mInLoad);
1709 }
1710
1711 public void onContextMenuClosed(Menu menu) {
1712 mUi.onContextMenuClosed(menu, mInLoad);
1713 }
1714
1715 // Helper method for getting the top window.
1716 @Override
1717 public WebView getCurrentTopWebView() {
1718 return mTabControl.getCurrentTopWebView();
1719 }
1720
1721 @Override
1722 public WebView getCurrentWebView() {
1723 return mTabControl.getCurrentWebView();
1724 }
1725
1726 /*
1727 * This method is called as a result of the user selecting the options
1728 * menu to see the download window. It shows the download window on top of
1729 * the current window.
1730 */
1731 void viewDownloads() {
1732 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1733 mActivity.startActivity(intent);
1734 }
1735
1736 // action mode
1737
1738 void onActionModeStarted(ActionMode mode) {
1739 mUi.onActionModeStarted(mode);
1740 mActionMode = mode;
1741 }
1742
1743 /*
1744 * True if a custom ActionMode (i.e. find or select) is in use.
1745 */
1746 @Override
1747 public boolean isInCustomActionMode() {
1748 return mActionMode != null;
1749 }
1750
1751 /*
1752 * End the current ActionMode.
1753 */
1754 @Override
1755 public void endActionMode() {
1756 if (mActionMode != null) {
1757 mActionMode.finish();
1758 }
1759 }
1760
1761 /*
1762 * Called by find and select when they are finished. Replace title bars
1763 * as necessary.
1764 */
1765 public void onActionModeFinished(ActionMode mode) {
1766 if (!isInCustomActionMode()) return;
1767 mUi.onActionModeFinished(mInLoad);
1768 mActionMode = null;
1769 }
1770
1771 boolean isInLoad() {
1772 return mInLoad;
1773 }
1774
1775 // bookmark handling
1776
1777 /**
1778 * add the current page as a bookmark to the given folder id
1779 * @param folderId use -1 for the default folder
1780 */
1781 @Override
1782 public void bookmarkCurrentPage(long folderId) {
1783 Intent i = new Intent(mActivity,
1784 AddBookmarkPage.class);
1785 WebView w = getCurrentTopWebView();
1786 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1787 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1788 String touchIconUrl = w.getTouchIconUrl();
1789 if (touchIconUrl != null) {
1790 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1791 WebSettings settings = w.getSettings();
1792 if (settings != null) {
1793 i.putExtra(AddBookmarkPage.USER_AGENT,
1794 settings.getUserAgentString());
1795 }
1796 }
1797 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1798 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1799 getDesiredThumbnailHeight(mActivity)));
1800 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1801 i.putExtra(BrowserContract.Bookmarks.PARENT,
1802 folderId);
1803 // Put the dialog at the upper right of the screen, covering the
1804 // star on the title bar.
1805 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1806 mActivity.startActivity(i);
1807 }
1808
1809 // file chooser
1810 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1811 mUploadHandler = new UploadHandler(this);
1812 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1813 }
1814
1815 // thumbnails
1816
1817 /**
1818 * Return the desired width for thumbnail screenshots, which are stored in
1819 * the database, and used on the bookmarks screen.
1820 * @param context Context for finding out the density of the screen.
1821 * @return desired width for thumbnail screenshot.
1822 */
1823 static int getDesiredThumbnailWidth(Context context) {
1824 return context.getResources().getDimensionPixelOffset(
1825 R.dimen.bookmarkThumbnailWidth);
1826 }
1827
1828 /**
1829 * Return the desired height for thumbnail screenshots, which are stored in
1830 * the database, and used on the bookmarks screen.
1831 * @param context Context for finding out the density of the screen.
1832 * @return desired height for thumbnail screenshot.
1833 */
1834 static int getDesiredThumbnailHeight(Context context) {
1835 return context.getResources().getDimensionPixelOffset(
1836 R.dimen.bookmarkThumbnailHeight);
1837 }
1838
1839 private static Bitmap createScreenshot(WebView view, int width, int height) {
1840 Picture thumbnail = view.capturePicture();
1841 if (thumbnail == null) {
1842 return null;
1843 }
1844 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1845 Canvas canvas = new Canvas(bm);
1846 // May need to tweak these values to determine what is the
1847 // best scale factor
1848 int thumbnailWidth = thumbnail.getWidth();
1849 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001850 float scaleFactor = 1.0f;
Michael Kolb8233fac2010-10-26 16:08:53 -07001851 if (thumbnailWidth > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001852 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001853 } else {
1854 return null;
1855 }
John Reckfe49ab42010-11-16 17:09:37 -08001856
Michael Kolb8233fac2010-10-26 16:08:53 -07001857 if (view.getWidth() > view.getHeight() &&
1858 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
1859 // If the device is in landscape and the page is shorter
John Reckfe49ab42010-11-16 17:09:37 -08001860 // than the height of the view, center the thumnail and crop the sides
1861 scaleFactor = (float) height / (float)thumbnailHeight;
1862 float wx = (thumbnailWidth * scaleFactor) - width;
1863 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001864 }
1865
John Reckfe49ab42010-11-16 17:09:37 -08001866 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001867
1868 thumbnail.draw(canvas);
1869 return bm;
1870 }
1871
1872 private void updateScreenshot(WebView view) {
1873 // If this is a bookmarked site, add a screenshot to the database.
1874 // FIXME: When should we update? Every time?
1875 // FIXME: Would like to make sure there is actually something to
1876 // draw, but the API for that (WebViewCore.pictureReady()) is not
1877 // currently accessible here.
1878
1879 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1880 getDesiredThumbnailHeight(mActivity));
1881 if (bm == null) {
1882 return;
1883 }
1884
1885 final ContentResolver cr = mActivity.getContentResolver();
1886 final String url = view.getUrl();
1887 final String originalUrl = view.getOriginalUrl();
1888
1889 new AsyncTask<Void, Void, Void>() {
1890 @Override
1891 protected Void doInBackground(Void... unused) {
1892 Cursor cursor = null;
1893 try {
1894 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
1895 if (cursor != null && cursor.moveToFirst()) {
1896 final ByteArrayOutputStream os =
1897 new ByteArrayOutputStream();
1898 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
1899
1900 ContentValues values = new ContentValues();
1901 values.put(Images.THUMBNAIL, os.toByteArray());
1902 values.put(Images.URL, cursor.getString(0));
1903
1904 do {
1905 cr.update(Images.CONTENT_URI, values, null, null);
1906 } while (cursor.moveToNext());
1907 }
1908 } catch (IllegalStateException e) {
1909 // Ignore
1910 } finally {
1911 if (cursor != null) cursor.close();
1912 }
1913 return null;
1914 }
1915 }.execute();
1916 }
1917
1918 private class Copy implements OnMenuItemClickListener {
1919 private CharSequence mText;
1920
1921 public boolean onMenuItemClick(MenuItem item) {
1922 copy(mText);
1923 return true;
1924 }
1925
1926 public Copy(CharSequence toCopy) {
1927 mText = toCopy;
1928 }
1929 }
1930
Leon Scroggins63c02662010-11-18 15:16:27 -05001931 private static class Download implements OnMenuItemClickListener {
1932 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001933 private String mText;
1934
1935 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05001936 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
1937 null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001938 return true;
1939 }
1940
Leon Scroggins63c02662010-11-18 15:16:27 -05001941 public Download(Activity activity, String toDownload) {
1942 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001943 mText = toDownload;
1944 }
1945 }
1946
Cary Clark8974d282010-11-22 10:46:05 -05001947 private static class SelectText implements OnMenuItemClickListener {
1948 private WebView mWebView;
1949
1950 public boolean onMenuItemClick(MenuItem item) {
1951 if (mWebView != null) {
1952 return mWebView.selectText();
1953 }
1954 return false;
1955 }
1956
1957 public SelectText(WebView webView) {
1958 mWebView = webView;
1959 }
1960
1961 }
1962
Michael Kolb8233fac2010-10-26 16:08:53 -07001963 /********************** TODO: UI stuff *****************************/
1964
1965 // these methods have been copied, they still need to be cleaned up
1966
1967 /****************** tabs ***************************************************/
1968
1969 // basic tab interactions:
1970
1971 // it is assumed that tabcontrol already knows about the tab
1972 protected void addTab(Tab tab) {
1973 mUi.addTab(tab);
1974 }
1975
1976 protected void removeTab(Tab tab) {
1977 mUi.removeTab(tab);
1978 mTabControl.removeTab(tab);
1979 }
1980
1981 protected void setActiveTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001982 mTabControl.setCurrentTab(tab);
Michael Kolb77df4562010-11-19 14:49:34 -08001983 // the tab is guaranteed to have a webview after setCurrentTab
1984 mUi.setActiveTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001985 }
1986
1987 protected void closeEmptyChildTab() {
1988 Tab current = mTabControl.getCurrentTab();
1989 if (current != null
1990 && current.getWebView().copyBackForwardList().getSize() == 0) {
1991 Tab parent = current.getParentTab();
1992 if (parent != null) {
1993 switchToTab(mTabControl.getTabIndex(parent));
1994 closeTab(current);
1995 }
1996 }
1997 }
1998
1999 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
2000 Log.i(LOGTAG, "Reusing tab for " + appId);
2001 // Dismiss the subwindow if applicable.
2002 dismissSubWindow(appTab);
2003 // Since we might kill the WebView, remove it from the
2004 // content view first.
2005 mUi.detachTab(appTab);
2006 // Recreate the main WebView after destroying the old one.
2007 // If the WebView has the same original url and is on that
2008 // page, it can be reused.
2009 boolean needsLoad =
2010 mTabControl.recreateWebView(appTab, urlData);
2011 // TODO: analyze why the remove and add are necessary
2012 mUi.attachTab(appTab);
2013 if (mTabControl.getCurrentTab() != appTab) {
2014 switchToTab(mTabControl.getTabIndex(appTab));
2015 if (needsLoad) {
2016 loadUrlDataIn(appTab, urlData);
2017 }
2018 } else {
2019 // If the tab was the current tab, we have to attach
2020 // it to the view system again.
2021 setActiveTab(appTab);
2022 if (needsLoad) {
2023 loadUrlDataIn(appTab, urlData);
2024 }
2025 }
2026 }
2027
2028 // Remove the sub window if it exists. Also called by TabControl when the
2029 // user clicks the 'X' to dismiss a sub window.
2030 public void dismissSubWindow(Tab tab) {
2031 removeSubWindow(tab);
2032 // dismiss the subwindow. This will destroy the WebView.
2033 tab.dismissSubWindow();
2034 getCurrentTopWebView().requestFocus();
2035 }
2036
2037 @Override
2038 public void removeSubWindow(Tab t) {
2039 if (t.getSubWebView() != null) {
2040 mUi.removeSubWindow(t.getSubViewContainer());
2041 }
2042 }
2043
2044 @Override
2045 public void attachSubWindow(Tab tab) {
2046 if (tab.getSubWebView() != null) {
2047 mUi.attachSubWindow(tab.getSubViewContainer());
2048 getCurrentTopWebView().requestFocus();
2049 }
2050 }
2051
Michael Kolb843510f2010-12-09 10:51:49 -08002052 @Override
2053 public Tab openTabToHomePage() {
2054 // check for max tabs
2055 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002056 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2057 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002058 } else {
2059 mUi.showMaxTabsWarning();
2060 return null;
2061 }
2062 }
2063
Michael Kolb18eb3772010-12-10 14:29:51 -08002064 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2065 if (mSettings.openInBackground() && !forceForeground) {
2066 Tab tab = mTabControl.createNewTab(false, null, null,
2067 (parent != null) && parent.isPrivateBrowsingEnabled());
2068 if (tab != null) {
2069 addTab(tab);
2070 WebView view = tab.getWebView();
2071 loadUrl(view, url);
2072 }
2073 return tab;
2074 } else {
2075 return openTabAndShow(parent, new UrlData(url), false, null);
2076 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002077 }
2078
Michael Kolb18eb3772010-12-10 14:29:51 -08002079
Michael Kolb8233fac2010-10-26 16:08:53 -07002080 // This method does a ton of stuff. It will attempt to create a new tab
2081 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2082 // url isn't null, it will load the given url.
Michael Kolb18eb3772010-12-10 14:29:51 -08002083 public Tab openTabAndShow(Tab parent, UrlData urlData, boolean closeOnExit,
Michael Kolb8233fac2010-10-26 16:08:53 -07002084 String appId) {
2085 final Tab currentTab = mTabControl.getCurrentTab();
2086 if (mTabControl.canCreateNewTab()) {
2087 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Michael Kolb18eb3772010-12-10 14:29:51 -08002088 urlData.mUrl,
2089 (parent != null) && parent.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -07002090 WebView webview = tab.getWebView();
2091 // We must set the new tab as the current tab to reflect the old
2092 // animation behavior.
2093 addTab(tab);
2094 setActiveTab(tab);
2095 if (!urlData.isEmpty()) {
2096 loadUrlDataIn(tab, urlData);
2097 }
2098 return tab;
2099 } else {
2100 // Get rid of the subwindow if it exists
2101 dismissSubWindow(currentTab);
2102 if (!urlData.isEmpty()) {
2103 // Load the given url.
2104 loadUrlDataIn(currentTab, urlData);
2105 }
2106 return currentTab;
2107 }
2108 }
2109
Michael Kolb8233fac2010-10-26 16:08:53 -07002110 @Override
2111 public Tab openIncognitoTab() {
2112 if (mTabControl.canCreateNewTab()) {
2113 Tab currentTab = mTabControl.getCurrentTab();
2114 Tab tab = mTabControl.createNewTab(false, null, null, true);
2115 addTab(tab);
2116 setActiveTab(tab);
2117 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002118 } else {
2119 mUi.showMaxTabsWarning();
2120 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002121 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002122 }
2123
2124 /**
2125 * @param index Index of the tab to change to, as defined by
2126 * mTabControl.getTabIndex(Tab t).
2127 * @return boolean True if we successfully switched to a different tab. If
2128 * the indexth tab is null, or if that tab is the same as
2129 * the current one, return false.
2130 */
2131 @Override
2132 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002133 // hide combo view if open
2134 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002135 Tab tab = mTabControl.getTab(index);
2136 Tab currentTab = mTabControl.getCurrentTab();
2137 if (tab == null || tab == currentTab) {
2138 return false;
2139 }
2140 setActiveTab(tab);
2141 return true;
2142 }
2143
2144 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002145 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002146 // hide combo view if open
2147 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002148 final Tab current = mTabControl.getCurrentTab();
2149 if (mTabControl.getTabCount() == 1) {
2150 // This is the last tab. Open a new one, with the home
2151 // page and close the current one.
2152 openTabToHomePage();
2153 closeTab(current);
2154 return;
2155 }
2156 final Tab parent = current.getParentTab();
2157 int indexToShow = -1;
2158 if (parent != null) {
2159 indexToShow = mTabControl.getTabIndex(parent);
2160 } else {
2161 final int currentIndex = mTabControl.getCurrentIndex();
2162 // Try to move to the tab to the right
2163 indexToShow = currentIndex + 1;
2164 if (indexToShow > mTabControl.getTabCount() - 1) {
2165 // Try to move to the tab to the left
2166 indexToShow = currentIndex - 1;
2167 }
2168 }
2169 if (switchToTab(indexToShow)) {
2170 // Close window
2171 closeTab(current);
2172 }
2173 }
2174
2175 /**
2176 * Close the tab, remove its associated title bar, and adjust mTabControl's
2177 * current tab to a valid value.
2178 */
2179 @Override
2180 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002181 // hide combo view if open
2182 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002183 int currentIndex = mTabControl.getCurrentIndex();
2184 int removeIndex = mTabControl.getTabIndex(tab);
2185 removeTab(tab);
2186 if (currentIndex >= removeIndex && currentIndex != 0) {
2187 currentIndex--;
2188 }
2189 Tab newtab = mTabControl.getTab(currentIndex);
2190 setActiveTab(newtab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002191 }
2192
2193 /**************** TODO: Url loading clean up *******************************/
2194
2195 // Called when loading from context menu or LOAD_URL message
2196 protected void loadUrlFromContext(WebView view, String url) {
2197 // In case the user enters nothing.
2198 if (url != null && url.length() != 0 && view != null) {
2199 url = UrlUtils.smartUrlFilter(url);
2200 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2201 loadUrl(view, url);
2202 }
2203 }
2204 }
2205
2206 /**
2207 * Load the URL into the given WebView and update the title bar
2208 * to reflect the new load. Call this instead of WebView.loadUrl
2209 * directly.
2210 * @param view The WebView used to load url.
2211 * @param url The URL to load.
2212 */
2213 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002214 view.loadUrl(url);
2215 }
2216
2217 /**
2218 * Load UrlData into a Tab and update the title bar to reflect the new
2219 * load. Call this instead of UrlData.loadIn directly.
2220 * @param t The Tab used to load.
2221 * @param data The UrlData being loaded.
2222 */
2223 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002224 data.loadIn(t);
2225 }
2226
2227 /**
2228 * Resets the browser title-view to whatever it must be
2229 * (for example, if we had a loading error)
2230 * When we have a new page, we call resetTitle, when we
2231 * have to reset the titlebar to whatever it used to be
2232 * (for example, if the user chose to stop loading), we
2233 * call resetTitleAndRevertLockIcon.
2234 */
2235 public void resetTitleAndRevertLockIcon(Tab tab) {
2236 mUi.resetTitleAndRevertLockIcon(tab);
2237 }
2238
2239 void resetTitleAndIcon(Tab tab) {
2240 mUi.resetTitleAndIcon(tab);
2241 }
2242
2243 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002244 * Sets a title composed of the URL and the title string.
2245 * @param url The URL of the site being loaded.
2246 * @param title The title of the site being loaded.
2247 */
2248 void setUrlTitle(Tab tab, String url, String title) {
2249 tab.setCurrentUrl(url);
2250 tab.setCurrentTitle(title);
2251 // If we are in voice search mode, the title has already been set.
2252 if (tab.isInVoiceSearchMode()) return;
2253 mUi.setUrlTitle(tab, url, title);
2254 }
2255
2256 void goBackOnePageOrQuit() {
2257 Tab current = mTabControl.getCurrentTab();
2258 if (current == null) {
2259 /*
2260 * Instead of finishing the activity, simply push this to the back
2261 * of the stack and let ActivityManager to choose the foreground
2262 * activity. As BrowserActivity is singleTask, it will be always the
2263 * root of the task. So we can use either true or false for
2264 * moveTaskToBack().
2265 */
2266 mActivity.moveTaskToBack(true);
2267 return;
2268 }
2269 WebView w = current.getWebView();
2270 if (w.canGoBack()) {
2271 w.goBack();
2272 } else {
2273 // Check to see if we are closing a window that was created by
2274 // another window. If so, we switch back to that window.
2275 Tab parent = current.getParentTab();
2276 if (parent != null) {
2277 switchToTab(mTabControl.getTabIndex(parent));
2278 // Now we close the other tab
2279 closeTab(current);
2280 } else {
2281 if (current.closeOnExit()) {
2282 // force the tab's inLoad() to be false as we are going to
2283 // either finish the activity or remove the tab. This will
2284 // ensure pauseWebViewTimers() taking action.
Michael Kolb70976932010-11-30 11:34:01 -08002285 current.clearInPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07002286 if (mTabControl.getTabCount() == 1) {
2287 mActivity.finish();
2288 return;
2289 }
2290 if (mActivityPaused) {
2291 Log.e(LOGTAG, "BrowserActivity is already paused "
2292 + "while handing goBackOnePageOrQuit.");
2293 }
Michael Kolb70976932010-11-30 11:34:01 -08002294 pauseWebViewTimers(current);
Michael Kolb8233fac2010-10-26 16:08:53 -07002295 removeTab(current);
2296 }
2297 /*
2298 * Instead of finishing the activity, simply push this to the back
2299 * of the stack and let ActivityManager to choose the foreground
2300 * activity. As BrowserActivity is singleTask, it will be always the
2301 * root of the task. So we can use either true or false for
2302 * moveTaskToBack().
2303 */
2304 mActivity.moveTaskToBack(true);
2305 }
2306 }
2307 }
2308
2309 /**
2310 * Feed the previously stored results strings to the BrowserProvider so that
2311 * the SearchDialog will show them instead of the standard searches.
2312 * @param result String to show on the editable line of the SearchDialog.
2313 */
2314 @Override
2315 public void showVoiceSearchResults(String result) {
2316 ContentProviderClient client = mActivity.getContentResolver()
2317 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2318 ContentProvider prov = client.getLocalContentProvider();
2319 BrowserProvider bp = (BrowserProvider) prov;
2320 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2321 client.release();
2322
2323 Bundle bundle = createGoogleSearchSourceBundle(
2324 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2325 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2326 startSearch(result, false, bundle, false);
2327 }
2328
2329 private void startSearch(String initialQuery, boolean selectInitialQuery,
2330 Bundle appSearchData, boolean globalSearch) {
2331 if (appSearchData == null) {
2332 appSearchData = createGoogleSearchSourceBundle(
2333 GOOGLE_SEARCH_SOURCE_TYPE);
2334 }
2335
2336 SearchEngine searchEngine = mSettings.getSearchEngine();
2337 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2338 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2339 }
2340 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2341 globalSearch);
2342 }
2343
2344 private Bundle createGoogleSearchSourceBundle(String source) {
2345 Bundle bundle = new Bundle();
2346 bundle.putString(Search.SOURCE, source);
2347 return bundle;
2348 }
2349
2350 /**
2351 * handle key events in browser
2352 *
2353 * @param keyCode
2354 * @param event
2355 * @return true if handled, false to pass to super
2356 */
2357 boolean onKeyDown(int keyCode, KeyEvent event) {
2358 // Even if MENU is already held down, we need to call to super to open
2359 // the IME on long press.
2360 if (KeyEvent.KEYCODE_MENU == keyCode) {
2361 mMenuIsDown = true;
2362 return false;
2363 }
2364 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2365 // still down, we don't want to trigger the search. Pretend to consume
2366 // the key and do nothing.
2367 if (mMenuIsDown) return true;
2368
2369 switch(keyCode) {
2370 case KeyEvent.KEYCODE_SPACE:
2371 // WebView/WebTextView handle the keys in the KeyDown. As
2372 // the Activity's shortcut keys are only handled when WebView
2373 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2374 if (event.isShiftPressed()) {
2375 pageUp();
2376 } else {
2377 pageDown();
2378 }
2379 return true;
2380 case KeyEvent.KEYCODE_BACK:
2381 if (event.getRepeatCount() == 0) {
2382 event.startTracking();
2383 return true;
2384 } else if (mUi.showsWeb()
2385 && event.isLongPress()) {
2386 bookmarksOrHistoryPicker(true);
2387 return true;
2388 }
2389 break;
2390 }
2391 return false;
2392 }
2393
2394 boolean onKeyUp(int keyCode, KeyEvent event) {
2395 switch(keyCode) {
2396 case KeyEvent.KEYCODE_MENU:
2397 mMenuIsDown = false;
2398 break;
2399 case KeyEvent.KEYCODE_BACK:
2400 if (event.isTracking() && !event.isCanceled()) {
2401 onBackKey();
2402 return true;
2403 }
2404 break;
2405 }
2406 return false;
2407 }
2408
2409 public boolean isMenuDown() {
2410 return mMenuIsDown;
2411 }
2412
Ben Murdoch8029a772010-11-16 11:58:21 +00002413 public void setupAutoFill(Message message) {
2414 // Open the settings activity at the AutoFill profile fragment so that
2415 // the user can create a new profile. When they return, we will dispatch
2416 // the message so that we can autofill the form using their new profile.
2417 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2418 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2419 AutoFillSettingsFragment.class.getName());
2420 mAutoFillSetupMessage = message;
2421 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2422 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002423}