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