blob: e88a676921acb63a2c5dea27f5d6affd829a0025 [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 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001450 if (!mCanChord) {
1451 // The user has already fired a shortcut with this hold down of the
1452 // menu key.
1453 return false;
1454 }
1455 if (null == getCurrentTopWebView()) {
1456 return false;
1457 }
1458 if (mMenuIsDown) {
1459 // The shortcut action consumes the MENU. Even if it is still down,
1460 // it won't trigger the next shortcut action. In the case of the
1461 // shortcut action triggering a new activity, like Bookmarks, we
1462 // won't get onKeyUp for MENU. So it is important to reset it here.
1463 mMenuIsDown = false;
1464 }
1465 switch (item.getItemId()) {
1466 // -- Main menu
1467 case R.id.new_tab_menu_id:
1468 openTabToHomePage();
1469 break;
1470
1471 case R.id.incognito_menu_id:
1472 openIncognitoTab();
1473 break;
1474
1475 case R.id.goto_menu_id:
1476 editUrl();
1477 break;
1478
1479 case R.id.bookmarks_menu_id:
1480 bookmarksOrHistoryPicker(false);
1481 break;
1482
1483 case R.id.active_tabs_menu_id:
1484 showActiveTabsPage();
1485 break;
1486
1487 case R.id.add_bookmark_menu_id:
1488 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
1489 break;
1490
1491 case R.id.stop_reload_menu_id:
1492 if (mInLoad) {
1493 stopLoading();
1494 } else {
1495 getCurrentTopWebView().reload();
1496 }
1497 break;
1498
1499 case R.id.back_menu_id:
1500 getCurrentTopWebView().goBack();
1501 break;
1502
1503 case R.id.forward_menu_id:
1504 getCurrentTopWebView().goForward();
1505 break;
1506
1507 case R.id.close_menu_id:
1508 // Close the subwindow if it exists.
1509 if (mTabControl.getCurrentSubWindow() != null) {
1510 dismissSubWindow(mTabControl.getCurrentTab());
1511 break;
1512 }
1513 closeCurrentTab();
1514 break;
1515
1516 case R.id.homepage_menu_id:
1517 Tab current = mTabControl.getCurrentTab();
1518 if (current != null) {
1519 dismissSubWindow(current);
1520 loadUrl(current.getWebView(), mSettings.getHomePage());
1521 }
1522 break;
1523
1524 case R.id.preferences_menu_id:
1525 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1526 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1527 getCurrentTopWebView().getUrl());
1528 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1529 break;
1530
1531 case R.id.find_menu_id:
1532 getCurrentTopWebView().showFindDialog(null);
1533 break;
1534
1535 case R.id.page_info_menu_id:
1536 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1537 false);
1538 break;
1539
1540 case R.id.classic_history_menu_id:
1541 bookmarksOrHistoryPicker(true);
1542 break;
1543
1544 case R.id.title_bar_share_page_url:
1545 case R.id.share_page_menu_id:
1546 Tab currentTab = mTabControl.getCurrentTab();
1547 if (null == currentTab) {
1548 mCanChord = false;
1549 return false;
1550 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001551 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001552 break;
1553
1554 case R.id.dump_nav_menu_id:
1555 getCurrentTopWebView().debugDump();
1556 break;
1557
1558 case R.id.dump_counters_menu_id:
1559 getCurrentTopWebView().dumpV8Counters();
1560 break;
1561
1562 case R.id.zoom_in_menu_id:
1563 getCurrentTopWebView().zoomIn();
1564 break;
1565
1566 case R.id.zoom_out_menu_id:
1567 getCurrentTopWebView().zoomOut();
1568 break;
1569
1570 case R.id.view_downloads_menu_id:
1571 viewDownloads();
1572 break;
1573
1574 case R.id.window_one_menu_id:
1575 case R.id.window_two_menu_id:
1576 case R.id.window_three_menu_id:
1577 case R.id.window_four_menu_id:
1578 case R.id.window_five_menu_id:
1579 case R.id.window_six_menu_id:
1580 case R.id.window_seven_menu_id:
1581 case R.id.window_eight_menu_id:
1582 {
1583 int menuid = item.getItemId();
1584 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1585 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1586 Tab desiredTab = mTabControl.getTab(id);
1587 if (desiredTab != null &&
1588 desiredTab != mTabControl.getCurrentTab()) {
1589 switchToTab(id);
1590 }
1591 break;
1592 }
1593 }
1594 }
1595 break;
1596
1597 default:
1598 return false;
1599 }
1600 mCanChord = false;
1601 return true;
1602 }
1603
1604 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001605 // Let the History and Bookmark fragments handle menus they created.
1606 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1607 return false;
1608 }
1609
Michael Kolb8233fac2010-10-26 16:08:53 -07001610 // chording is not an issue with context menus, but we use the same
1611 // options selector, so set mCanChord to true so we can access them.
1612 mCanChord = true;
1613 int id = item.getItemId();
1614 boolean result = true;
1615 switch (id) {
1616 // For the context menu from the title bar
1617 case R.id.title_bar_copy_page_url:
1618 Tab currentTab = mTabControl.getCurrentTab();
1619 if (null == currentTab) {
1620 result = false;
1621 break;
1622 }
1623 WebView mainView = currentTab.getWebView();
1624 if (null == mainView) {
1625 result = false;
1626 break;
1627 }
1628 copy(mainView.getUrl());
1629 break;
1630 // -- Browser context menu
1631 case R.id.open_context_menu_id:
1632 case R.id.bookmark_context_menu_id:
1633 case R.id.save_link_context_menu_id:
1634 case R.id.share_link_context_menu_id:
1635 case R.id.copy_link_context_menu_id:
1636 final WebView webView = getCurrentTopWebView();
1637 if (null == webView) {
1638 result = false;
1639 break;
1640 }
1641 final HashMap<String, WebView> hrefMap =
1642 new HashMap<String, WebView>();
1643 hrefMap.put("webview", webView);
1644 final Message msg = mHandler.obtainMessage(
1645 FOCUS_NODE_HREF, id, 0, hrefMap);
1646 webView.requestFocusNodeHref(msg);
1647 break;
1648
1649 default:
1650 // For other context menus
1651 result = onOptionsItemSelected(item);
1652 }
1653 mCanChord = false;
1654 return result;
1655 }
1656
1657 /**
1658 * support programmatically opening the context menu
1659 */
1660 public void openContextMenu(View view) {
1661 mActivity.openContextMenu(view);
1662 }
1663
1664 /**
1665 * programmatically open the options menu
1666 */
1667 public void openOptionsMenu() {
1668 mActivity.openOptionsMenu();
1669 }
1670
1671 public boolean onMenuOpened(int featureId, Menu menu) {
1672 if (mOptionsMenuOpen) {
1673 if (mConfigChanged) {
1674 // We do not need to make any changes to the state of the
1675 // title bar, since the only thing that happened was a
1676 // change in orientation
1677 mConfigChanged = false;
1678 } else {
1679 if (!mExtendedMenuOpen) {
1680 mExtendedMenuOpen = true;
1681 mUi.onExtendedMenuOpened();
1682 } else {
1683 // Switching the menu back to icon view, so show the
1684 // title bar once again.
1685 mExtendedMenuOpen = false;
1686 mUi.onExtendedMenuClosed(mInLoad);
1687 mUi.onOptionsMenuOpened();
1688 }
1689 }
1690 } else {
1691 // The options menu is closed, so open it, and show the title
1692 mOptionsMenuOpen = true;
1693 mConfigChanged = false;
1694 mExtendedMenuOpen = false;
1695 mUi.onOptionsMenuOpened();
1696 }
1697 return true;
1698 }
1699
1700 public void onOptionsMenuClosed(Menu menu) {
1701 mOptionsMenuOpen = false;
1702 mUi.onOptionsMenuClosed(mInLoad);
1703 }
1704
1705 public void onContextMenuClosed(Menu menu) {
1706 mUi.onContextMenuClosed(menu, mInLoad);
1707 }
1708
1709 // Helper method for getting the top window.
1710 @Override
1711 public WebView getCurrentTopWebView() {
1712 return mTabControl.getCurrentTopWebView();
1713 }
1714
1715 @Override
1716 public WebView getCurrentWebView() {
1717 return mTabControl.getCurrentWebView();
1718 }
1719
1720 /*
1721 * This method is called as a result of the user selecting the options
1722 * menu to see the download window. It shows the download window on top of
1723 * the current window.
1724 */
1725 void viewDownloads() {
1726 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1727 mActivity.startActivity(intent);
1728 }
1729
1730 // action mode
1731
1732 void onActionModeStarted(ActionMode mode) {
1733 mUi.onActionModeStarted(mode);
1734 mActionMode = mode;
1735 }
1736
1737 /*
1738 * True if a custom ActionMode (i.e. find or select) is in use.
1739 */
1740 @Override
1741 public boolean isInCustomActionMode() {
1742 return mActionMode != null;
1743 }
1744
1745 /*
1746 * End the current ActionMode.
1747 */
1748 @Override
1749 public void endActionMode() {
1750 if (mActionMode != null) {
1751 mActionMode.finish();
1752 }
1753 }
1754
1755 /*
1756 * Called by find and select when they are finished. Replace title bars
1757 * as necessary.
1758 */
1759 public void onActionModeFinished(ActionMode mode) {
1760 if (!isInCustomActionMode()) return;
1761 mUi.onActionModeFinished(mInLoad);
1762 mActionMode = null;
1763 }
1764
1765 boolean isInLoad() {
1766 return mInLoad;
1767 }
1768
1769 // bookmark handling
1770
1771 /**
1772 * add the current page as a bookmark to the given folder id
1773 * @param folderId use -1 for the default folder
1774 */
1775 @Override
1776 public void bookmarkCurrentPage(long folderId) {
1777 Intent i = new Intent(mActivity,
1778 AddBookmarkPage.class);
1779 WebView w = getCurrentTopWebView();
1780 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1781 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1782 String touchIconUrl = w.getTouchIconUrl();
1783 if (touchIconUrl != null) {
1784 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1785 WebSettings settings = w.getSettings();
1786 if (settings != null) {
1787 i.putExtra(AddBookmarkPage.USER_AGENT,
1788 settings.getUserAgentString());
1789 }
1790 }
1791 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1792 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1793 getDesiredThumbnailHeight(mActivity)));
1794 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1795 i.putExtra(BrowserContract.Bookmarks.PARENT,
1796 folderId);
1797 // Put the dialog at the upper right of the screen, covering the
1798 // star on the title bar.
1799 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1800 mActivity.startActivity(i);
1801 }
1802
1803 // file chooser
1804 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1805 mUploadHandler = new UploadHandler(this);
1806 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1807 }
1808
1809 // thumbnails
1810
1811 /**
1812 * Return the desired width for thumbnail screenshots, which are stored in
1813 * the database, and used on the bookmarks screen.
1814 * @param context Context for finding out the density of the screen.
1815 * @return desired width for thumbnail screenshot.
1816 */
1817 static int getDesiredThumbnailWidth(Context context) {
1818 return context.getResources().getDimensionPixelOffset(
1819 R.dimen.bookmarkThumbnailWidth);
1820 }
1821
1822 /**
1823 * Return the desired height for thumbnail screenshots, which are stored in
1824 * the database, and used on the bookmarks screen.
1825 * @param context Context for finding out the density of the screen.
1826 * @return desired height for thumbnail screenshot.
1827 */
1828 static int getDesiredThumbnailHeight(Context context) {
1829 return context.getResources().getDimensionPixelOffset(
1830 R.dimen.bookmarkThumbnailHeight);
1831 }
1832
1833 private static Bitmap createScreenshot(WebView view, int width, int height) {
1834 Picture thumbnail = view.capturePicture();
1835 if (thumbnail == null) {
1836 return null;
1837 }
1838 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1839 Canvas canvas = new Canvas(bm);
1840 // May need to tweak these values to determine what is the
1841 // best scale factor
1842 int thumbnailWidth = thumbnail.getWidth();
1843 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001844 float scaleFactor = 1.0f;
Michael Kolb8233fac2010-10-26 16:08:53 -07001845 if (thumbnailWidth > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001846 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001847 } else {
1848 return null;
1849 }
John Reckfe49ab42010-11-16 17:09:37 -08001850
Michael Kolb8233fac2010-10-26 16:08:53 -07001851 if (view.getWidth() > view.getHeight() &&
1852 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
1853 // If the device is in landscape and the page is shorter
John Reckfe49ab42010-11-16 17:09:37 -08001854 // than the height of the view, center the thumnail and crop the sides
1855 scaleFactor = (float) height / (float)thumbnailHeight;
1856 float wx = (thumbnailWidth * scaleFactor) - width;
1857 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001858 }
1859
John Reckfe49ab42010-11-16 17:09:37 -08001860 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001861
1862 thumbnail.draw(canvas);
1863 return bm;
1864 }
1865
1866 private void updateScreenshot(WebView view) {
1867 // If this is a bookmarked site, add a screenshot to the database.
1868 // FIXME: When should we update? Every time?
1869 // FIXME: Would like to make sure there is actually something to
1870 // draw, but the API for that (WebViewCore.pictureReady()) is not
1871 // currently accessible here.
1872
1873 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1874 getDesiredThumbnailHeight(mActivity));
1875 if (bm == null) {
1876 return;
1877 }
1878
1879 final ContentResolver cr = mActivity.getContentResolver();
1880 final String url = view.getUrl();
1881 final String originalUrl = view.getOriginalUrl();
1882
1883 new AsyncTask<Void, Void, Void>() {
1884 @Override
1885 protected Void doInBackground(Void... unused) {
1886 Cursor cursor = null;
1887 try {
1888 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
1889 if (cursor != null && cursor.moveToFirst()) {
1890 final ByteArrayOutputStream os =
1891 new ByteArrayOutputStream();
1892 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
1893
1894 ContentValues values = new ContentValues();
1895 values.put(Images.THUMBNAIL, os.toByteArray());
1896 values.put(Images.URL, cursor.getString(0));
1897
1898 do {
1899 cr.update(Images.CONTENT_URI, values, null, null);
1900 } while (cursor.moveToNext());
1901 }
1902 } catch (IllegalStateException e) {
1903 // Ignore
1904 } finally {
1905 if (cursor != null) cursor.close();
1906 }
1907 return null;
1908 }
1909 }.execute();
1910 }
1911
1912 private class Copy implements OnMenuItemClickListener {
1913 private CharSequence mText;
1914
1915 public boolean onMenuItemClick(MenuItem item) {
1916 copy(mText);
1917 return true;
1918 }
1919
1920 public Copy(CharSequence toCopy) {
1921 mText = toCopy;
1922 }
1923 }
1924
Leon Scroggins63c02662010-11-18 15:16:27 -05001925 private static class Download implements OnMenuItemClickListener {
1926 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001927 private String mText;
1928
1929 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05001930 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
1931 null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001932 return true;
1933 }
1934
Leon Scroggins63c02662010-11-18 15:16:27 -05001935 public Download(Activity activity, String toDownload) {
1936 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001937 mText = toDownload;
1938 }
1939 }
1940
Cary Clark8974d282010-11-22 10:46:05 -05001941 private static class SelectText implements OnMenuItemClickListener {
1942 private WebView mWebView;
1943
1944 public boolean onMenuItemClick(MenuItem item) {
1945 if (mWebView != null) {
1946 return mWebView.selectText();
1947 }
1948 return false;
1949 }
1950
1951 public SelectText(WebView webView) {
1952 mWebView = webView;
1953 }
1954
1955 }
1956
Michael Kolb8233fac2010-10-26 16:08:53 -07001957 /********************** TODO: UI stuff *****************************/
1958
1959 // these methods have been copied, they still need to be cleaned up
1960
1961 /****************** tabs ***************************************************/
1962
1963 // basic tab interactions:
1964
1965 // it is assumed that tabcontrol already knows about the tab
1966 protected void addTab(Tab tab) {
1967 mUi.addTab(tab);
1968 }
1969
1970 protected void removeTab(Tab tab) {
1971 mUi.removeTab(tab);
1972 mTabControl.removeTab(tab);
1973 }
1974
1975 protected void setActiveTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001976 mTabControl.setCurrentTab(tab);
Michael Kolb77df4562010-11-19 14:49:34 -08001977 // the tab is guaranteed to have a webview after setCurrentTab
1978 mUi.setActiveTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001979 }
1980
1981 protected void closeEmptyChildTab() {
1982 Tab current = mTabControl.getCurrentTab();
1983 if (current != null
1984 && current.getWebView().copyBackForwardList().getSize() == 0) {
1985 Tab parent = current.getParentTab();
1986 if (parent != null) {
1987 switchToTab(mTabControl.getTabIndex(parent));
1988 closeTab(current);
1989 }
1990 }
1991 }
1992
1993 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
1994 Log.i(LOGTAG, "Reusing tab for " + appId);
1995 // Dismiss the subwindow if applicable.
1996 dismissSubWindow(appTab);
1997 // Since we might kill the WebView, remove it from the
1998 // content view first.
1999 mUi.detachTab(appTab);
2000 // Recreate the main WebView after destroying the old one.
2001 // If the WebView has the same original url and is on that
2002 // page, it can be reused.
2003 boolean needsLoad =
2004 mTabControl.recreateWebView(appTab, urlData);
2005 // TODO: analyze why the remove and add are necessary
2006 mUi.attachTab(appTab);
2007 if (mTabControl.getCurrentTab() != appTab) {
2008 switchToTab(mTabControl.getTabIndex(appTab));
2009 if (needsLoad) {
2010 loadUrlDataIn(appTab, urlData);
2011 }
2012 } else {
2013 // If the tab was the current tab, we have to attach
2014 // it to the view system again.
2015 setActiveTab(appTab);
2016 if (needsLoad) {
2017 loadUrlDataIn(appTab, urlData);
2018 }
2019 }
2020 }
2021
2022 // Remove the sub window if it exists. Also called by TabControl when the
2023 // user clicks the 'X' to dismiss a sub window.
2024 public void dismissSubWindow(Tab tab) {
2025 removeSubWindow(tab);
2026 // dismiss the subwindow. This will destroy the WebView.
2027 tab.dismissSubWindow();
2028 getCurrentTopWebView().requestFocus();
2029 }
2030
2031 @Override
2032 public void removeSubWindow(Tab t) {
2033 if (t.getSubWebView() != null) {
2034 mUi.removeSubWindow(t.getSubViewContainer());
2035 }
2036 }
2037
2038 @Override
2039 public void attachSubWindow(Tab tab) {
2040 if (tab.getSubWebView() != null) {
2041 mUi.attachSubWindow(tab.getSubViewContainer());
2042 getCurrentTopWebView().requestFocus();
2043 }
2044 }
2045
Michael Kolb843510f2010-12-09 10:51:49 -08002046 @Override
2047 public Tab openTabToHomePage() {
2048 // check for max tabs
2049 if (mTabControl.canCreateNewTab()) {
Michael Kolb18eb3772010-12-10 14:29:51 -08002050 return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
2051 false, null);
Michael Kolb843510f2010-12-09 10:51:49 -08002052 } else {
2053 mUi.showMaxTabsWarning();
2054 return null;
2055 }
2056 }
2057
Michael Kolb18eb3772010-12-10 14:29:51 -08002058 protected Tab openTab(Tab parent, String url, boolean forceForeground) {
2059 if (mSettings.openInBackground() && !forceForeground) {
2060 Tab tab = mTabControl.createNewTab(false, null, null,
2061 (parent != null) && parent.isPrivateBrowsingEnabled());
2062 if (tab != null) {
2063 addTab(tab);
2064 WebView view = tab.getWebView();
2065 loadUrl(view, url);
2066 }
2067 return tab;
2068 } else {
2069 return openTabAndShow(parent, new UrlData(url), false, null);
2070 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002071 }
2072
Michael Kolb18eb3772010-12-10 14:29:51 -08002073
Michael Kolb8233fac2010-10-26 16:08:53 -07002074 // This method does a ton of stuff. It will attempt to create a new tab
2075 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2076 // url isn't null, it will load the given url.
Michael Kolb18eb3772010-12-10 14:29:51 -08002077 public Tab openTabAndShow(Tab parent, UrlData urlData, boolean closeOnExit,
Michael Kolb8233fac2010-10-26 16:08:53 -07002078 String appId) {
2079 final Tab currentTab = mTabControl.getCurrentTab();
2080 if (mTabControl.canCreateNewTab()) {
2081 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Michael Kolb18eb3772010-12-10 14:29:51 -08002082 urlData.mUrl,
2083 (parent != null) && parent.isPrivateBrowsingEnabled());
Michael Kolb8233fac2010-10-26 16:08:53 -07002084 WebView webview = tab.getWebView();
2085 // We must set the new tab as the current tab to reflect the old
2086 // animation behavior.
2087 addTab(tab);
2088 setActiveTab(tab);
2089 if (!urlData.isEmpty()) {
2090 loadUrlDataIn(tab, urlData);
2091 }
2092 return tab;
2093 } else {
2094 // Get rid of the subwindow if it exists
2095 dismissSubWindow(currentTab);
2096 if (!urlData.isEmpty()) {
2097 // Load the given url.
2098 loadUrlDataIn(currentTab, urlData);
2099 }
2100 return currentTab;
2101 }
2102 }
2103
Michael Kolb8233fac2010-10-26 16:08:53 -07002104 @Override
2105 public Tab openIncognitoTab() {
2106 if (mTabControl.canCreateNewTab()) {
2107 Tab currentTab = mTabControl.getCurrentTab();
2108 Tab tab = mTabControl.createNewTab(false, null, null, true);
2109 addTab(tab);
2110 setActiveTab(tab);
2111 return tab;
Michael Kolb843510f2010-12-09 10:51:49 -08002112 } else {
2113 mUi.showMaxTabsWarning();
2114 return null;
Michael Kolb8233fac2010-10-26 16:08:53 -07002115 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002116 }
2117
2118 /**
2119 * @param index Index of the tab to change to, as defined by
2120 * mTabControl.getTabIndex(Tab t).
2121 * @return boolean True if we successfully switched to a different tab. If
2122 * the indexth tab is null, or if that tab is the same as
2123 * the current one, return false.
2124 */
2125 @Override
2126 public boolean switchToTab(int index) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002127 // hide combo view if open
2128 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002129 Tab tab = mTabControl.getTab(index);
2130 Tab currentTab = mTabControl.getCurrentTab();
2131 if (tab == null || tab == currentTab) {
2132 return false;
2133 }
2134 setActiveTab(tab);
2135 return true;
2136 }
2137
2138 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002139 public void closeCurrentTab() {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002140 // hide combo view if open
2141 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002142 final Tab current = mTabControl.getCurrentTab();
2143 if (mTabControl.getTabCount() == 1) {
2144 // This is the last tab. Open a new one, with the home
2145 // page and close the current one.
2146 openTabToHomePage();
2147 closeTab(current);
2148 return;
2149 }
2150 final Tab parent = current.getParentTab();
2151 int indexToShow = -1;
2152 if (parent != null) {
2153 indexToShow = mTabControl.getTabIndex(parent);
2154 } else {
2155 final int currentIndex = mTabControl.getCurrentIndex();
2156 // Try to move to the tab to the right
2157 indexToShow = currentIndex + 1;
2158 if (indexToShow > mTabControl.getTabCount() - 1) {
2159 // Try to move to the tab to the left
2160 indexToShow = currentIndex - 1;
2161 }
2162 }
2163 if (switchToTab(indexToShow)) {
2164 // Close window
2165 closeTab(current);
2166 }
2167 }
2168
2169 /**
2170 * Close the tab, remove its associated title bar, and adjust mTabControl's
2171 * current tab to a valid value.
2172 */
2173 @Override
2174 public void closeTab(Tab tab) {
Michael Kolb14ee8fb2010-12-09 09:08:20 -08002175 // hide combo view if open
2176 removeComboView();
Michael Kolb8233fac2010-10-26 16:08:53 -07002177 int currentIndex = mTabControl.getCurrentIndex();
2178 int removeIndex = mTabControl.getTabIndex(tab);
2179 removeTab(tab);
2180 if (currentIndex >= removeIndex && currentIndex != 0) {
2181 currentIndex--;
2182 }
2183 Tab newtab = mTabControl.getTab(currentIndex);
2184 setActiveTab(newtab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002185 }
2186
2187 /**************** TODO: Url loading clean up *******************************/
2188
2189 // Called when loading from context menu or LOAD_URL message
2190 protected void loadUrlFromContext(WebView view, String url) {
2191 // In case the user enters nothing.
2192 if (url != null && url.length() != 0 && view != null) {
2193 url = UrlUtils.smartUrlFilter(url);
2194 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2195 loadUrl(view, url);
2196 }
2197 }
2198 }
2199
2200 /**
2201 * Load the URL into the given WebView and update the title bar
2202 * to reflect the new load. Call this instead of WebView.loadUrl
2203 * directly.
2204 * @param view The WebView used to load url.
2205 * @param url The URL to load.
2206 */
2207 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002208 view.loadUrl(url);
2209 }
2210
2211 /**
2212 * Load UrlData into a Tab and update the title bar to reflect the new
2213 * load. Call this instead of UrlData.loadIn directly.
2214 * @param t The Tab used to load.
2215 * @param data The UrlData being loaded.
2216 */
2217 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002218 data.loadIn(t);
2219 }
2220
2221 /**
2222 * Resets the browser title-view to whatever it must be
2223 * (for example, if we had a loading error)
2224 * When we have a new page, we call resetTitle, when we
2225 * have to reset the titlebar to whatever it used to be
2226 * (for example, if the user chose to stop loading), we
2227 * call resetTitleAndRevertLockIcon.
2228 */
2229 public void resetTitleAndRevertLockIcon(Tab tab) {
2230 mUi.resetTitleAndRevertLockIcon(tab);
2231 }
2232
2233 void resetTitleAndIcon(Tab tab) {
2234 mUi.resetTitleAndIcon(tab);
2235 }
2236
2237 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002238 * Sets a title composed of the URL and the title string.
2239 * @param url The URL of the site being loaded.
2240 * @param title The title of the site being loaded.
2241 */
2242 void setUrlTitle(Tab tab, String url, String title) {
2243 tab.setCurrentUrl(url);
2244 tab.setCurrentTitle(title);
2245 // If we are in voice search mode, the title has already been set.
2246 if (tab.isInVoiceSearchMode()) return;
2247 mUi.setUrlTitle(tab, url, title);
2248 }
2249
2250 void goBackOnePageOrQuit() {
2251 Tab current = mTabControl.getCurrentTab();
2252 if (current == null) {
2253 /*
2254 * Instead of finishing the activity, simply push this to the back
2255 * of the stack and let ActivityManager to choose the foreground
2256 * activity. As BrowserActivity is singleTask, it will be always the
2257 * root of the task. So we can use either true or false for
2258 * moveTaskToBack().
2259 */
2260 mActivity.moveTaskToBack(true);
2261 return;
2262 }
2263 WebView w = current.getWebView();
2264 if (w.canGoBack()) {
2265 w.goBack();
2266 } else {
2267 // Check to see if we are closing a window that was created by
2268 // another window. If so, we switch back to that window.
2269 Tab parent = current.getParentTab();
2270 if (parent != null) {
2271 switchToTab(mTabControl.getTabIndex(parent));
2272 // Now we close the other tab
2273 closeTab(current);
2274 } else {
2275 if (current.closeOnExit()) {
2276 // force the tab's inLoad() to be false as we are going to
2277 // either finish the activity or remove the tab. This will
2278 // ensure pauseWebViewTimers() taking action.
Michael Kolb70976932010-11-30 11:34:01 -08002279 current.clearInPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07002280 if (mTabControl.getTabCount() == 1) {
2281 mActivity.finish();
2282 return;
2283 }
2284 if (mActivityPaused) {
2285 Log.e(LOGTAG, "BrowserActivity is already paused "
2286 + "while handing goBackOnePageOrQuit.");
2287 }
Michael Kolb70976932010-11-30 11:34:01 -08002288 pauseWebViewTimers(current);
Michael Kolb8233fac2010-10-26 16:08:53 -07002289 removeTab(current);
2290 }
2291 /*
2292 * Instead of finishing the activity, simply push this to the back
2293 * of the stack and let ActivityManager to choose the foreground
2294 * activity. As BrowserActivity is singleTask, it will be always the
2295 * root of the task. So we can use either true or false for
2296 * moveTaskToBack().
2297 */
2298 mActivity.moveTaskToBack(true);
2299 }
2300 }
2301 }
2302
2303 /**
2304 * Feed the previously stored results strings to the BrowserProvider so that
2305 * the SearchDialog will show them instead of the standard searches.
2306 * @param result String to show on the editable line of the SearchDialog.
2307 */
2308 @Override
2309 public void showVoiceSearchResults(String result) {
2310 ContentProviderClient client = mActivity.getContentResolver()
2311 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2312 ContentProvider prov = client.getLocalContentProvider();
2313 BrowserProvider bp = (BrowserProvider) prov;
2314 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2315 client.release();
2316
2317 Bundle bundle = createGoogleSearchSourceBundle(
2318 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2319 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2320 startSearch(result, false, bundle, false);
2321 }
2322
2323 private void startSearch(String initialQuery, boolean selectInitialQuery,
2324 Bundle appSearchData, boolean globalSearch) {
2325 if (appSearchData == null) {
2326 appSearchData = createGoogleSearchSourceBundle(
2327 GOOGLE_SEARCH_SOURCE_TYPE);
2328 }
2329
2330 SearchEngine searchEngine = mSettings.getSearchEngine();
2331 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2332 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2333 }
2334 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2335 globalSearch);
2336 }
2337
2338 private Bundle createGoogleSearchSourceBundle(String source) {
2339 Bundle bundle = new Bundle();
2340 bundle.putString(Search.SOURCE, source);
2341 return bundle;
2342 }
2343
2344 /**
2345 * handle key events in browser
2346 *
2347 * @param keyCode
2348 * @param event
2349 * @return true if handled, false to pass to super
2350 */
2351 boolean onKeyDown(int keyCode, KeyEvent event) {
2352 // Even if MENU is already held down, we need to call to super to open
2353 // the IME on long press.
2354 if (KeyEvent.KEYCODE_MENU == keyCode) {
2355 mMenuIsDown = true;
2356 return false;
2357 }
2358 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2359 // still down, we don't want to trigger the search. Pretend to consume
2360 // the key and do nothing.
2361 if (mMenuIsDown) return true;
2362
2363 switch(keyCode) {
2364 case KeyEvent.KEYCODE_SPACE:
2365 // WebView/WebTextView handle the keys in the KeyDown. As
2366 // the Activity's shortcut keys are only handled when WebView
2367 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2368 if (event.isShiftPressed()) {
2369 pageUp();
2370 } else {
2371 pageDown();
2372 }
2373 return true;
2374 case KeyEvent.KEYCODE_BACK:
2375 if (event.getRepeatCount() == 0) {
2376 event.startTracking();
2377 return true;
2378 } else if (mUi.showsWeb()
2379 && event.isLongPress()) {
2380 bookmarksOrHistoryPicker(true);
2381 return true;
2382 }
2383 break;
2384 }
2385 return false;
2386 }
2387
2388 boolean onKeyUp(int keyCode, KeyEvent event) {
2389 switch(keyCode) {
2390 case KeyEvent.KEYCODE_MENU:
2391 mMenuIsDown = false;
2392 break;
2393 case KeyEvent.KEYCODE_BACK:
2394 if (event.isTracking() && !event.isCanceled()) {
2395 onBackKey();
2396 return true;
2397 }
2398 break;
2399 }
2400 return false;
2401 }
2402
2403 public boolean isMenuDown() {
2404 return mMenuIsDown;
2405 }
2406
Ben Murdoch8029a772010-11-16 11:58:21 +00002407 public void setupAutoFill(Message message) {
2408 // Open the settings activity at the AutoFill profile fragment so that
2409 // the user can create a new profile. When they return, we will dispatch
2410 // the message so that we can autofill the form using their new profile.
2411 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2412 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2413 AutoFillSettingsFragment.class.getName());
2414 mAutoFillSetupMessage = message;
2415 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2416 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002417}