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