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