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