blob: 5642d4d3c19f660852946c06b316a213405fd65e [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
1029 // end WebViewController
1030
1031 protected void pageUp() {
1032 getCurrentTopWebView().pageUp(false);
1033 }
1034
1035 protected void pageDown() {
1036 getCurrentTopWebView().pageDown(false);
1037 }
1038
1039 // callback from phone title bar
1040 public void editUrl() {
1041 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
1042 String url = (getCurrentTopWebView() == null) ? null : getCurrentTopWebView().getUrl();
1043 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1044 null, false);
1045 }
1046
1047 public void activateVoiceSearchMode(String title) {
1048 mUi.showVoiceTitleBar(title);
1049 }
1050
1051 public void revertVoiceSearchMode(Tab tab) {
1052 mUi.revertVoiceTitleBar(tab);
1053 }
1054
1055 public void showCustomView(Tab tab, View view,
1056 WebChromeClient.CustomViewCallback callback) {
1057 if (tab.inForeground()) {
1058 if (mUi.isCustomViewShowing()) {
1059 callback.onCustomViewHidden();
1060 return;
1061 }
1062 mUi.showCustomView(view, callback);
1063 // Save the menu state and set it to empty while the custom
1064 // view is showing.
1065 mOldMenuState = mMenuState;
1066 mMenuState = EMPTY_MENU;
1067 }
1068 }
1069
1070 @Override
1071 public void hideCustomView() {
1072 if (mUi.isCustomViewShowing()) {
1073 mUi.onHideCustomView();
1074 // Reset the old menu state.
1075 mMenuState = mOldMenuState;
1076 mOldMenuState = EMPTY_MENU;
1077 }
1078 }
1079
1080 protected void onActivityResult(int requestCode, int resultCode,
1081 Intent intent) {
1082 if (getCurrentTopWebView() == null) return;
1083 switch (requestCode) {
1084 case PREFERENCES_PAGE:
1085 if (resultCode == Activity.RESULT_OK && intent != null) {
1086 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
1087 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
1088 mTabControl.removeParentChildRelationShips();
1089 }
1090 }
1091 break;
1092 case FILE_SELECTED:
1093 // Choose a file from the file picker.
1094 if (null == mUploadHandler) break;
1095 mUploadHandler.onResult(resultCode, intent);
1096 mUploadHandler = null;
1097 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001098 case AUTOFILL_SETUP:
1099 // Determine whether a profile was actually set up or not
1100 // and if so, send the message back to the WebTextView to
1101 // fill the form with the new profile.
1102 if (getSettings().getAutoFillProfile() != null) {
1103 mAutoFillSetupMessage.sendToTarget();
1104 mAutoFillSetupMessage = null;
1105 }
1106 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001107 default:
1108 break;
1109 }
1110 getCurrentTopWebView().requestFocus();
1111 }
1112
1113 /**
1114 * Open the Go page.
1115 * @param startWithHistory If true, open starting on the history tab.
1116 * Otherwise, start with the bookmarks tab.
1117 */
1118 @Override
1119 public void bookmarksOrHistoryPicker(boolean startWithHistory) {
1120 if (mTabControl.getCurrentWebView() == null) {
1121 return;
1122 }
1123 Bundle extras = new Bundle();
1124 // Disable opening in a new window if we have maxed out the windows
1125 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1126 !mTabControl.canCreateNewTab());
1127 mUi.showComboView(startWithHistory, extras);
1128 }
1129
1130 // combo view callbacks
1131
1132 /**
1133 * callback from ComboPage when clear history is requested
1134 */
1135 public void onRemoveParentChildRelationships() {
1136 mTabControl.removeParentChildRelationShips();
1137 }
1138
1139 /**
1140 * callback from ComboPage when bookmark/history selection
1141 */
1142 @Override
1143 public void onUrlSelected(String url, boolean newTab) {
1144 removeComboView();
1145 if (!TextUtils.isEmpty(url)) {
1146 if (newTab) {
1147 openTab(url, false);
1148 } else {
1149 final Tab currentTab = mTabControl.getCurrentTab();
1150 dismissSubWindow(currentTab);
1151 loadUrl(getCurrentTopWebView(), url);
1152 }
1153 }
1154 }
1155
1156 /**
1157 * callback from ComboPage when dismissed
1158 */
1159 @Override
1160 public void onComboCanceled() {
1161 removeComboView();
1162 }
1163
1164 /**
1165 * dismiss the ComboPage
1166 */
1167 @Override
1168 public void removeComboView() {
1169 mUi.hideComboView();
1170 }
1171
1172 // active tabs page handling
1173
1174 protected void showActiveTabsPage() {
1175 mMenuState = EMPTY_MENU;
1176 mUi.showActiveTabsPage();
1177 }
1178
1179 /**
1180 * Remove the active tabs page.
1181 * @param needToAttach If true, the active tabs page did not attach a tab
1182 * to the content view, so we need to do that here.
1183 */
1184 @Override
1185 public void removeActiveTabsPage(boolean needToAttach) {
1186 mMenuState = R.id.MAIN_MENU;
1187 mUi.removeActiveTabsPage();
1188 if (needToAttach) {
1189 setActiveTab(mTabControl.getCurrentTab());
1190 }
1191 getCurrentTopWebView().requestFocus();
1192 }
1193
1194 // key handling
1195 protected void onBackKey() {
1196 if (!mUi.onBackKey()) {
1197 WebView subwindow = mTabControl.getCurrentSubWindow();
1198 if (subwindow != null) {
1199 if (subwindow.canGoBack()) {
1200 subwindow.goBack();
1201 } else {
1202 dismissSubWindow(mTabControl.getCurrentTab());
1203 }
1204 } else {
1205 goBackOnePageOrQuit();
1206 }
1207 }
1208 }
1209
1210 // menu handling and state
1211 // TODO: maybe put into separate handler
1212
1213 protected boolean onCreateOptionsMenu(Menu menu) {
1214 MenuInflater inflater = mActivity.getMenuInflater();
1215 inflater.inflate(R.menu.browser, menu);
1216 updateInLoadMenuItems(menu);
1217 // hold on to the menu reference here; it is used by the page callbacks
1218 // to update the menu based on loading state
1219 mCachedMenu = menu;
1220 return true;
1221 }
1222
1223 protected void onCreateContextMenu(ContextMenu menu, View v,
1224 ContextMenuInfo menuInfo) {
1225 if (v instanceof TitleBarBase) {
1226 return;
1227 }
1228 if (!(v instanceof WebView)) {
1229 return;
1230 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001231 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001232 WebView.HitTestResult result = webview.getHitTestResult();
1233 if (result == null) {
1234 return;
1235 }
1236
1237 int type = result.getType();
1238 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1239 Log.w(LOGTAG,
1240 "We should not show context menu when nothing is touched");
1241 return;
1242 }
1243 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1244 // let TextView handles context menu
1245 return;
1246 }
1247
1248 // Note, http://b/issue?id=1106666 is requesting that
1249 // an inflated menu can be used again. This is not available
1250 // yet, so inflate each time (yuk!)
1251 MenuInflater inflater = mActivity.getMenuInflater();
1252 inflater.inflate(R.menu.browsercontext, menu);
1253
1254 // Show the correct menu group
1255 final String extra = result.getExtra();
1256 menu.setGroupVisible(R.id.PHONE_MENU,
1257 type == WebView.HitTestResult.PHONE_TYPE);
1258 menu.setGroupVisible(R.id.EMAIL_MENU,
1259 type == WebView.HitTestResult.EMAIL_TYPE);
1260 menu.setGroupVisible(R.id.GEO_MENU,
1261 type == WebView.HitTestResult.GEO_TYPE);
1262 menu.setGroupVisible(R.id.IMAGE_MENU,
1263 type == WebView.HitTestResult.IMAGE_TYPE
1264 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1265 menu.setGroupVisible(R.id.ANCHOR_MENU,
1266 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1267 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark8974d282010-11-22 10:46:05 -05001268 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1269 || type == WebView.HitTestResult.PHONE_TYPE
1270 || type == WebView.HitTestResult.EMAIL_TYPE
1271 || type == WebView.HitTestResult.GEO_TYPE;
1272 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
1273 if (hitText) {
1274 menu.findItem(R.id.select_text_menu_id)
1275 .setOnMenuItemClickListener(new SelectText(webview));
1276 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001277 // Setup custom handling depending on the type
1278 switch (type) {
1279 case WebView.HitTestResult.PHONE_TYPE:
1280 menu.setHeaderTitle(Uri.decode(extra));
1281 menu.findItem(R.id.dial_context_menu_id).setIntent(
1282 new Intent(Intent.ACTION_VIEW, Uri
1283 .parse(WebView.SCHEME_TEL + extra)));
1284 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1285 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1286 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1287 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1288 addIntent);
1289 menu.findItem(R.id.copy_phone_context_menu_id)
1290 .setOnMenuItemClickListener(
1291 new Copy(extra));
1292 break;
1293
1294 case WebView.HitTestResult.EMAIL_TYPE:
1295 menu.setHeaderTitle(extra);
1296 menu.findItem(R.id.email_context_menu_id).setIntent(
1297 new Intent(Intent.ACTION_VIEW, Uri
1298 .parse(WebView.SCHEME_MAILTO + extra)));
1299 menu.findItem(R.id.copy_mail_context_menu_id)
1300 .setOnMenuItemClickListener(
1301 new Copy(extra));
1302 break;
1303
1304 case WebView.HitTestResult.GEO_TYPE:
1305 menu.setHeaderTitle(extra);
1306 menu.findItem(R.id.map_context_menu_id).setIntent(
1307 new Intent(Intent.ACTION_VIEW, Uri
1308 .parse(WebView.SCHEME_GEO
1309 + URLEncoder.encode(extra))));
1310 menu.findItem(R.id.copy_geo_context_menu_id)
1311 .setOnMenuItemClickListener(
1312 new Copy(extra));
1313 break;
1314
1315 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1316 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1317 TextView titleView = (TextView) LayoutInflater.from(mActivity)
1318 .inflate(android.R.layout.browser_link_context_header,
1319 null);
1320 titleView.setText(extra);
1321 menu.setHeaderView(titleView);
1322 // decide whether to show the open link in new tab option
1323 boolean showNewTab = mTabControl.canCreateNewTab();
1324 MenuItem newTabItem
1325 = menu.findItem(R.id.open_newtab_context_menu_id);
1326 newTabItem.setVisible(showNewTab);
1327 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001328 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1329 newTabItem.setOnMenuItemClickListener(
1330 new MenuItem.OnMenuItemClickListener() {
1331 @Override
1332 public boolean onMenuItemClick(MenuItem item) {
1333 final HashMap<String, WebView> hrefMap =
1334 new HashMap<String, WebView>();
1335 hrefMap.put("webview", webview);
1336 final Message msg = mHandler.obtainMessage(
1337 FOCUS_NODE_HREF,
1338 R.id.open_newtab_context_menu_id,
1339 0, hrefMap);
1340 webview.requestFocusNodeHref(msg);
1341 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001342 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001343 });
1344 } else {
1345 newTabItem.setOnMenuItemClickListener(
1346 new MenuItem.OnMenuItemClickListener() {
1347 @Override
1348 public boolean onMenuItemClick(MenuItem item) {
1349 final Tab parent = mTabControl.getCurrentTab();
1350 final Tab newTab = openTab(extra, false);
1351 if (newTab != parent) {
1352 parent.addChildTab(newTab);
1353 }
1354 return true;
1355 }
1356 });
1357 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001358 }
1359 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1360 Bookmarks.urlHasAcceptableScheme(extra));
1361 PackageManager pm = mActivity.getPackageManager();
1362 Intent send = new Intent(Intent.ACTION_SEND);
1363 send.setType("text/plain");
1364 ResolveInfo ri = pm.resolveActivity(send,
1365 PackageManager.MATCH_DEFAULT_ONLY);
1366 menu.findItem(R.id.share_link_context_menu_id)
1367 .setVisible(ri != null);
1368 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1369 break;
1370 }
1371 // otherwise fall through to handle image part
1372 case WebView.HitTestResult.IMAGE_TYPE:
1373 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1374 menu.setHeaderTitle(extra);
1375 }
1376 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1377 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1378 menu.findItem(R.id.download_context_menu_id).
Leon Scroggins63c02662010-11-18 15:16:27 -05001379 setOnMenuItemClickListener(new Download(mActivity, extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001380 menu.findItem(R.id.set_wallpaper_context_menu_id).
1381 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1382 extra));
1383 break;
1384
1385 default:
1386 Log.w(LOGTAG, "We should not get here.");
1387 break;
1388 }
1389 //update the ui
1390 mUi.onContextMenuCreated(menu);
1391 }
1392
1393 /**
1394 * As the menu can be open when loading state changes
1395 * we must manually update the state of the stop/reload menu
1396 * item
1397 */
1398 private void updateInLoadMenuItems(Menu menu) {
1399 if (menu == null) {
1400 return;
1401 }
1402 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1403 MenuItem src = mInLoad ?
1404 menu.findItem(R.id.stop_menu_id):
1405 menu.findItem(R.id.reload_menu_id);
1406 if (src != null) {
1407 dest.setIcon(src.getIcon());
1408 dest.setTitle(src.getTitle());
1409 }
1410 }
1411
1412 boolean prepareOptionsMenu(Menu menu) {
1413 // This happens when the user begins to hold down the menu key, so
1414 // allow them to chord to get a shortcut.
1415 mCanChord = true;
1416 // Note: setVisible will decide whether an item is visible; while
1417 // setEnabled() will decide whether an item is enabled, which also means
1418 // whether the matching shortcut key will function.
1419 switch (mMenuState) {
1420 case EMPTY_MENU:
1421 if (mCurrentMenuState != mMenuState) {
1422 menu.setGroupVisible(R.id.MAIN_MENU, false);
1423 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1424 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1425 }
1426 break;
1427 default:
1428 if (mCurrentMenuState != mMenuState) {
1429 menu.setGroupVisible(R.id.MAIN_MENU, true);
1430 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1431 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1432 }
1433 final WebView w = getCurrentTopWebView();
1434 boolean canGoBack = false;
1435 boolean canGoForward = false;
1436 boolean isHome = false;
1437 if (w != null) {
1438 canGoBack = w.canGoBack();
1439 canGoForward = w.canGoForward();
1440 isHome = mSettings.getHomePage().equals(w.getUrl());
1441 }
1442 final MenuItem back = menu.findItem(R.id.back_menu_id);
1443 back.setEnabled(canGoBack);
1444
1445 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1446 home.setEnabled(!isHome);
1447
1448 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1449 forward.setEnabled(canGoForward);
1450
1451 // decide whether to show the share link option
1452 PackageManager pm = mActivity.getPackageManager();
1453 Intent send = new Intent(Intent.ACTION_SEND);
1454 send.setType("text/plain");
1455 ResolveInfo ri = pm.resolveActivity(send,
1456 PackageManager.MATCH_DEFAULT_ONLY);
1457 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1458
1459 boolean isNavDump = mSettings.isNavDump();
1460 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1461 nav.setVisible(isNavDump);
1462 nav.setEnabled(isNavDump);
1463
1464 boolean showDebugSettings = mSettings.showDebugSettings();
1465 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1466 counter.setVisible(showDebugSettings);
1467 counter.setEnabled(showDebugSettings);
1468
1469 // allow the ui to adjust state based settings
1470 mUi.onPrepareOptionsMenu(menu);
1471
1472 break;
1473 }
1474 mCurrentMenuState = mMenuState;
1475 return true;
1476 }
1477
1478 public boolean onOptionsItemSelected(MenuItem item) {
1479 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1480 // menu remains active, so ensure comboview is dismissed
1481 // if main menu option is selected
1482 removeComboView();
1483 }
1484 // check the action bar button before mCanChord check, as the prepare call
1485 // doesn't come for action bar buttons
1486 if (item.getItemId() == R.id.newtab) {
1487 openTabToHomePage();
1488 return true;
1489 }
1490 if (!mCanChord) {
1491 // The user has already fired a shortcut with this hold down of the
1492 // menu key.
1493 return false;
1494 }
1495 if (null == getCurrentTopWebView()) {
1496 return false;
1497 }
1498 if (mMenuIsDown) {
1499 // The shortcut action consumes the MENU. Even if it is still down,
1500 // it won't trigger the next shortcut action. In the case of the
1501 // shortcut action triggering a new activity, like Bookmarks, we
1502 // won't get onKeyUp for MENU. So it is important to reset it here.
1503 mMenuIsDown = false;
1504 }
1505 switch (item.getItemId()) {
1506 // -- Main menu
1507 case R.id.new_tab_menu_id:
1508 openTabToHomePage();
1509 break;
1510
1511 case R.id.incognito_menu_id:
1512 openIncognitoTab();
1513 break;
1514
1515 case R.id.goto_menu_id:
1516 editUrl();
1517 break;
1518
1519 case R.id.bookmarks_menu_id:
1520 bookmarksOrHistoryPicker(false);
1521 break;
1522
1523 case R.id.active_tabs_menu_id:
1524 showActiveTabsPage();
1525 break;
1526
1527 case R.id.add_bookmark_menu_id:
1528 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
1529 break;
1530
1531 case R.id.stop_reload_menu_id:
1532 if (mInLoad) {
1533 stopLoading();
1534 } else {
1535 getCurrentTopWebView().reload();
1536 }
1537 break;
1538
1539 case R.id.back_menu_id:
1540 getCurrentTopWebView().goBack();
1541 break;
1542
1543 case R.id.forward_menu_id:
1544 getCurrentTopWebView().goForward();
1545 break;
1546
1547 case R.id.close_menu_id:
1548 // Close the subwindow if it exists.
1549 if (mTabControl.getCurrentSubWindow() != null) {
1550 dismissSubWindow(mTabControl.getCurrentTab());
1551 break;
1552 }
1553 closeCurrentTab();
1554 break;
1555
1556 case R.id.homepage_menu_id:
1557 Tab current = mTabControl.getCurrentTab();
1558 if (current != null) {
1559 dismissSubWindow(current);
1560 loadUrl(current.getWebView(), mSettings.getHomePage());
1561 }
1562 break;
1563
1564 case R.id.preferences_menu_id:
1565 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1566 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1567 getCurrentTopWebView().getUrl());
1568 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1569 break;
1570
1571 case R.id.find_menu_id:
1572 getCurrentTopWebView().showFindDialog(null);
1573 break;
1574
1575 case R.id.page_info_menu_id:
1576 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1577 false);
1578 break;
1579
1580 case R.id.classic_history_menu_id:
1581 bookmarksOrHistoryPicker(true);
1582 break;
1583
1584 case R.id.title_bar_share_page_url:
1585 case R.id.share_page_menu_id:
1586 Tab currentTab = mTabControl.getCurrentTab();
1587 if (null == currentTab) {
1588 mCanChord = false;
1589 return false;
1590 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08001591 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001592 break;
1593
1594 case R.id.dump_nav_menu_id:
1595 getCurrentTopWebView().debugDump();
1596 break;
1597
1598 case R.id.dump_counters_menu_id:
1599 getCurrentTopWebView().dumpV8Counters();
1600 break;
1601
1602 case R.id.zoom_in_menu_id:
1603 getCurrentTopWebView().zoomIn();
1604 break;
1605
1606 case R.id.zoom_out_menu_id:
1607 getCurrentTopWebView().zoomOut();
1608 break;
1609
1610 case R.id.view_downloads_menu_id:
1611 viewDownloads();
1612 break;
1613
1614 case R.id.window_one_menu_id:
1615 case R.id.window_two_menu_id:
1616 case R.id.window_three_menu_id:
1617 case R.id.window_four_menu_id:
1618 case R.id.window_five_menu_id:
1619 case R.id.window_six_menu_id:
1620 case R.id.window_seven_menu_id:
1621 case R.id.window_eight_menu_id:
1622 {
1623 int menuid = item.getItemId();
1624 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1625 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1626 Tab desiredTab = mTabControl.getTab(id);
1627 if (desiredTab != null &&
1628 desiredTab != mTabControl.getCurrentTab()) {
1629 switchToTab(id);
1630 }
1631 break;
1632 }
1633 }
1634 }
1635 break;
1636
1637 default:
1638 return false;
1639 }
1640 mCanChord = false;
1641 return true;
1642 }
1643
1644 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001645 // Let the History and Bookmark fragments handle menus they created.
1646 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1647 return false;
1648 }
1649
Michael Kolb8233fac2010-10-26 16:08:53 -07001650 // chording is not an issue with context menus, but we use the same
1651 // options selector, so set mCanChord to true so we can access them.
1652 mCanChord = true;
1653 int id = item.getItemId();
1654 boolean result = true;
1655 switch (id) {
1656 // For the context menu from the title bar
1657 case R.id.title_bar_copy_page_url:
1658 Tab currentTab = mTabControl.getCurrentTab();
1659 if (null == currentTab) {
1660 result = false;
1661 break;
1662 }
1663 WebView mainView = currentTab.getWebView();
1664 if (null == mainView) {
1665 result = false;
1666 break;
1667 }
1668 copy(mainView.getUrl());
1669 break;
1670 // -- Browser context menu
1671 case R.id.open_context_menu_id:
1672 case R.id.bookmark_context_menu_id:
1673 case R.id.save_link_context_menu_id:
1674 case R.id.share_link_context_menu_id:
1675 case R.id.copy_link_context_menu_id:
1676 final WebView webView = getCurrentTopWebView();
1677 if (null == webView) {
1678 result = false;
1679 break;
1680 }
1681 final HashMap<String, WebView> hrefMap =
1682 new HashMap<String, WebView>();
1683 hrefMap.put("webview", webView);
1684 final Message msg = mHandler.obtainMessage(
1685 FOCUS_NODE_HREF, id, 0, hrefMap);
1686 webView.requestFocusNodeHref(msg);
1687 break;
1688
1689 default:
1690 // For other context menus
1691 result = onOptionsItemSelected(item);
1692 }
1693 mCanChord = false;
1694 return result;
1695 }
1696
1697 /**
1698 * support programmatically opening the context menu
1699 */
1700 public void openContextMenu(View view) {
1701 mActivity.openContextMenu(view);
1702 }
1703
1704 /**
1705 * programmatically open the options menu
1706 */
1707 public void openOptionsMenu() {
1708 mActivity.openOptionsMenu();
1709 }
1710
1711 public boolean onMenuOpened(int featureId, Menu menu) {
1712 if (mOptionsMenuOpen) {
1713 if (mConfigChanged) {
1714 // We do not need to make any changes to the state of the
1715 // title bar, since the only thing that happened was a
1716 // change in orientation
1717 mConfigChanged = false;
1718 } else {
1719 if (!mExtendedMenuOpen) {
1720 mExtendedMenuOpen = true;
1721 mUi.onExtendedMenuOpened();
1722 } else {
1723 // Switching the menu back to icon view, so show the
1724 // title bar once again.
1725 mExtendedMenuOpen = false;
1726 mUi.onExtendedMenuClosed(mInLoad);
1727 mUi.onOptionsMenuOpened();
1728 }
1729 }
1730 } else {
1731 // The options menu is closed, so open it, and show the title
1732 mOptionsMenuOpen = true;
1733 mConfigChanged = false;
1734 mExtendedMenuOpen = false;
1735 mUi.onOptionsMenuOpened();
1736 }
1737 return true;
1738 }
1739
1740 public void onOptionsMenuClosed(Menu menu) {
1741 mOptionsMenuOpen = false;
1742 mUi.onOptionsMenuClosed(mInLoad);
1743 }
1744
1745 public void onContextMenuClosed(Menu menu) {
1746 mUi.onContextMenuClosed(menu, mInLoad);
1747 }
1748
1749 // Helper method for getting the top window.
1750 @Override
1751 public WebView getCurrentTopWebView() {
1752 return mTabControl.getCurrentTopWebView();
1753 }
1754
1755 @Override
1756 public WebView getCurrentWebView() {
1757 return mTabControl.getCurrentWebView();
1758 }
1759
1760 /*
1761 * This method is called as a result of the user selecting the options
1762 * menu to see the download window. It shows the download window on top of
1763 * the current window.
1764 */
1765 void viewDownloads() {
1766 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1767 mActivity.startActivity(intent);
1768 }
1769
1770 // action mode
1771
1772 void onActionModeStarted(ActionMode mode) {
1773 mUi.onActionModeStarted(mode);
1774 mActionMode = mode;
1775 }
1776
1777 /*
1778 * True if a custom ActionMode (i.e. find or select) is in use.
1779 */
1780 @Override
1781 public boolean isInCustomActionMode() {
1782 return mActionMode != null;
1783 }
1784
1785 /*
1786 * End the current ActionMode.
1787 */
1788 @Override
1789 public void endActionMode() {
1790 if (mActionMode != null) {
1791 mActionMode.finish();
1792 }
1793 }
1794
1795 /*
1796 * Called by find and select when they are finished. Replace title bars
1797 * as necessary.
1798 */
1799 public void onActionModeFinished(ActionMode mode) {
1800 if (!isInCustomActionMode()) return;
1801 mUi.onActionModeFinished(mInLoad);
1802 mActionMode = null;
1803 }
1804
1805 boolean isInLoad() {
1806 return mInLoad;
1807 }
1808
1809 // bookmark handling
1810
1811 /**
1812 * add the current page as a bookmark to the given folder id
1813 * @param folderId use -1 for the default folder
1814 */
1815 @Override
1816 public void bookmarkCurrentPage(long folderId) {
1817 Intent i = new Intent(mActivity,
1818 AddBookmarkPage.class);
1819 WebView w = getCurrentTopWebView();
1820 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1821 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1822 String touchIconUrl = w.getTouchIconUrl();
1823 if (touchIconUrl != null) {
1824 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1825 WebSettings settings = w.getSettings();
1826 if (settings != null) {
1827 i.putExtra(AddBookmarkPage.USER_AGENT,
1828 settings.getUserAgentString());
1829 }
1830 }
1831 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1832 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1833 getDesiredThumbnailHeight(mActivity)));
1834 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1835 i.putExtra(BrowserContract.Bookmarks.PARENT,
1836 folderId);
1837 // Put the dialog at the upper right of the screen, covering the
1838 // star on the title bar.
1839 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1840 mActivity.startActivity(i);
1841 }
1842
1843 // file chooser
1844 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1845 mUploadHandler = new UploadHandler(this);
1846 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1847 }
1848
1849 // thumbnails
1850
1851 /**
1852 * Return the desired width for thumbnail screenshots, which are stored in
1853 * the database, and used on the bookmarks screen.
1854 * @param context Context for finding out the density of the screen.
1855 * @return desired width for thumbnail screenshot.
1856 */
1857 static int getDesiredThumbnailWidth(Context context) {
1858 return context.getResources().getDimensionPixelOffset(
1859 R.dimen.bookmarkThumbnailWidth);
1860 }
1861
1862 /**
1863 * Return the desired height for thumbnail screenshots, which are stored in
1864 * the database, and used on the bookmarks screen.
1865 * @param context Context for finding out the density of the screen.
1866 * @return desired height for thumbnail screenshot.
1867 */
1868 static int getDesiredThumbnailHeight(Context context) {
1869 return context.getResources().getDimensionPixelOffset(
1870 R.dimen.bookmarkThumbnailHeight);
1871 }
1872
1873 private static Bitmap createScreenshot(WebView view, int width, int height) {
1874 Picture thumbnail = view.capturePicture();
1875 if (thumbnail == null) {
1876 return null;
1877 }
1878 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1879 Canvas canvas = new Canvas(bm);
1880 // May need to tweak these values to determine what is the
1881 // best scale factor
1882 int thumbnailWidth = thumbnail.getWidth();
1883 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001884 float scaleFactor = 1.0f;
Michael Kolb8233fac2010-10-26 16:08:53 -07001885 if (thumbnailWidth > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001886 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001887 } else {
1888 return null;
1889 }
John Reckfe49ab42010-11-16 17:09:37 -08001890
Michael Kolb8233fac2010-10-26 16:08:53 -07001891 if (view.getWidth() > view.getHeight() &&
1892 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
1893 // If the device is in landscape and the page is shorter
John Reckfe49ab42010-11-16 17:09:37 -08001894 // than the height of the view, center the thumnail and crop the sides
1895 scaleFactor = (float) height / (float)thumbnailHeight;
1896 float wx = (thumbnailWidth * scaleFactor) - width;
1897 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001898 }
1899
John Reckfe49ab42010-11-16 17:09:37 -08001900 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001901
1902 thumbnail.draw(canvas);
1903 return bm;
1904 }
1905
1906 private void updateScreenshot(WebView view) {
1907 // If this is a bookmarked site, add a screenshot to the database.
1908 // FIXME: When should we update? Every time?
1909 // FIXME: Would like to make sure there is actually something to
1910 // draw, but the API for that (WebViewCore.pictureReady()) is not
1911 // currently accessible here.
1912
1913 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1914 getDesiredThumbnailHeight(mActivity));
1915 if (bm == null) {
1916 return;
1917 }
1918
1919 final ContentResolver cr = mActivity.getContentResolver();
1920 final String url = view.getUrl();
1921 final String originalUrl = view.getOriginalUrl();
1922
1923 new AsyncTask<Void, Void, Void>() {
1924 @Override
1925 protected Void doInBackground(Void... unused) {
1926 Cursor cursor = null;
1927 try {
1928 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
1929 if (cursor != null && cursor.moveToFirst()) {
1930 final ByteArrayOutputStream os =
1931 new ByteArrayOutputStream();
1932 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
1933
1934 ContentValues values = new ContentValues();
1935 values.put(Images.THUMBNAIL, os.toByteArray());
1936 values.put(Images.URL, cursor.getString(0));
1937
1938 do {
1939 cr.update(Images.CONTENT_URI, values, null, null);
1940 } while (cursor.moveToNext());
1941 }
1942 } catch (IllegalStateException e) {
1943 // Ignore
1944 } finally {
1945 if (cursor != null) cursor.close();
1946 }
1947 return null;
1948 }
1949 }.execute();
1950 }
1951
1952 private class Copy implements OnMenuItemClickListener {
1953 private CharSequence mText;
1954
1955 public boolean onMenuItemClick(MenuItem item) {
1956 copy(mText);
1957 return true;
1958 }
1959
1960 public Copy(CharSequence toCopy) {
1961 mText = toCopy;
1962 }
1963 }
1964
Leon Scroggins63c02662010-11-18 15:16:27 -05001965 private static class Download implements OnMenuItemClickListener {
1966 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001967 private String mText;
1968
1969 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05001970 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
1971 null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001972 return true;
1973 }
1974
Leon Scroggins63c02662010-11-18 15:16:27 -05001975 public Download(Activity activity, String toDownload) {
1976 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001977 mText = toDownload;
1978 }
1979 }
1980
Cary Clark8974d282010-11-22 10:46:05 -05001981 private static class SelectText implements OnMenuItemClickListener {
1982 private WebView mWebView;
1983
1984 public boolean onMenuItemClick(MenuItem item) {
1985 if (mWebView != null) {
1986 return mWebView.selectText();
1987 }
1988 return false;
1989 }
1990
1991 public SelectText(WebView webView) {
1992 mWebView = webView;
1993 }
1994
1995 }
1996
Michael Kolb8233fac2010-10-26 16:08:53 -07001997 /********************** TODO: UI stuff *****************************/
1998
1999 // these methods have been copied, they still need to be cleaned up
2000
2001 /****************** tabs ***************************************************/
2002
2003 // basic tab interactions:
2004
2005 // it is assumed that tabcontrol already knows about the tab
2006 protected void addTab(Tab tab) {
2007 mUi.addTab(tab);
2008 }
2009
2010 protected void removeTab(Tab tab) {
2011 mUi.removeTab(tab);
2012 mTabControl.removeTab(tab);
2013 }
2014
2015 protected void setActiveTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002016 mTabControl.setCurrentTab(tab);
Michael Kolb77df4562010-11-19 14:49:34 -08002017 // the tab is guaranteed to have a webview after setCurrentTab
2018 mUi.setActiveTab(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002019 }
2020
2021 protected void closeEmptyChildTab() {
2022 Tab current = mTabControl.getCurrentTab();
2023 if (current != null
2024 && current.getWebView().copyBackForwardList().getSize() == 0) {
2025 Tab parent = current.getParentTab();
2026 if (parent != null) {
2027 switchToTab(mTabControl.getTabIndex(parent));
2028 closeTab(current);
2029 }
2030 }
2031 }
2032
2033 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
2034 Log.i(LOGTAG, "Reusing tab for " + appId);
2035 // Dismiss the subwindow if applicable.
2036 dismissSubWindow(appTab);
2037 // Since we might kill the WebView, remove it from the
2038 // content view first.
2039 mUi.detachTab(appTab);
2040 // Recreate the main WebView after destroying the old one.
2041 // If the WebView has the same original url and is on that
2042 // page, it can be reused.
2043 boolean needsLoad =
2044 mTabControl.recreateWebView(appTab, urlData);
2045 // TODO: analyze why the remove and add are necessary
2046 mUi.attachTab(appTab);
2047 if (mTabControl.getCurrentTab() != appTab) {
2048 switchToTab(mTabControl.getTabIndex(appTab));
2049 if (needsLoad) {
2050 loadUrlDataIn(appTab, urlData);
2051 }
2052 } else {
2053 // If the tab was the current tab, we have to attach
2054 // it to the view system again.
2055 setActiveTab(appTab);
2056 if (needsLoad) {
2057 loadUrlDataIn(appTab, urlData);
2058 }
2059 }
2060 }
2061
2062 // Remove the sub window if it exists. Also called by TabControl when the
2063 // user clicks the 'X' to dismiss a sub window.
2064 public void dismissSubWindow(Tab tab) {
2065 removeSubWindow(tab);
2066 // dismiss the subwindow. This will destroy the WebView.
2067 tab.dismissSubWindow();
2068 getCurrentTopWebView().requestFocus();
2069 }
2070
2071 @Override
2072 public void removeSubWindow(Tab t) {
2073 if (t.getSubWebView() != null) {
2074 mUi.removeSubWindow(t.getSubViewContainer());
2075 }
2076 }
2077
2078 @Override
2079 public void attachSubWindow(Tab tab) {
2080 if (tab.getSubWebView() != null) {
2081 mUi.attachSubWindow(tab.getSubViewContainer());
2082 getCurrentTopWebView().requestFocus();
2083 }
2084 }
2085
2086 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
2087 // that accepts url as string.
2088
2089 protected Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
2090 return openTabAndShow(new UrlData(url), closeOnExit, appId);
2091 }
2092
2093 // This method does a ton of stuff. It will attempt to create a new tab
2094 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2095 // url isn't null, it will load the given url.
2096
2097 public Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
2098 String appId) {
2099 final Tab currentTab = mTabControl.getCurrentTab();
2100 if (mTabControl.canCreateNewTab()) {
2101 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
2102 urlData.mUrl, false);
2103 WebView webview = tab.getWebView();
2104 // We must set the new tab as the current tab to reflect the old
2105 // animation behavior.
2106 addTab(tab);
2107 setActiveTab(tab);
2108 if (!urlData.isEmpty()) {
2109 loadUrlDataIn(tab, urlData);
2110 }
2111 return tab;
2112 } else {
2113 // Get rid of the subwindow if it exists
2114 dismissSubWindow(currentTab);
2115 if (!urlData.isEmpty()) {
2116 // Load the given url.
2117 loadUrlDataIn(currentTab, urlData);
2118 }
2119 return currentTab;
2120 }
2121 }
2122
2123 protected Tab openTab(String url, boolean forceForeground) {
2124 if (mSettings.openInBackground() && !forceForeground) {
2125 Tab tab = mTabControl.createNewTab();
2126 if (tab != null) {
2127 addTab(tab);
2128 WebView view = tab.getWebView();
2129 loadUrl(view, url);
2130 }
2131 return tab;
2132 } else {
2133 return openTabAndShow(url, false, null);
2134 }
2135 }
2136
2137 @Override
2138 public Tab openIncognitoTab() {
2139 if (mTabControl.canCreateNewTab()) {
2140 Tab currentTab = mTabControl.getCurrentTab();
2141 Tab tab = mTabControl.createNewTab(false, null, null, true);
2142 addTab(tab);
2143 setActiveTab(tab);
2144 return tab;
2145 }
2146 return null;
2147 }
2148
2149 /**
2150 * @param index Index of the tab to change to, as defined by
2151 * mTabControl.getTabIndex(Tab t).
2152 * @return boolean True if we successfully switched to a different tab. If
2153 * the indexth tab is null, or if that tab is the same as
2154 * the current one, return false.
2155 */
2156 @Override
2157 public boolean switchToTab(int index) {
2158 Tab tab = mTabControl.getTab(index);
2159 Tab currentTab = mTabControl.getCurrentTab();
2160 if (tab == null || tab == currentTab) {
2161 return false;
2162 }
2163 setActiveTab(tab);
2164 return true;
2165 }
2166
2167 @Override
2168 public Tab openTabToHomePage() {
2169 return openTabAndShow(mSettings.getHomePage(), false, null);
2170 }
2171
2172 @Override
2173 public void closeCurrentTab() {
2174 final Tab current = mTabControl.getCurrentTab();
2175 if (mTabControl.getTabCount() == 1) {
2176 // This is the last tab. Open a new one, with the home
2177 // page and close the current one.
2178 openTabToHomePage();
2179 closeTab(current);
2180 return;
2181 }
2182 final Tab parent = current.getParentTab();
2183 int indexToShow = -1;
2184 if (parent != null) {
2185 indexToShow = mTabControl.getTabIndex(parent);
2186 } else {
2187 final int currentIndex = mTabControl.getCurrentIndex();
2188 // Try to move to the tab to the right
2189 indexToShow = currentIndex + 1;
2190 if (indexToShow > mTabControl.getTabCount() - 1) {
2191 // Try to move to the tab to the left
2192 indexToShow = currentIndex - 1;
2193 }
2194 }
2195 if (switchToTab(indexToShow)) {
2196 // Close window
2197 closeTab(current);
2198 }
2199 }
2200
2201 /**
2202 * Close the tab, remove its associated title bar, and adjust mTabControl's
2203 * current tab to a valid value.
2204 */
2205 @Override
2206 public void closeTab(Tab tab) {
2207 int currentIndex = mTabControl.getCurrentIndex();
2208 int removeIndex = mTabControl.getTabIndex(tab);
2209 removeTab(tab);
2210 if (currentIndex >= removeIndex && currentIndex != 0) {
2211 currentIndex--;
2212 }
2213 Tab newtab = mTabControl.getTab(currentIndex);
2214 setActiveTab(newtab);
2215 if (!mTabControl.hasAnyOpenIncognitoTabs()) {
Steve Block83101a82010-11-26 11:33:35 +00002216 WebView.cleanupPrivateBrowsingFiles();
Michael Kolb8233fac2010-10-26 16:08:53 -07002217 }
2218 }
2219
2220 /**************** TODO: Url loading clean up *******************************/
2221
2222 // Called when loading from context menu or LOAD_URL message
2223 protected void loadUrlFromContext(WebView view, String url) {
2224 // In case the user enters nothing.
2225 if (url != null && url.length() != 0 && view != null) {
2226 url = UrlUtils.smartUrlFilter(url);
2227 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2228 loadUrl(view, url);
2229 }
2230 }
2231 }
2232
2233 /**
2234 * Load the URL into the given WebView and update the title bar
2235 * to reflect the new load. Call this instead of WebView.loadUrl
2236 * directly.
2237 * @param view The WebView used to load url.
2238 * @param url The URL to load.
2239 */
2240 protected void loadUrl(WebView view, String url) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002241 view.loadUrl(url);
2242 }
2243
2244 /**
2245 * Load UrlData into a Tab and update the title bar to reflect the new
2246 * load. Call this instead of UrlData.loadIn directly.
2247 * @param t The Tab used to load.
2248 * @param data The UrlData being loaded.
2249 */
2250 protected void loadUrlDataIn(Tab t, UrlData data) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002251 data.loadIn(t);
2252 }
2253
2254 /**
2255 * Resets the browser title-view to whatever it must be
2256 * (for example, if we had a loading error)
2257 * When we have a new page, we call resetTitle, when we
2258 * have to reset the titlebar to whatever it used to be
2259 * (for example, if the user chose to stop loading), we
2260 * call resetTitleAndRevertLockIcon.
2261 */
2262 public void resetTitleAndRevertLockIcon(Tab tab) {
2263 mUi.resetTitleAndRevertLockIcon(tab);
2264 }
2265
2266 void resetTitleAndIcon(Tab tab) {
2267 mUi.resetTitleAndIcon(tab);
2268 }
2269
2270 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07002271 * Sets a title composed of the URL and the title string.
2272 * @param url The URL of the site being loaded.
2273 * @param title The title of the site being loaded.
2274 */
2275 void setUrlTitle(Tab tab, String url, String title) {
2276 tab.setCurrentUrl(url);
2277 tab.setCurrentTitle(title);
2278 // If we are in voice search mode, the title has already been set.
2279 if (tab.isInVoiceSearchMode()) return;
2280 mUi.setUrlTitle(tab, url, title);
2281 }
2282
2283 void goBackOnePageOrQuit() {
2284 Tab current = mTabControl.getCurrentTab();
2285 if (current == null) {
2286 /*
2287 * Instead of finishing the activity, simply push this to the back
2288 * of the stack and let ActivityManager to choose the foreground
2289 * activity. As BrowserActivity is singleTask, it will be always the
2290 * root of the task. So we can use either true or false for
2291 * moveTaskToBack().
2292 */
2293 mActivity.moveTaskToBack(true);
2294 return;
2295 }
2296 WebView w = current.getWebView();
2297 if (w.canGoBack()) {
2298 w.goBack();
2299 } else {
2300 // Check to see if we are closing a window that was created by
2301 // another window. If so, we switch back to that window.
2302 Tab parent = current.getParentTab();
2303 if (parent != null) {
2304 switchToTab(mTabControl.getTabIndex(parent));
2305 // Now we close the other tab
2306 closeTab(current);
2307 } else {
2308 if (current.closeOnExit()) {
2309 // force the tab's inLoad() to be false as we are going to
2310 // either finish the activity or remove the tab. This will
2311 // ensure pauseWebViewTimers() taking action.
Michael Kolb70976932010-11-30 11:34:01 -08002312 current.clearInPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07002313 if (mTabControl.getTabCount() == 1) {
2314 mActivity.finish();
2315 return;
2316 }
2317 if (mActivityPaused) {
2318 Log.e(LOGTAG, "BrowserActivity is already paused "
2319 + "while handing goBackOnePageOrQuit.");
2320 }
Michael Kolb70976932010-11-30 11:34:01 -08002321 pauseWebViewTimers(current);
Michael Kolb8233fac2010-10-26 16:08:53 -07002322 removeTab(current);
2323 }
2324 /*
2325 * Instead of finishing the activity, simply push this to the back
2326 * of the stack and let ActivityManager to choose the foreground
2327 * activity. As BrowserActivity is singleTask, it will be always the
2328 * root of the task. So we can use either true or false for
2329 * moveTaskToBack().
2330 */
2331 mActivity.moveTaskToBack(true);
2332 }
2333 }
2334 }
2335
2336 /**
2337 * Feed the previously stored results strings to the BrowserProvider so that
2338 * the SearchDialog will show them instead of the standard searches.
2339 * @param result String to show on the editable line of the SearchDialog.
2340 */
2341 @Override
2342 public void showVoiceSearchResults(String result) {
2343 ContentProviderClient client = mActivity.getContentResolver()
2344 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2345 ContentProvider prov = client.getLocalContentProvider();
2346 BrowserProvider bp = (BrowserProvider) prov;
2347 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2348 client.release();
2349
2350 Bundle bundle = createGoogleSearchSourceBundle(
2351 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2352 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2353 startSearch(result, false, bundle, false);
2354 }
2355
2356 private void startSearch(String initialQuery, boolean selectInitialQuery,
2357 Bundle appSearchData, boolean globalSearch) {
2358 if (appSearchData == null) {
2359 appSearchData = createGoogleSearchSourceBundle(
2360 GOOGLE_SEARCH_SOURCE_TYPE);
2361 }
2362
2363 SearchEngine searchEngine = mSettings.getSearchEngine();
2364 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2365 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2366 }
2367 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2368 globalSearch);
2369 }
2370
2371 private Bundle createGoogleSearchSourceBundle(String source) {
2372 Bundle bundle = new Bundle();
2373 bundle.putString(Search.SOURCE, source);
2374 return bundle;
2375 }
2376
2377 /**
2378 * handle key events in browser
2379 *
2380 * @param keyCode
2381 * @param event
2382 * @return true if handled, false to pass to super
2383 */
2384 boolean onKeyDown(int keyCode, KeyEvent event) {
2385 // Even if MENU is already held down, we need to call to super to open
2386 // the IME on long press.
2387 if (KeyEvent.KEYCODE_MENU == keyCode) {
2388 mMenuIsDown = true;
2389 return false;
2390 }
2391 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2392 // still down, we don't want to trigger the search. Pretend to consume
2393 // the key and do nothing.
2394 if (mMenuIsDown) return true;
2395
2396 switch(keyCode) {
2397 case KeyEvent.KEYCODE_SPACE:
2398 // WebView/WebTextView handle the keys in the KeyDown. As
2399 // the Activity's shortcut keys are only handled when WebView
2400 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2401 if (event.isShiftPressed()) {
2402 pageUp();
2403 } else {
2404 pageDown();
2405 }
2406 return true;
2407 case KeyEvent.KEYCODE_BACK:
2408 if (event.getRepeatCount() == 0) {
2409 event.startTracking();
2410 return true;
2411 } else if (mUi.showsWeb()
2412 && event.isLongPress()) {
2413 bookmarksOrHistoryPicker(true);
2414 return true;
2415 }
2416 break;
2417 }
2418 return false;
2419 }
2420
2421 boolean onKeyUp(int keyCode, KeyEvent event) {
2422 switch(keyCode) {
2423 case KeyEvent.KEYCODE_MENU:
2424 mMenuIsDown = false;
2425 break;
2426 case KeyEvent.KEYCODE_BACK:
2427 if (event.isTracking() && !event.isCanceled()) {
2428 onBackKey();
2429 return true;
2430 }
2431 break;
2432 }
2433 return false;
2434 }
2435
2436 public boolean isMenuDown() {
2437 return mMenuIsDown;
2438 }
2439
Ben Murdoch8029a772010-11-16 11:58:21 +00002440 public void setupAutoFill(Message message) {
2441 // Open the settings activity at the AutoFill profile fragment so that
2442 // the user can create a new profile. When they return, we will dispatch
2443 // the message so that we can autofill the form using their new profile.
2444 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
2445 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
2446 AutoFillSettingsFragment.class.getName());
2447 mAutoFillSetupMessage = message;
2448 mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
2449 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002450}