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