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