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