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