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