blob: 79fff3dca0992692424b8afdb107ddaf5e2423f9 [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);
1196
1197 // Setup custom handling depending on the type
1198 switch (type) {
1199 case WebView.HitTestResult.PHONE_TYPE:
1200 menu.setHeaderTitle(Uri.decode(extra));
1201 menu.findItem(R.id.dial_context_menu_id).setIntent(
1202 new Intent(Intent.ACTION_VIEW, Uri
1203 .parse(WebView.SCHEME_TEL + extra)));
1204 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1205 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1206 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1207 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1208 addIntent);
1209 menu.findItem(R.id.copy_phone_context_menu_id)
1210 .setOnMenuItemClickListener(
1211 new Copy(extra));
1212 break;
1213
1214 case WebView.HitTestResult.EMAIL_TYPE:
1215 menu.setHeaderTitle(extra);
1216 menu.findItem(R.id.email_context_menu_id).setIntent(
1217 new Intent(Intent.ACTION_VIEW, Uri
1218 .parse(WebView.SCHEME_MAILTO + extra)));
1219 menu.findItem(R.id.copy_mail_context_menu_id)
1220 .setOnMenuItemClickListener(
1221 new Copy(extra));
1222 break;
1223
1224 case WebView.HitTestResult.GEO_TYPE:
1225 menu.setHeaderTitle(extra);
1226 menu.findItem(R.id.map_context_menu_id).setIntent(
1227 new Intent(Intent.ACTION_VIEW, Uri
1228 .parse(WebView.SCHEME_GEO
1229 + URLEncoder.encode(extra))));
1230 menu.findItem(R.id.copy_geo_context_menu_id)
1231 .setOnMenuItemClickListener(
1232 new Copy(extra));
1233 break;
1234
1235 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1236 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1237 TextView titleView = (TextView) LayoutInflater.from(mActivity)
1238 .inflate(android.R.layout.browser_link_context_header,
1239 null);
1240 titleView.setText(extra);
1241 menu.setHeaderView(titleView);
1242 // decide whether to show the open link in new tab option
1243 boolean showNewTab = mTabControl.canCreateNewTab();
1244 MenuItem newTabItem
1245 = menu.findItem(R.id.open_newtab_context_menu_id);
1246 newTabItem.setVisible(showNewTab);
1247 if (showNewTab) {
1248 newTabItem.setOnMenuItemClickListener(
1249 new MenuItem.OnMenuItemClickListener() {
1250 public boolean onMenuItemClick(MenuItem item) {
1251 final Tab parent = mTabControl.getCurrentTab();
1252 final Tab newTab = openTab(extra, false);
1253 if (newTab != parent) {
1254 parent.addChildTab(newTab);
1255 }
1256 return true;
1257 }
1258 });
1259 }
1260 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1261 Bookmarks.urlHasAcceptableScheme(extra));
1262 PackageManager pm = mActivity.getPackageManager();
1263 Intent send = new Intent(Intent.ACTION_SEND);
1264 send.setType("text/plain");
1265 ResolveInfo ri = pm.resolveActivity(send,
1266 PackageManager.MATCH_DEFAULT_ONLY);
1267 menu.findItem(R.id.share_link_context_menu_id)
1268 .setVisible(ri != null);
1269 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1270 break;
1271 }
1272 // otherwise fall through to handle image part
1273 case WebView.HitTestResult.IMAGE_TYPE:
1274 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1275 menu.setHeaderTitle(extra);
1276 }
1277 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1278 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1279 menu.findItem(R.id.download_context_menu_id).
Leon Scroggins63c02662010-11-18 15:16:27 -05001280 setOnMenuItemClickListener(new Download(mActivity, extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001281 menu.findItem(R.id.set_wallpaper_context_menu_id).
1282 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1283 extra));
1284 break;
1285
1286 default:
1287 Log.w(LOGTAG, "We should not get here.");
1288 break;
1289 }
1290 //update the ui
1291 mUi.onContextMenuCreated(menu);
1292 }
1293
1294 /**
1295 * As the menu can be open when loading state changes
1296 * we must manually update the state of the stop/reload menu
1297 * item
1298 */
1299 private void updateInLoadMenuItems(Menu menu) {
1300 if (menu == null) {
1301 return;
1302 }
1303 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
1304 MenuItem src = mInLoad ?
1305 menu.findItem(R.id.stop_menu_id):
1306 menu.findItem(R.id.reload_menu_id);
1307 if (src != null) {
1308 dest.setIcon(src.getIcon());
1309 dest.setTitle(src.getTitle());
1310 }
1311 }
1312
1313 boolean prepareOptionsMenu(Menu menu) {
1314 // This happens when the user begins to hold down the menu key, so
1315 // allow them to chord to get a shortcut.
1316 mCanChord = true;
1317 // Note: setVisible will decide whether an item is visible; while
1318 // setEnabled() will decide whether an item is enabled, which also means
1319 // whether the matching shortcut key will function.
1320 switch (mMenuState) {
1321 case EMPTY_MENU:
1322 if (mCurrentMenuState != mMenuState) {
1323 menu.setGroupVisible(R.id.MAIN_MENU, false);
1324 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1325 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1326 }
1327 break;
1328 default:
1329 if (mCurrentMenuState != mMenuState) {
1330 menu.setGroupVisible(R.id.MAIN_MENU, true);
1331 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1332 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1333 }
1334 final WebView w = getCurrentTopWebView();
1335 boolean canGoBack = false;
1336 boolean canGoForward = false;
1337 boolean isHome = false;
1338 if (w != null) {
1339 canGoBack = w.canGoBack();
1340 canGoForward = w.canGoForward();
1341 isHome = mSettings.getHomePage().equals(w.getUrl());
1342 }
1343 final MenuItem back = menu.findItem(R.id.back_menu_id);
1344 back.setEnabled(canGoBack);
1345
1346 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1347 home.setEnabled(!isHome);
1348
1349 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1350 forward.setEnabled(canGoForward);
1351
1352 // decide whether to show the share link option
1353 PackageManager pm = mActivity.getPackageManager();
1354 Intent send = new Intent(Intent.ACTION_SEND);
1355 send.setType("text/plain");
1356 ResolveInfo ri = pm.resolveActivity(send,
1357 PackageManager.MATCH_DEFAULT_ONLY);
1358 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1359
1360 boolean isNavDump = mSettings.isNavDump();
1361 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1362 nav.setVisible(isNavDump);
1363 nav.setEnabled(isNavDump);
1364
1365 boolean showDebugSettings = mSettings.showDebugSettings();
1366 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1367 counter.setVisible(showDebugSettings);
1368 counter.setEnabled(showDebugSettings);
1369
1370 // allow the ui to adjust state based settings
1371 mUi.onPrepareOptionsMenu(menu);
1372
1373 break;
1374 }
1375 mCurrentMenuState = mMenuState;
1376 return true;
1377 }
1378
1379 public boolean onOptionsItemSelected(MenuItem item) {
1380 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1381 // menu remains active, so ensure comboview is dismissed
1382 // if main menu option is selected
1383 removeComboView();
1384 }
1385 // check the action bar button before mCanChord check, as the prepare call
1386 // doesn't come for action bar buttons
1387 if (item.getItemId() == R.id.newtab) {
1388 openTabToHomePage();
1389 return true;
1390 }
1391 if (!mCanChord) {
1392 // The user has already fired a shortcut with this hold down of the
1393 // menu key.
1394 return false;
1395 }
1396 if (null == getCurrentTopWebView()) {
1397 return false;
1398 }
1399 if (mMenuIsDown) {
1400 // The shortcut action consumes the MENU. Even if it is still down,
1401 // it won't trigger the next shortcut action. In the case of the
1402 // shortcut action triggering a new activity, like Bookmarks, we
1403 // won't get onKeyUp for MENU. So it is important to reset it here.
1404 mMenuIsDown = false;
1405 }
1406 switch (item.getItemId()) {
1407 // -- Main menu
1408 case R.id.new_tab_menu_id:
1409 openTabToHomePage();
1410 break;
1411
1412 case R.id.incognito_menu_id:
1413 openIncognitoTab();
1414 break;
1415
1416 case R.id.goto_menu_id:
1417 editUrl();
1418 break;
1419
1420 case R.id.bookmarks_menu_id:
1421 bookmarksOrHistoryPicker(false);
1422 break;
1423
1424 case R.id.active_tabs_menu_id:
1425 showActiveTabsPage();
1426 break;
1427
1428 case R.id.add_bookmark_menu_id:
1429 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
1430 break;
1431
1432 case R.id.stop_reload_menu_id:
1433 if (mInLoad) {
1434 stopLoading();
1435 } else {
1436 getCurrentTopWebView().reload();
1437 }
1438 break;
1439
1440 case R.id.back_menu_id:
1441 getCurrentTopWebView().goBack();
1442 break;
1443
1444 case R.id.forward_menu_id:
1445 getCurrentTopWebView().goForward();
1446 break;
1447
1448 case R.id.close_menu_id:
1449 // Close the subwindow if it exists.
1450 if (mTabControl.getCurrentSubWindow() != null) {
1451 dismissSubWindow(mTabControl.getCurrentTab());
1452 break;
1453 }
1454 closeCurrentTab();
1455 break;
1456
1457 case R.id.homepage_menu_id:
1458 Tab current = mTabControl.getCurrentTab();
1459 if (current != null) {
1460 dismissSubWindow(current);
1461 loadUrl(current.getWebView(), mSettings.getHomePage());
1462 }
1463 break;
1464
1465 case R.id.preferences_menu_id:
1466 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
1467 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1468 getCurrentTopWebView().getUrl());
1469 mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
1470 break;
1471
1472 case R.id.find_menu_id:
1473 getCurrentTopWebView().showFindDialog(null);
1474 break;
1475
1476 case R.id.page_info_menu_id:
1477 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
1478 false);
1479 break;
1480
1481 case R.id.classic_history_menu_id:
1482 bookmarksOrHistoryPicker(true);
1483 break;
1484
1485 case R.id.title_bar_share_page_url:
1486 case R.id.share_page_menu_id:
1487 Tab currentTab = mTabControl.getCurrentTab();
1488 if (null == currentTab) {
1489 mCanChord = false;
1490 return false;
1491 }
1492 currentTab.populatePickerData();
1493 sharePage(mActivity, currentTab.getTitle(),
1494 currentTab.getUrl(), currentTab.getFavicon(),
1495 createScreenshot(currentTab.getWebView(),
1496 getDesiredThumbnailWidth(mActivity),
1497 getDesiredThumbnailHeight(mActivity)));
1498 break;
1499
1500 case R.id.dump_nav_menu_id:
1501 getCurrentTopWebView().debugDump();
1502 break;
1503
1504 case R.id.dump_counters_menu_id:
1505 getCurrentTopWebView().dumpV8Counters();
1506 break;
1507
1508 case R.id.zoom_in_menu_id:
1509 getCurrentTopWebView().zoomIn();
1510 break;
1511
1512 case R.id.zoom_out_menu_id:
1513 getCurrentTopWebView().zoomOut();
1514 break;
1515
1516 case R.id.view_downloads_menu_id:
1517 viewDownloads();
1518 break;
1519
1520 case R.id.window_one_menu_id:
1521 case R.id.window_two_menu_id:
1522 case R.id.window_three_menu_id:
1523 case R.id.window_four_menu_id:
1524 case R.id.window_five_menu_id:
1525 case R.id.window_six_menu_id:
1526 case R.id.window_seven_menu_id:
1527 case R.id.window_eight_menu_id:
1528 {
1529 int menuid = item.getItemId();
1530 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1531 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1532 Tab desiredTab = mTabControl.getTab(id);
1533 if (desiredTab != null &&
1534 desiredTab != mTabControl.getCurrentTab()) {
1535 switchToTab(id);
1536 }
1537 break;
1538 }
1539 }
1540 }
1541 break;
1542
1543 default:
1544 return false;
1545 }
1546 mCanChord = false;
1547 return true;
1548 }
1549
1550 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08001551 // Let the History and Bookmark fragments handle menus they created.
1552 if (item.getGroupId() == R.id.CONTEXT_MENU) {
1553 return false;
1554 }
1555
Michael Kolb8233fac2010-10-26 16:08:53 -07001556 // chording is not an issue with context menus, but we use the same
1557 // options selector, so set mCanChord to true so we can access them.
1558 mCanChord = true;
1559 int id = item.getItemId();
1560 boolean result = true;
1561 switch (id) {
1562 // For the context menu from the title bar
1563 case R.id.title_bar_copy_page_url:
1564 Tab currentTab = mTabControl.getCurrentTab();
1565 if (null == currentTab) {
1566 result = false;
1567 break;
1568 }
1569 WebView mainView = currentTab.getWebView();
1570 if (null == mainView) {
1571 result = false;
1572 break;
1573 }
1574 copy(mainView.getUrl());
1575 break;
1576 // -- Browser context menu
1577 case R.id.open_context_menu_id:
1578 case R.id.bookmark_context_menu_id:
1579 case R.id.save_link_context_menu_id:
1580 case R.id.share_link_context_menu_id:
1581 case R.id.copy_link_context_menu_id:
1582 final WebView webView = getCurrentTopWebView();
1583 if (null == webView) {
1584 result = false;
1585 break;
1586 }
1587 final HashMap<String, WebView> hrefMap =
1588 new HashMap<String, WebView>();
1589 hrefMap.put("webview", webView);
1590 final Message msg = mHandler.obtainMessage(
1591 FOCUS_NODE_HREF, id, 0, hrefMap);
1592 webView.requestFocusNodeHref(msg);
1593 break;
1594
1595 default:
1596 // For other context menus
1597 result = onOptionsItemSelected(item);
1598 }
1599 mCanChord = false;
1600 return result;
1601 }
1602
1603 /**
1604 * support programmatically opening the context menu
1605 */
1606 public void openContextMenu(View view) {
1607 mActivity.openContextMenu(view);
1608 }
1609
1610 /**
1611 * programmatically open the options menu
1612 */
1613 public void openOptionsMenu() {
1614 mActivity.openOptionsMenu();
1615 }
1616
1617 public boolean onMenuOpened(int featureId, Menu menu) {
1618 if (mOptionsMenuOpen) {
1619 if (mConfigChanged) {
1620 // We do not need to make any changes to the state of the
1621 // title bar, since the only thing that happened was a
1622 // change in orientation
1623 mConfigChanged = false;
1624 } else {
1625 if (!mExtendedMenuOpen) {
1626 mExtendedMenuOpen = true;
1627 mUi.onExtendedMenuOpened();
1628 } else {
1629 // Switching the menu back to icon view, so show the
1630 // title bar once again.
1631 mExtendedMenuOpen = false;
1632 mUi.onExtendedMenuClosed(mInLoad);
1633 mUi.onOptionsMenuOpened();
1634 }
1635 }
1636 } else {
1637 // The options menu is closed, so open it, and show the title
1638 mOptionsMenuOpen = true;
1639 mConfigChanged = false;
1640 mExtendedMenuOpen = false;
1641 mUi.onOptionsMenuOpened();
1642 }
1643 return true;
1644 }
1645
1646 public void onOptionsMenuClosed(Menu menu) {
1647 mOptionsMenuOpen = false;
1648 mUi.onOptionsMenuClosed(mInLoad);
1649 }
1650
1651 public void onContextMenuClosed(Menu menu) {
1652 mUi.onContextMenuClosed(menu, mInLoad);
1653 }
1654
1655 // Helper method for getting the top window.
1656 @Override
1657 public WebView getCurrentTopWebView() {
1658 return mTabControl.getCurrentTopWebView();
1659 }
1660
1661 @Override
1662 public WebView getCurrentWebView() {
1663 return mTabControl.getCurrentWebView();
1664 }
1665
1666 /*
1667 * This method is called as a result of the user selecting the options
1668 * menu to see the download window. It shows the download window on top of
1669 * the current window.
1670 */
1671 void viewDownloads() {
1672 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1673 mActivity.startActivity(intent);
1674 }
1675
1676 // action mode
1677
1678 void onActionModeStarted(ActionMode mode) {
1679 mUi.onActionModeStarted(mode);
1680 mActionMode = mode;
1681 }
1682
1683 /*
1684 * True if a custom ActionMode (i.e. find or select) is in use.
1685 */
1686 @Override
1687 public boolean isInCustomActionMode() {
1688 return mActionMode != null;
1689 }
1690
1691 /*
1692 * End the current ActionMode.
1693 */
1694 @Override
1695 public void endActionMode() {
1696 if (mActionMode != null) {
1697 mActionMode.finish();
1698 }
1699 }
1700
1701 /*
1702 * Called by find and select when they are finished. Replace title bars
1703 * as necessary.
1704 */
1705 public void onActionModeFinished(ActionMode mode) {
1706 if (!isInCustomActionMode()) return;
1707 mUi.onActionModeFinished(mInLoad);
1708 mActionMode = null;
1709 }
1710
1711 boolean isInLoad() {
1712 return mInLoad;
1713 }
1714
1715 // bookmark handling
1716
1717 /**
1718 * add the current page as a bookmark to the given folder id
1719 * @param folderId use -1 for the default folder
1720 */
1721 @Override
1722 public void bookmarkCurrentPage(long folderId) {
1723 Intent i = new Intent(mActivity,
1724 AddBookmarkPage.class);
1725 WebView w = getCurrentTopWebView();
1726 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
1727 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
1728 String touchIconUrl = w.getTouchIconUrl();
1729 if (touchIconUrl != null) {
1730 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
1731 WebSettings settings = w.getSettings();
1732 if (settings != null) {
1733 i.putExtra(AddBookmarkPage.USER_AGENT,
1734 settings.getUserAgentString());
1735 }
1736 }
1737 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
1738 createScreenshot(w, getDesiredThumbnailWidth(mActivity),
1739 getDesiredThumbnailHeight(mActivity)));
1740 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
1741 i.putExtra(BrowserContract.Bookmarks.PARENT,
1742 folderId);
1743 // Put the dialog at the upper right of the screen, covering the
1744 // star on the title bar.
1745 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
1746 mActivity.startActivity(i);
1747 }
1748
1749 // file chooser
1750 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
1751 mUploadHandler = new UploadHandler(this);
1752 mUploadHandler.openFileChooser(uploadMsg, acceptType);
1753 }
1754
1755 // thumbnails
1756
1757 /**
1758 * Return the desired width 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 width for thumbnail screenshot.
1762 */
1763 static int getDesiredThumbnailWidth(Context context) {
1764 return context.getResources().getDimensionPixelOffset(
1765 R.dimen.bookmarkThumbnailWidth);
1766 }
1767
1768 /**
1769 * Return the desired height for thumbnail screenshots, which are stored in
1770 * the database, and used on the bookmarks screen.
1771 * @param context Context for finding out the density of the screen.
1772 * @return desired height for thumbnail screenshot.
1773 */
1774 static int getDesiredThumbnailHeight(Context context) {
1775 return context.getResources().getDimensionPixelOffset(
1776 R.dimen.bookmarkThumbnailHeight);
1777 }
1778
1779 private static Bitmap createScreenshot(WebView view, int width, int height) {
1780 Picture thumbnail = view.capturePicture();
1781 if (thumbnail == null) {
1782 return null;
1783 }
1784 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1785 Canvas canvas = new Canvas(bm);
1786 // May need to tweak these values to determine what is the
1787 // best scale factor
1788 int thumbnailWidth = thumbnail.getWidth();
1789 int thumbnailHeight = thumbnail.getHeight();
John Reckfe49ab42010-11-16 17:09:37 -08001790 float scaleFactor = 1.0f;
Michael Kolb8233fac2010-10-26 16:08:53 -07001791 if (thumbnailWidth > 0) {
John Reckfe49ab42010-11-16 17:09:37 -08001792 scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb8233fac2010-10-26 16:08:53 -07001793 } else {
1794 return null;
1795 }
John Reckfe49ab42010-11-16 17:09:37 -08001796
Michael Kolb8233fac2010-10-26 16:08:53 -07001797 if (view.getWidth() > view.getHeight() &&
1798 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
1799 // If the device is in landscape and the page is shorter
John Reckfe49ab42010-11-16 17:09:37 -08001800 // than the height of the view, center the thumnail and crop the sides
1801 scaleFactor = (float) height / (float)thumbnailHeight;
1802 float wx = (thumbnailWidth * scaleFactor) - width;
1803 canvas.translate((int) -(wx / 2), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -07001804 }
1805
John Reckfe49ab42010-11-16 17:09:37 -08001806 canvas.scale(scaleFactor, scaleFactor);
Michael Kolb8233fac2010-10-26 16:08:53 -07001807
1808 thumbnail.draw(canvas);
1809 return bm;
1810 }
1811
1812 private void updateScreenshot(WebView view) {
1813 // If this is a bookmarked site, add a screenshot to the database.
1814 // FIXME: When should we update? Every time?
1815 // FIXME: Would like to make sure there is actually something to
1816 // draw, but the API for that (WebViewCore.pictureReady()) is not
1817 // currently accessible here.
1818
1819 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
1820 getDesiredThumbnailHeight(mActivity));
1821 if (bm == null) {
1822 return;
1823 }
1824
1825 final ContentResolver cr = mActivity.getContentResolver();
1826 final String url = view.getUrl();
1827 final String originalUrl = view.getOriginalUrl();
1828
1829 new AsyncTask<Void, Void, Void>() {
1830 @Override
1831 protected Void doInBackground(Void... unused) {
1832 Cursor cursor = null;
1833 try {
1834 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
1835 if (cursor != null && cursor.moveToFirst()) {
1836 final ByteArrayOutputStream os =
1837 new ByteArrayOutputStream();
1838 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
1839
1840 ContentValues values = new ContentValues();
1841 values.put(Images.THUMBNAIL, os.toByteArray());
1842 values.put(Images.URL, cursor.getString(0));
1843
1844 do {
1845 cr.update(Images.CONTENT_URI, values, null, null);
1846 } while (cursor.moveToNext());
1847 }
1848 } catch (IllegalStateException e) {
1849 // Ignore
1850 } finally {
1851 if (cursor != null) cursor.close();
1852 }
1853 return null;
1854 }
1855 }.execute();
1856 }
1857
1858 private class Copy implements OnMenuItemClickListener {
1859 private CharSequence mText;
1860
1861 public boolean onMenuItemClick(MenuItem item) {
1862 copy(mText);
1863 return true;
1864 }
1865
1866 public Copy(CharSequence toCopy) {
1867 mText = toCopy;
1868 }
1869 }
1870
Leon Scroggins63c02662010-11-18 15:16:27 -05001871 private static class Download implements OnMenuItemClickListener {
1872 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001873 private String mText;
1874
1875 public boolean onMenuItemClick(MenuItem item) {
Leon Scroggins63c02662010-11-18 15:16:27 -05001876 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
1877 null, null);
Michael Kolb8233fac2010-10-26 16:08:53 -07001878 return true;
1879 }
1880
Leon Scroggins63c02662010-11-18 15:16:27 -05001881 public Download(Activity activity, String toDownload) {
1882 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07001883 mText = toDownload;
1884 }
1885 }
1886
1887 /********************** TODO: UI stuff *****************************/
1888
1889 // these methods have been copied, they still need to be cleaned up
1890
1891 /****************** tabs ***************************************************/
1892
1893 // basic tab interactions:
1894
1895 // it is assumed that tabcontrol already knows about the tab
1896 protected void addTab(Tab tab) {
1897 mUi.addTab(tab);
1898 }
1899
1900 protected void removeTab(Tab tab) {
1901 mUi.removeTab(tab);
1902 mTabControl.removeTab(tab);
1903 }
1904
1905 protected void setActiveTab(Tab tab) {
1906 // Update the UI before setting the current tab in TabControl
1907 // so the UI can access the old tab to switch over from
1908 mUi.setActiveTab(tab);
1909 mTabControl.setCurrentTab(tab);
1910 }
1911
1912 protected void closeEmptyChildTab() {
1913 Tab current = mTabControl.getCurrentTab();
1914 if (current != null
1915 && current.getWebView().copyBackForwardList().getSize() == 0) {
1916 Tab parent = current.getParentTab();
1917 if (parent != null) {
1918 switchToTab(mTabControl.getTabIndex(parent));
1919 closeTab(current);
1920 }
1921 }
1922 }
1923
1924 protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
1925 Log.i(LOGTAG, "Reusing tab for " + appId);
1926 // Dismiss the subwindow if applicable.
1927 dismissSubWindow(appTab);
1928 // Since we might kill the WebView, remove it from the
1929 // content view first.
1930 mUi.detachTab(appTab);
1931 // Recreate the main WebView after destroying the old one.
1932 // If the WebView has the same original url and is on that
1933 // page, it can be reused.
1934 boolean needsLoad =
1935 mTabControl.recreateWebView(appTab, urlData);
1936 // TODO: analyze why the remove and add are necessary
1937 mUi.attachTab(appTab);
1938 if (mTabControl.getCurrentTab() != appTab) {
1939 switchToTab(mTabControl.getTabIndex(appTab));
1940 if (needsLoad) {
1941 loadUrlDataIn(appTab, urlData);
1942 }
1943 } else {
1944 // If the tab was the current tab, we have to attach
1945 // it to the view system again.
1946 setActiveTab(appTab);
1947 if (needsLoad) {
1948 loadUrlDataIn(appTab, urlData);
1949 }
1950 }
1951 }
1952
1953 // Remove the sub window if it exists. Also called by TabControl when the
1954 // user clicks the 'X' to dismiss a sub window.
1955 public void dismissSubWindow(Tab tab) {
1956 removeSubWindow(tab);
1957 // dismiss the subwindow. This will destroy the WebView.
1958 tab.dismissSubWindow();
1959 getCurrentTopWebView().requestFocus();
1960 }
1961
1962 @Override
1963 public void removeSubWindow(Tab t) {
1964 if (t.getSubWebView() != null) {
1965 mUi.removeSubWindow(t.getSubViewContainer());
1966 }
1967 }
1968
1969 @Override
1970 public void attachSubWindow(Tab tab) {
1971 if (tab.getSubWebView() != null) {
1972 mUi.attachSubWindow(tab.getSubViewContainer());
1973 getCurrentTopWebView().requestFocus();
1974 }
1975 }
1976
1977 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
1978 // that accepts url as string.
1979
1980 protected Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
1981 return openTabAndShow(new UrlData(url), closeOnExit, appId);
1982 }
1983
1984 // This method does a ton of stuff. It will attempt to create a new tab
1985 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1986 // url isn't null, it will load the given url.
1987
1988 public Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1989 String appId) {
1990 final Tab currentTab = mTabControl.getCurrentTab();
1991 if (mTabControl.canCreateNewTab()) {
1992 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1993 urlData.mUrl, false);
1994 WebView webview = tab.getWebView();
1995 // We must set the new tab as the current tab to reflect the old
1996 // animation behavior.
1997 addTab(tab);
1998 setActiveTab(tab);
1999 if (!urlData.isEmpty()) {
2000 loadUrlDataIn(tab, urlData);
2001 }
2002 return tab;
2003 } else {
2004 // Get rid of the subwindow if it exists
2005 dismissSubWindow(currentTab);
2006 if (!urlData.isEmpty()) {
2007 // Load the given url.
2008 loadUrlDataIn(currentTab, urlData);
2009 }
2010 return currentTab;
2011 }
2012 }
2013
2014 protected Tab openTab(String url, boolean forceForeground) {
2015 if (mSettings.openInBackground() && !forceForeground) {
2016 Tab tab = mTabControl.createNewTab();
2017 if (tab != null) {
2018 addTab(tab);
2019 WebView view = tab.getWebView();
2020 loadUrl(view, url);
2021 }
2022 return tab;
2023 } else {
2024 return openTabAndShow(url, false, null);
2025 }
2026 }
2027
2028 @Override
2029 public Tab openIncognitoTab() {
2030 if (mTabControl.canCreateNewTab()) {
2031 Tab currentTab = mTabControl.getCurrentTab();
2032 Tab tab = mTabControl.createNewTab(false, null, null, true);
2033 addTab(tab);
2034 setActiveTab(tab);
2035 return tab;
2036 }
2037 return null;
2038 }
2039
2040 /**
2041 * @param index Index of the tab to change to, as defined by
2042 * mTabControl.getTabIndex(Tab t).
2043 * @return boolean True if we successfully switched to a different tab. If
2044 * the indexth tab is null, or if that tab is the same as
2045 * the current one, return false.
2046 */
2047 @Override
2048 public boolean switchToTab(int index) {
2049 Tab tab = mTabControl.getTab(index);
2050 Tab currentTab = mTabControl.getCurrentTab();
2051 if (tab == null || tab == currentTab) {
2052 return false;
2053 }
2054 setActiveTab(tab);
2055 return true;
2056 }
2057
2058 @Override
2059 public Tab openTabToHomePage() {
2060 return openTabAndShow(mSettings.getHomePage(), false, null);
2061 }
2062
2063 @Override
2064 public void closeCurrentTab() {
2065 final Tab current = mTabControl.getCurrentTab();
2066 if (mTabControl.getTabCount() == 1) {
2067 // This is the last tab. Open a new one, with the home
2068 // page and close the current one.
2069 openTabToHomePage();
2070 closeTab(current);
2071 return;
2072 }
2073 final Tab parent = current.getParentTab();
2074 int indexToShow = -1;
2075 if (parent != null) {
2076 indexToShow = mTabControl.getTabIndex(parent);
2077 } else {
2078 final int currentIndex = mTabControl.getCurrentIndex();
2079 // Try to move to the tab to the right
2080 indexToShow = currentIndex + 1;
2081 if (indexToShow > mTabControl.getTabCount() - 1) {
2082 // Try to move to the tab to the left
2083 indexToShow = currentIndex - 1;
2084 }
2085 }
2086 if (switchToTab(indexToShow)) {
2087 // Close window
2088 closeTab(current);
2089 }
2090 }
2091
2092 /**
2093 * Close the tab, remove its associated title bar, and adjust mTabControl's
2094 * current tab to a valid value.
2095 */
2096 @Override
2097 public void closeTab(Tab tab) {
2098 int currentIndex = mTabControl.getCurrentIndex();
2099 int removeIndex = mTabControl.getTabIndex(tab);
2100 removeTab(tab);
2101 if (currentIndex >= removeIndex && currentIndex != 0) {
2102 currentIndex--;
2103 }
2104 Tab newtab = mTabControl.getTab(currentIndex);
2105 setActiveTab(newtab);
2106 if (!mTabControl.hasAnyOpenIncognitoTabs()) {
2107 WebView.cleanupPrivateBrowsingFiles(mActivity);
2108 }
2109 }
2110
2111 /**************** TODO: Url loading clean up *******************************/
2112
2113 // Called when loading from context menu or LOAD_URL message
2114 protected void loadUrlFromContext(WebView view, String url) {
2115 // In case the user enters nothing.
2116 if (url != null && url.length() != 0 && view != null) {
2117 url = UrlUtils.smartUrlFilter(url);
2118 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
2119 loadUrl(view, url);
2120 }
2121 }
2122 }
2123
2124 /**
2125 * Load the URL into the given WebView and update the title bar
2126 * to reflect the new load. Call this instead of WebView.loadUrl
2127 * directly.
2128 * @param view The WebView used to load url.
2129 * @param url The URL to load.
2130 */
2131 protected void loadUrl(WebView view, String url) {
2132 updateTitleBarForNewLoad(view, url);
2133 view.loadUrl(url);
2134 }
2135
2136 /**
2137 * Load UrlData into a Tab and update the title bar to reflect the new
2138 * load. Call this instead of UrlData.loadIn directly.
2139 * @param t The Tab used to load.
2140 * @param data The UrlData being loaded.
2141 */
2142 protected void loadUrlDataIn(Tab t, UrlData data) {
2143 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
2144 data.loadIn(t);
2145 }
2146
2147 /**
2148 * Resets the browser title-view to whatever it must be
2149 * (for example, if we had a loading error)
2150 * When we have a new page, we call resetTitle, when we
2151 * have to reset the titlebar to whatever it used to be
2152 * (for example, if the user chose to stop loading), we
2153 * call resetTitleAndRevertLockIcon.
2154 */
2155 public void resetTitleAndRevertLockIcon(Tab tab) {
2156 mUi.resetTitleAndRevertLockIcon(tab);
2157 }
2158
2159 void resetTitleAndIcon(Tab tab) {
2160 mUi.resetTitleAndIcon(tab);
2161 }
2162
2163 /**
2164 * If the WebView is the top window, update the title bar to reflect
2165 * loading the new URL. i.e. set its text, clear the favicon (which
2166 * will be set once the page begins loading), and set the progress to
2167 * INITIAL_PROGRESS to show that the page has begun to load. Called
2168 * by loadUrl and loadUrlDataIn.
2169 * @param view The WebView that is starting a load.
2170 * @param url The URL that is being loaded.
2171 */
2172 private void updateTitleBarForNewLoad(WebView view, String url) {
2173 if (view == getCurrentTopWebView()) {
2174 // TODO we should come with a tab and not with a view
2175 Tab tab = mTabControl.getTabFromView(view);
2176 setUrlTitle(tab, url, null);
2177 mUi.setFavicon(tab, null);
2178 onProgressChanged(tab, INITIAL_PROGRESS);
2179 }
2180 }
2181
2182 /**
2183 * Sets a title composed of the URL and the title string.
2184 * @param url The URL of the site being loaded.
2185 * @param title The title of the site being loaded.
2186 */
2187 void setUrlTitle(Tab tab, String url, String title) {
2188 tab.setCurrentUrl(url);
2189 tab.setCurrentTitle(title);
2190 // If we are in voice search mode, the title has already been set.
2191 if (tab.isInVoiceSearchMode()) return;
2192 mUi.setUrlTitle(tab, url, title);
2193 }
2194
2195 void goBackOnePageOrQuit() {
2196 Tab current = mTabControl.getCurrentTab();
2197 if (current == null) {
2198 /*
2199 * Instead of finishing the activity, simply push this to the back
2200 * of the stack and let ActivityManager to choose the foreground
2201 * activity. As BrowserActivity is singleTask, it will be always the
2202 * root of the task. So we can use either true or false for
2203 * moveTaskToBack().
2204 */
2205 mActivity.moveTaskToBack(true);
2206 return;
2207 }
2208 WebView w = current.getWebView();
2209 if (w.canGoBack()) {
2210 w.goBack();
2211 } else {
2212 // Check to see if we are closing a window that was created by
2213 // another window. If so, we switch back to that window.
2214 Tab parent = current.getParentTab();
2215 if (parent != null) {
2216 switchToTab(mTabControl.getTabIndex(parent));
2217 // Now we close the other tab
2218 closeTab(current);
2219 } else {
2220 if (current.closeOnExit()) {
2221 // force the tab's inLoad() to be false as we are going to
2222 // either finish the activity or remove the tab. This will
2223 // ensure pauseWebViewTimers() taking action.
2224 mTabControl.getCurrentTab().clearInPageLoad();
2225 if (mTabControl.getTabCount() == 1) {
2226 mActivity.finish();
2227 return;
2228 }
2229 if (mActivityPaused) {
2230 Log.e(LOGTAG, "BrowserActivity is already paused "
2231 + "while handing goBackOnePageOrQuit.");
2232 }
2233 pauseWebViewTimers(true);
2234 removeTab(current);
2235 }
2236 /*
2237 * Instead of finishing the activity, simply push this to the back
2238 * of the stack and let ActivityManager to choose the foreground
2239 * activity. As BrowserActivity is singleTask, it will be always the
2240 * root of the task. So we can use either true or false for
2241 * moveTaskToBack().
2242 */
2243 mActivity.moveTaskToBack(true);
2244 }
2245 }
2246 }
2247
2248 /**
2249 * Feed the previously stored results strings to the BrowserProvider so that
2250 * the SearchDialog will show them instead of the standard searches.
2251 * @param result String to show on the editable line of the SearchDialog.
2252 */
2253 @Override
2254 public void showVoiceSearchResults(String result) {
2255 ContentProviderClient client = mActivity.getContentResolver()
2256 .acquireContentProviderClient(Browser.BOOKMARKS_URI);
2257 ContentProvider prov = client.getLocalContentProvider();
2258 BrowserProvider bp = (BrowserProvider) prov;
2259 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
2260 client.release();
2261
2262 Bundle bundle = createGoogleSearchSourceBundle(
2263 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
2264 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
2265 startSearch(result, false, bundle, false);
2266 }
2267
2268 private void startSearch(String initialQuery, boolean selectInitialQuery,
2269 Bundle appSearchData, boolean globalSearch) {
2270 if (appSearchData == null) {
2271 appSearchData = createGoogleSearchSourceBundle(
2272 GOOGLE_SEARCH_SOURCE_TYPE);
2273 }
2274
2275 SearchEngine searchEngine = mSettings.getSearchEngine();
2276 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
2277 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
2278 }
2279 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
2280 globalSearch);
2281 }
2282
2283 private Bundle createGoogleSearchSourceBundle(String source) {
2284 Bundle bundle = new Bundle();
2285 bundle.putString(Search.SOURCE, source);
2286 return bundle;
2287 }
2288
2289 /**
2290 * handle key events in browser
2291 *
2292 * @param keyCode
2293 * @param event
2294 * @return true if handled, false to pass to super
2295 */
2296 boolean onKeyDown(int keyCode, KeyEvent event) {
2297 // Even if MENU is already held down, we need to call to super to open
2298 // the IME on long press.
2299 if (KeyEvent.KEYCODE_MENU == keyCode) {
2300 mMenuIsDown = true;
2301 return false;
2302 }
2303 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2304 // still down, we don't want to trigger the search. Pretend to consume
2305 // the key and do nothing.
2306 if (mMenuIsDown) return true;
2307
2308 switch(keyCode) {
2309 case KeyEvent.KEYCODE_SPACE:
2310 // WebView/WebTextView handle the keys in the KeyDown. As
2311 // the Activity's shortcut keys are only handled when WebView
2312 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2313 if (event.isShiftPressed()) {
2314 pageUp();
2315 } else {
2316 pageDown();
2317 }
2318 return true;
2319 case KeyEvent.KEYCODE_BACK:
2320 if (event.getRepeatCount() == 0) {
2321 event.startTracking();
2322 return true;
2323 } else if (mUi.showsWeb()
2324 && event.isLongPress()) {
2325 bookmarksOrHistoryPicker(true);
2326 return true;
2327 }
2328 break;
2329 }
2330 return false;
2331 }
2332
2333 boolean onKeyUp(int keyCode, KeyEvent event) {
2334 switch(keyCode) {
2335 case KeyEvent.KEYCODE_MENU:
2336 mMenuIsDown = false;
2337 break;
2338 case KeyEvent.KEYCODE_BACK:
2339 if (event.isTracking() && !event.isCanceled()) {
2340 onBackKey();
2341 return true;
2342 }
2343 break;
2344 }
2345 return false;
2346 }
2347
2348 public boolean isMenuDown() {
2349 return mMenuIsDown;
2350 }
2351
2352}