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