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