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