BrowserActivity.java revision f450cd0d744da48a5bdd9cdb6cc23a2df8b31db4
1/* 2 * Copyright (C) 2006 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.google.android.googleapps.IGoogleLoginService; 20import com.google.android.googlelogin.GoogleLoginServiceConstants; 21 22import android.app.Activity; 23import android.app.ActivityManager; 24import android.app.AlertDialog; 25import android.app.ProgressDialog; 26import android.app.SearchManager; 27import android.content.ActivityNotFoundException; 28import android.content.BroadcastReceiver; 29import android.content.ComponentName; 30import android.content.ContentResolver; 31import android.content.ContentUris; 32import android.content.ContentValues; 33import android.content.Context; 34import android.content.DialogInterface; 35import android.content.Intent; 36import android.content.IntentFilter; 37import android.content.ServiceConnection; 38import android.content.DialogInterface.OnCancelListener; 39import android.content.pm.PackageInfo; 40import android.content.pm.PackageManager; 41import android.content.pm.ResolveInfo; 42import android.content.res.AssetManager; 43import android.content.res.Configuration; 44import android.content.res.Resources; 45import android.database.Cursor; 46import android.database.sqlite.SQLiteDatabase; 47import android.database.sqlite.SQLiteException; 48import android.graphics.Bitmap; 49import android.graphics.Canvas; 50import android.graphics.Color; 51import android.graphics.DrawFilter; 52import android.graphics.Paint; 53import android.graphics.PaintFlagsDrawFilter; 54import android.graphics.Picture; 55import android.graphics.drawable.BitmapDrawable; 56import android.graphics.drawable.Drawable; 57import android.graphics.drawable.LayerDrawable; 58import android.graphics.drawable.PaintDrawable; 59import android.hardware.SensorListener; 60import android.hardware.SensorManager; 61import android.net.ConnectivityManager; 62import android.net.Uri; 63import android.net.WebAddress; 64import android.net.http.EventHandler; 65import android.net.http.SslCertificate; 66import android.net.http.SslError; 67import android.os.AsyncTask; 68import android.os.Bundle; 69import android.os.Debug; 70import android.os.Environment; 71import android.os.Handler; 72import android.os.IBinder; 73import android.os.Message; 74import android.os.PowerManager; 75import android.os.Process; 76import android.os.RemoteException; 77import android.os.ServiceManager; 78import android.os.SystemClock; 79import android.provider.Browser; 80import android.provider.Contacts; 81import android.provider.Downloads; 82import android.provider.MediaStore; 83import android.provider.Contacts.Intents.Insert; 84import android.text.IClipboard; 85import android.text.TextUtils; 86import android.text.format.DateFormat; 87import android.text.util.Regex; 88import android.util.Log; 89import android.view.ContextMenu; 90import android.view.Gravity; 91import android.view.KeyEvent; 92import android.view.LayoutInflater; 93import android.view.Menu; 94import android.view.MenuInflater; 95import android.view.MenuItem; 96import android.view.View; 97import android.view.ViewGroup; 98import android.view.Window; 99import android.view.WindowManager; 100import android.view.ContextMenu.ContextMenuInfo; 101import android.view.MenuItem.OnMenuItemClickListener; 102import android.view.animation.AlphaAnimation; 103import android.view.animation.Animation; 104import android.view.animation.AnimationSet; 105import android.view.animation.DecelerateInterpolator; 106import android.view.animation.ScaleAnimation; 107import android.view.animation.TranslateAnimation; 108import android.webkit.CookieManager; 109import android.webkit.CookieSyncManager; 110import android.webkit.DownloadListener; 111import android.webkit.HttpAuthHandler; 112import android.webkit.PluginManager; 113import android.webkit.SslErrorHandler; 114import android.webkit.URLUtil; 115import android.webkit.WebChromeClient; 116import android.webkit.WebChromeClient.CustomViewCallback; 117import android.webkit.WebHistoryItem; 118import android.webkit.WebIconDatabase; 119import android.webkit.WebStorage; 120import android.webkit.WebView; 121import android.webkit.WebViewClient; 122import android.widget.EditText; 123import android.widget.FrameLayout; 124import android.widget.LinearLayout; 125import android.widget.TextView; 126import android.widget.Toast; 127 128import java.io.BufferedOutputStream; 129import java.io.ByteArrayOutputStream; 130import java.io.File; 131import java.io.FileInputStream; 132import java.io.FileOutputStream; 133import java.io.IOException; 134import java.io.InputStream; 135import java.net.MalformedURLException; 136import java.net.URI; 137import java.net.URISyntaxException; 138import java.net.URL; 139import java.net.URLEncoder; 140import java.text.ParseException; 141import java.util.Date; 142import java.util.Enumeration; 143import java.util.HashMap; 144import java.util.LinkedList; 145import java.util.Vector; 146import java.util.regex.Matcher; 147import java.util.regex.Pattern; 148import java.util.zip.ZipEntry; 149import java.util.zip.ZipFile; 150 151public class BrowserActivity extends Activity 152 implements KeyTracker.OnKeyTracker, 153 View.OnCreateContextMenuListener, 154 DownloadListener { 155 156 /* Define some aliases to make these debugging flags easier to refer to. 157 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG". 158 */ 159 private final static boolean DEBUG = com.android.browser.Browser.DEBUG; 160 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED; 161 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED; 162 163 private IGoogleLoginService mGls = null; 164 private ServiceConnection mGlsConnection = null; 165 166 private SensorManager mSensorManager = null; 167 168 private WebStorage.QuotaUpdater mWebStorageQuotaUpdater = null; 169 170 // These are single-character shortcuts for searching popular sources. 171 private static final int SHORTCUT_INVALID = 0; 172 private static final int SHORTCUT_GOOGLE_SEARCH = 1; 173 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2; 174 private static final int SHORTCUT_DICTIONARY_SEARCH = 3; 175 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4; 176 177 /* Whitelisted webpages 178 private static HashSet<String> sWhiteList; 179 180 static { 181 sWhiteList = new HashSet<String>(); 182 sWhiteList.add("cnn.com/"); 183 sWhiteList.add("espn.go.com/"); 184 sWhiteList.add("nytimes.com/"); 185 sWhiteList.add("engadget.com/"); 186 sWhiteList.add("yahoo.com/"); 187 sWhiteList.add("msn.com/"); 188 sWhiteList.add("amazon.com/"); 189 sWhiteList.add("consumerist.com/"); 190 sWhiteList.add("google.com/m/news"); 191 } 192 */ 193 194 private void setupHomePage() { 195 final Runnable getAccount = new Runnable() { 196 public void run() { 197 // Lower priority 198 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 199 // get the default home page 200 String homepage = mSettings.getHomePage(); 201 202 try { 203 if (mGls == null) return; 204 205 if (!homepage.startsWith("http://www.google.")) return; 206 if (homepage.indexOf('?') == -1) return; 207 208 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED); 209 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE); 210 211 // three cases: 212 // 213 // hostedUser == googleUser 214 // The device has only a google account 215 // 216 // hostedUser != googleUser 217 // The device has a hosted account and a google account 218 // 219 // hostedUser != null, googleUser == null 220 // The device has only a hosted account (so far) 221 222 // developers might have no accounts at all 223 if (hostedUser == null) return; 224 225 if (googleUser == null || !hostedUser.equals(googleUser)) { 226 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1); 227 homepage = homepage.replace("?", "/a/" + domain + "?"); 228 } 229 } catch (RemoteException ignore) { 230 // Login service died; carry on 231 } catch (RuntimeException ignore) { 232 // Login service died; carry on 233 } finally { 234 finish(homepage); 235 } 236 } 237 238 private void finish(final String homepage) { 239 mHandler.post(new Runnable() { 240 public void run() { 241 mSettings.setHomePage(BrowserActivity.this, homepage); 242 resumeAfterCredentials(); 243 244 // as this is running in a separate thread, 245 // BrowserActivity's onDestroy() may have been called, 246 // which also calls unbindService(). 247 if (mGlsConnection != null) { 248 // we no longer need to keep GLS open 249 unbindService(mGlsConnection); 250 mGlsConnection = null; 251 } 252 } }); 253 } }; 254 255 final boolean[] done = { false }; 256 257 // Open a connection to the Google Login Service. The first 258 // time the connection is established, set up the homepage depending on 259 // the account in a background thread. 260 mGlsConnection = new ServiceConnection() { 261 public void onServiceConnected(ComponentName className, IBinder service) { 262 mGls = IGoogleLoginService.Stub.asInterface(service); 263 if (done[0] == false) { 264 done[0] = true; 265 Thread account = new Thread(getAccount); 266 account.setName("GLSAccount"); 267 account.start(); 268 } 269 } 270 public void onServiceDisconnected(ComponentName className) { 271 mGls = null; 272 } 273 }; 274 275 bindService(GoogleLoginServiceConstants.SERVICE_INTENT, 276 mGlsConnection, Context.BIND_AUTO_CREATE); 277 } 278 279 /** 280 * This class is in charge of installing pre-packaged plugins 281 * from the Browser assets directory to the user's data partition. 282 * Plugins are loaded from the "plugins" directory in the assets; 283 * Anything that is in this directory will be copied over to the 284 * user data partition in app_plugins. 285 */ 286 private class CopyPlugins implements Runnable { 287 final static String TAG = "PluginsInstaller"; 288 final static String ZIP_FILTER = "assets/plugins/"; 289 final static String APK_PATH = "/system/app/Browser.apk"; 290 final static String PLUGIN_EXTENSION = ".so"; 291 final static String TEMPORARY_EXTENSION = "_temp"; 292 final static String BUILD_INFOS_FILE = "build.prop"; 293 final static String SYSTEM_BUILD_INFOS_FILE = "/system/" 294 + BUILD_INFOS_FILE; 295 final int BUFSIZE = 4096; 296 boolean mDoOverwrite = false; 297 String pluginsPath; 298 Context mContext; 299 File pluginsDir; 300 AssetManager manager; 301 302 public CopyPlugins (boolean overwrite, Context context) { 303 mDoOverwrite = overwrite; 304 mContext = context; 305 } 306 307 /** 308 * Returned a filtered list of ZipEntry. 309 * We list all the files contained in the zip and 310 * only returns the ones starting with the ZIP_FILTER 311 * path. 312 * 313 * @param zip the zip file used. 314 */ 315 public Vector<ZipEntry> pluginsFilesFromZip(ZipFile zip) { 316 Vector<ZipEntry> list = new Vector<ZipEntry>(); 317 Enumeration entries = zip.entries(); 318 while (entries.hasMoreElements()) { 319 ZipEntry entry = (ZipEntry) entries.nextElement(); 320 if (entry.getName().startsWith(ZIP_FILTER)) { 321 list.add(entry); 322 } 323 } 324 return list; 325 } 326 327 /** 328 * Utility method to copy the content from an inputstream 329 * to a file output stream. 330 */ 331 public void copyStreams(InputStream is, FileOutputStream fos) { 332 BufferedOutputStream os = null; 333 try { 334 byte data[] = new byte[BUFSIZE]; 335 int count; 336 os = new BufferedOutputStream(fos, BUFSIZE); 337 while ((count = is.read(data, 0, BUFSIZE)) != -1) { 338 os.write(data, 0, count); 339 } 340 os.flush(); 341 } catch (IOException e) { 342 Log.e(TAG, "Exception while copying: " + e); 343 } finally { 344 try { 345 if (os != null) { 346 os.close(); 347 } 348 } catch (IOException e2) { 349 Log.e(TAG, "Exception while closing the stream: " + e2); 350 } 351 } 352 } 353 354 /** 355 * Returns a string containing the contents of a file 356 * 357 * @param file the target file 358 */ 359 private String contentsOfFile(File file) { 360 String ret = null; 361 FileInputStream is = null; 362 try { 363 byte[] buffer = new byte[BUFSIZE]; 364 int count; 365 is = new FileInputStream(file); 366 StringBuffer out = new StringBuffer(); 367 368 while ((count = is.read(buffer, 0, BUFSIZE)) != -1) { 369 out.append(new String(buffer, 0, count)); 370 } 371 ret = out.toString(); 372 } catch (IOException e) { 373 Log.e(TAG, "Exception getting contents of file " + e); 374 } finally { 375 if (is != null) { 376 try { 377 is.close(); 378 } catch (IOException e2) { 379 Log.e(TAG, "Exception while closing the file: " + e2); 380 } 381 } 382 } 383 return ret; 384 } 385 386 /** 387 * Utility method to initialize the user data plugins path. 388 */ 389 public void initPluginsPath() { 390 BrowserSettings s = BrowserSettings.getInstance(); 391 pluginsPath = s.getPluginsPath(); 392 if (pluginsPath == null) { 393 s.loadFromDb(mContext); 394 pluginsPath = s.getPluginsPath(); 395 } 396 if (LOGV_ENABLED) { 397 Log.v(TAG, "Plugin path: " + pluginsPath); 398 } 399 } 400 401 /** 402 * Utility method to delete a file or a directory 403 * 404 * @param file the File to delete 405 */ 406 public void deleteFile(File file) { 407 File[] files = file.listFiles(); 408 if ((files != null) && files.length > 0) { 409 for (int i=0; i< files.length; i++) { 410 deleteFile(files[i]); 411 } 412 } 413 if (!file.delete()) { 414 Log.e(TAG, file.getPath() + " could not get deleted"); 415 } 416 } 417 418 /** 419 * Clean the content of the plugins directory. 420 * We delete the directory, then recreate it. 421 */ 422 public void cleanPluginsDirectory() { 423 if (LOGV_ENABLED) { 424 Log.v(TAG, "delete plugins directory: " + pluginsPath); 425 } 426 File pluginsDirectory = new File(pluginsPath); 427 deleteFile(pluginsDirectory); 428 pluginsDirectory.mkdir(); 429 } 430 431 432 /** 433 * Copy the SYSTEM_BUILD_INFOS_FILE file containing the 434 * informations about the system build to the 435 * BUILD_INFOS_FILE in the plugins directory. 436 */ 437 public void copyBuildInfos() { 438 try { 439 if (LOGV_ENABLED) { 440 Log.v(TAG, "Copy build infos to the plugins directory"); 441 } 442 File buildInfoFile = new File(SYSTEM_BUILD_INFOS_FILE); 443 File buildInfoPlugins = new File(pluginsPath, BUILD_INFOS_FILE); 444 copyStreams(new FileInputStream(buildInfoFile), 445 new FileOutputStream(buildInfoPlugins)); 446 } catch (IOException e) { 447 Log.e(TAG, "Exception while copying the build infos: " + e); 448 } 449 } 450 451 /** 452 * Returns true if the current system is newer than the 453 * system that installed the plugins. 454 * We determinate this by checking the build number of the system. 455 * 456 * At the end of the plugins copy operation, we copy the 457 * SYSTEM_BUILD_INFOS_FILE to the BUILD_INFOS_FILE. 458 * We then just have to load both and compare them -- if they 459 * are different the current system is newer. 460 * 461 * Loading and comparing the strings should be faster than 462 * creating a hash, the files being rather small. Extracting the 463 * version number would require some parsing which may be more 464 * brittle. 465 */ 466 public boolean newSystemImage() { 467 try { 468 File buildInfoFile = new File(SYSTEM_BUILD_INFOS_FILE); 469 File buildInfoPlugins = new File(pluginsPath, BUILD_INFOS_FILE); 470 if (!buildInfoPlugins.exists()) { 471 if (LOGV_ENABLED) { 472 Log.v(TAG, "build.prop in plugins directory " + pluginsPath 473 + " does not exist, therefore it's a new system image"); 474 } 475 return true; 476 } else { 477 String buildInfo = contentsOfFile(buildInfoFile); 478 String buildInfoPlugin = contentsOfFile(buildInfoPlugins); 479 if (buildInfo == null || buildInfoPlugin == null 480 || buildInfo.compareTo(buildInfoPlugin) != 0) { 481 if (LOGV_ENABLED) { 482 Log.v(TAG, "build.prop are different, " 483 + " therefore it's a new system image"); 484 } 485 return true; 486 } 487 } 488 } catch (Exception e) { 489 Log.e(TAG, "Exc in newSystemImage(): " + e); 490 } 491 return false; 492 } 493 494 /** 495 * Check if the version of the plugins contained in the 496 * Browser assets is the same as the version of the plugins 497 * in the plugins directory. 498 * We simply iterate on every file in the assets/plugins 499 * and return false if a file listed in the assets does 500 * not exist in the plugins directory. 501 */ 502 private boolean checkIsDifferentVersions() { 503 try { 504 ZipFile zip = new ZipFile(APK_PATH); 505 Vector<ZipEntry> files = pluginsFilesFromZip(zip); 506 int zipFilterLength = ZIP_FILTER.length(); 507 508 Enumeration entries = files.elements(); 509 while (entries.hasMoreElements()) { 510 ZipEntry entry = (ZipEntry) entries.nextElement(); 511 String path = entry.getName().substring(zipFilterLength); 512 File outputFile = new File(pluginsPath, path); 513 if (!outputFile.exists()) { 514 if (LOGV_ENABLED) { 515 Log.v(TAG, "checkIsDifferentVersions(): extracted file " 516 + path + " does not exist, we have a different version"); 517 } 518 return true; 519 } 520 } 521 } catch (IOException e) { 522 Log.e(TAG, "Exception in checkDifferentVersions(): " + e); 523 } 524 return false; 525 } 526 527 /** 528 * Copy every files from the assets/plugins directory 529 * to the app_plugins directory in the data partition. 530 * Once copied, we copy over the SYSTEM_BUILD_INFOS file 531 * in the plugins directory. 532 * 533 * NOTE: we directly access the content from the Browser 534 * package (it's a zip file) and do not use AssetManager 535 * as there is a limit of 1Mb (see Asset.h) 536 */ 537 public void run() { 538 // Lower the priority 539 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 540 try { 541 if (pluginsPath == null) { 542 Log.e(TAG, "No plugins path found!"); 543 return; 544 } 545 546 ZipFile zip = new ZipFile(APK_PATH); 547 Vector<ZipEntry> files = pluginsFilesFromZip(zip); 548 Vector<File> plugins = new Vector<File>(); 549 int zipFilterLength = ZIP_FILTER.length(); 550 551 Enumeration entries = files.elements(); 552 while (entries.hasMoreElements()) { 553 ZipEntry entry = (ZipEntry) entries.nextElement(); 554 String path = entry.getName().substring(zipFilterLength); 555 File outputFile = new File(pluginsPath, path); 556 outputFile.getParentFile().mkdirs(); 557 558 if (outputFile.exists() && !mDoOverwrite) { 559 if (LOGV_ENABLED) { 560 Log.v(TAG, path + " already extracted."); 561 } 562 } else { 563 if (path.endsWith(PLUGIN_EXTENSION)) { 564 // We rename plugins to be sure a half-copied 565 // plugin is not loaded by the browser. 566 plugins.add(outputFile); 567 outputFile = new File(pluginsPath, 568 path + TEMPORARY_EXTENSION); 569 } 570 FileOutputStream fos = new FileOutputStream(outputFile); 571 if (LOGV_ENABLED) { 572 Log.v(TAG, "copy " + entry + " to " 573 + pluginsPath + "/" + path); 574 } 575 copyStreams(zip.getInputStream(entry), fos); 576 } 577 } 578 579 // We now rename the .so we copied, once all their resources 580 // are safely copied over to the user data partition. 581 Enumeration elems = plugins.elements(); 582 while (elems.hasMoreElements()) { 583 File renamedFile = (File) elems.nextElement(); 584 File sourceFile = new File(renamedFile.getPath() 585 + TEMPORARY_EXTENSION); 586 if (LOGV_ENABLED) { 587 Log.v(TAG, "rename " + sourceFile.getPath() 588 + " to " + renamedFile.getPath()); 589 } 590 sourceFile.renameTo(renamedFile); 591 } 592 593 copyBuildInfos(); 594 } catch (IOException e) { 595 Log.e(TAG, "IO Exception: " + e); 596 } 597 } 598 }; 599 600 /** 601 * Copy the content of assets/plugins/ to the app_plugins directory 602 * in the data partition. 603 * 604 * This function is called every time the browser is started. 605 * We first check if the system image is newer than the one that 606 * copied the plugins (if there's plugins in the data partition). 607 * If this is the case, we then check if the versions are different. 608 * If they are different, we clean the plugins directory in the 609 * data partition, then start a thread to copy the plugins while 610 * the browser continue to load. 611 * 612 * @param overwrite if true overwrite the files even if they are 613 * already present (to let the user "reset" the plugins if needed). 614 */ 615 private void copyPlugins(boolean overwrite) { 616 CopyPlugins copyPluginsFromAssets = new CopyPlugins(overwrite, this); 617 copyPluginsFromAssets.initPluginsPath(); 618 if (copyPluginsFromAssets.newSystemImage()) { 619 if (copyPluginsFromAssets.checkIsDifferentVersions()) { 620 copyPluginsFromAssets.cleanPluginsDirectory(); 621 Thread copyplugins = new Thread(copyPluginsFromAssets); 622 copyplugins.setName("CopyPlugins"); 623 copyplugins.start(); 624 } 625 } 626 } 627 628 private class ClearThumbnails extends AsyncTask<File, Void, Void> { 629 @Override 630 public Void doInBackground(File... files) { 631 if (files != null) { 632 for (File f : files) { 633 f.delete(); 634 } 635 } 636 return null; 637 } 638 } 639 640 // Flag to enable the touchable browser bar with buttons 641 private final boolean CUSTOM_BROWSER_BAR = true; 642 643 @Override public void onCreate(Bundle icicle) { 644 if (LOGV_ENABLED) { 645 Log.v(LOGTAG, this + " onStart"); 646 } 647 super.onCreate(icicle); 648 if (CUSTOM_BROWSER_BAR) { 649 this.requestWindowFeature(Window.FEATURE_NO_TITLE); 650 } else { 651 this.requestWindowFeature(Window.FEATURE_LEFT_ICON); 652 this.requestWindowFeature(Window.FEATURE_RIGHT_ICON); 653 this.requestWindowFeature(Window.FEATURE_PROGRESS); 654 this.requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); 655 } 656 // test the browser in OpenGL 657 // requestWindowFeature(Window.FEATURE_OPENGL); 658 659 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL); 660 661 mResolver = getContentResolver(); 662 663 // 664 // start MASF proxy service 665 // 666 //Intent proxyServiceIntent = new Intent(); 667 //proxyServiceIntent.setComponent 668 // (new ComponentName( 669 // "com.android.masfproxyservice", 670 // "com.android.masfproxyservice.MasfProxyService")); 671 //startService(proxyServiceIntent, null); 672 673 mSecLockIcon = Resources.getSystem().getDrawable( 674 android.R.drawable.ic_secure); 675 mMixLockIcon = Resources.getSystem().getDrawable( 676 android.R.drawable.ic_partial_secure); 677 mGenericFavicon = getResources().getDrawable( 678 R.drawable.app_web_browser_sm); 679 680 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView() 681 .findViewById(com.android.internal.R.id.content); 682 if (CUSTOM_BROWSER_BAR) { 683 // This FrameLayout will hold the custom FrameLayout and a LinearLayout 684 // that contains the title bar and a FrameLayout, which 685 // holds everything else. 686 FrameLayout browserFrameLayout = (FrameLayout) LayoutInflater.from(this) 687 .inflate(R.layout.custom_screen, null); 688 mTitleBar = (TitleBar) browserFrameLayout.findViewById(R.id.title_bar); 689 mTitleBar.setBrowserActivity(this); 690 mContentView = (FrameLayout) browserFrameLayout.findViewById( 691 R.id.main_content); 692 mCustomViewContainer = (FrameLayout) browserFrameLayout 693 .findViewById(R.id.fullscreen_custom_content); 694 frameLayout.addView(browserFrameLayout, COVER_SCREEN_PARAMS); 695 } else { 696 mCustomViewContainer = new FrameLayout(this); 697 mCustomViewContainer.setBackgroundColor(Color.BLACK); 698 mContentView = new FrameLayout(this); 699 frameLayout.addView(mCustomViewContainer, COVER_SCREEN_PARAMS); 700 frameLayout.addView(mContentView, COVER_SCREEN_PARAMS); 701 } 702 703 // Create the tab control and our initial tab 704 mTabControl = new TabControl(this); 705 706 // Open the icon database and retain all the bookmark urls for favicons 707 retainIconsOnStartup(); 708 709 // Keep a settings instance handy. 710 mSettings = BrowserSettings.getInstance(); 711 mSettings.setTabControl(mTabControl); 712 mSettings.loadFromDb(this); 713 714 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); 715 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser"); 716 717 // If this was a web search request, pass it on to the default web search provider. 718 if (handleWebSearchIntent(getIntent())) { 719 moveTaskToBack(true); 720 return; 721 } 722 723 if (!mTabControl.restoreState(icicle)) { 724 // clear up the thumbnail directory if we can't restore the state as 725 // none of the files in the directory are referenced any more. 726 new ClearThumbnails().execute( 727 mTabControl.getThumbnailDir().listFiles()); 728 final Intent intent = getIntent(); 729 final Bundle extra = intent.getExtras(); 730 // Create an initial tab. 731 // If the intent is ACTION_VIEW and data is not null, the Browser is 732 // invoked to view the content by another application. In this case, 733 // the tab will be close when exit. 734 UrlData urlData = getUrlDataFromIntent(intent); 735 736 final TabControl.Tab t = mTabControl.createNewTab( 737 Intent.ACTION_VIEW.equals(intent.getAction()) && 738 intent.getData() != null, 739 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl); 740 mTabControl.setCurrentTab(t); 741 // This is one of the only places we call attachTabToContentView 742 // without animating from the tab picker. 743 attachTabToContentView(t); 744 WebView webView = t.getWebView(); 745 if (extra != null) { 746 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0); 747 if (scale > 0 && scale <= 1000) { 748 webView.setInitialScale(scale); 749 } 750 } 751 // If we are not restoring from an icicle, then there is a high 752 // likely hood this is the first run. So, check to see if the 753 // homepage needs to be configured and copy any plugins from our 754 // asset directory to the data partition. 755 if ((extra == null || !extra.getBoolean("testing")) 756 && !mSettings.isLoginInitialized()) { 757 setupHomePage(); 758 } 759 copyPlugins(true); 760 761 if (urlData.isEmpty()) { 762 if (mSettings.isLoginInitialized()) { 763 webView.loadUrl(mSettings.getHomePage()); 764 } else { 765 waitForCredentials(); 766 } 767 } else { 768 if (extra != null) { 769 urlData.setPostData(extra 770 .getByteArray(Browser.EXTRA_POST_DATA)); 771 } 772 urlData.loadIn(webView); 773 } 774 } else { 775 // TabControl.restoreState() will create a new tab even if 776 // restoring the state fails. Attach it to the view here since we 777 // are not animating from the tab picker. 778 attachTabToContentView(mTabControl.getCurrentTab()); 779 } 780 // Read JavaScript flags if it exists. 781 String jsFlags = mSettings.getJsFlags(); 782 if (jsFlags.trim().length() != 0) { 783 mTabControl.getCurrentWebView().setJsFlags(jsFlags); 784 } 785 786 /* enables registration for changes in network status from 787 http stack */ 788 mNetworkStateChangedFilter = new IntentFilter(); 789 mNetworkStateChangedFilter.addAction( 790 ConnectivityManager.CONNECTIVITY_ACTION); 791 mNetworkStateIntentReceiver = new BroadcastReceiver() { 792 @Override 793 public void onReceive(Context context, Intent intent) { 794 if (intent.getAction().equals( 795 ConnectivityManager.CONNECTIVITY_ACTION)) { 796 boolean down = intent.getBooleanExtra( 797 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); 798 onNetworkToggle(!down); 799 } 800 } 801 }; 802 803 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED); 804 filter.addAction(Intent.ACTION_PACKAGE_REMOVED); 805 filter.addDataScheme("package"); 806 mPackageInstallationReceiver = new BroadcastReceiver() { 807 @Override 808 public void onReceive(Context context, Intent intent) { 809 final String action = intent.getAction(); 810 final String packageName = intent.getData() 811 .getSchemeSpecificPart(); 812 final boolean replacing = intent.getBooleanExtra( 813 Intent.EXTRA_REPLACING, false); 814 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) { 815 // if it is replacing, refreshPlugins() when adding 816 return; 817 } 818 PackageManager pm = BrowserActivity.this.getPackageManager(); 819 PackageInfo pkgInfo = null; 820 try { 821 pkgInfo = pm.getPackageInfo(packageName, 822 PackageManager.GET_PERMISSIONS); 823 } catch (PackageManager.NameNotFoundException e) { 824 return; 825 } 826 if (pkgInfo != null) { 827 String permissions[] = pkgInfo.requestedPermissions; 828 if (permissions == null) { 829 return; 830 } 831 boolean permissionOk = false; 832 for (String permit : permissions) { 833 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) { 834 permissionOk = true; 835 break; 836 } 837 } 838 if (permissionOk) { 839 PluginManager.getInstance(BrowserActivity.this) 840 .refreshPlugins( 841 Intent.ACTION_PACKAGE_ADDED 842 .equals(action)); 843 } 844 } 845 } 846 }; 847 registerReceiver(mPackageInstallationReceiver, filter); 848 } 849 850 @Override 851 protected void onNewIntent(Intent intent) { 852 TabControl.Tab current = mTabControl.getCurrentTab(); 853 // When a tab is closed on exit, the current tab index is set to -1. 854 // Reset before proceed as Browser requires the current tab to be set. 855 if (current == null) { 856 // Try to reset the tab in case the index was incorrect. 857 current = mTabControl.getTab(0); 858 if (current == null) { 859 // No tabs at all so just ignore this intent. 860 return; 861 } 862 mTabControl.setCurrentTab(current); 863 attachTabToContentView(current); 864 resetTitleAndIcon(current.getWebView()); 865 } 866 final String action = intent.getAction(); 867 final int flags = intent.getFlags(); 868 if (Intent.ACTION_MAIN.equals(action) || 869 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) { 870 // just resume the browser 871 return; 872 } 873 if (Intent.ACTION_VIEW.equals(action) 874 || Intent.ACTION_SEARCH.equals(action) 875 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action) 876 || Intent.ACTION_WEB_SEARCH.equals(action)) { 877 // If this was a search request (e.g. search query directly typed into the address bar), 878 // pass it on to the default web search provider. 879 if (handleWebSearchIntent(intent)) { 880 return; 881 } 882 883 UrlData urlData = getUrlDataFromIntent(intent); 884 if (urlData.isEmpty()) { 885 urlData = new UrlData(mSettings.getHomePage()); 886 } 887 urlData.setPostData(intent 888 .getByteArrayExtra(Browser.EXTRA_POST_DATA)); 889 890 if (Intent.ACTION_VIEW.equals(action) && 891 (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) { 892 final String appId = 893 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID); 894 final TabControl.Tab appTab = mTabControl.getTabFromId(appId); 895 if (appTab != null) { 896 Log.i(LOGTAG, "Reusing tab for " + appId); 897 // Dismiss the subwindow if applicable. 898 dismissSubWindow(appTab); 899 // Since we might kill the WebView, remove it from the 900 // content view first. 901 removeTabFromContentView(appTab); 902 // Recreate the main WebView after destroying the old one. 903 // If the WebView has the same original url and is on that 904 // page, it can be reused. 905 boolean needsLoad = 906 mTabControl.recreateWebView(appTab, urlData.mUrl); 907 908 if (current != appTab) { 909 showTab(appTab, needsLoad ? urlData : EMPTY_URL_DATA); 910 } else { 911 if (mTabOverview != null && mAnimationCount == 0) { 912 sendAnimateFromOverview(appTab, false, 913 needsLoad ? urlData : EMPTY_URL_DATA, 914 TAB_OVERVIEW_DELAY, null); 915 } else { 916 // If the tab was the current tab, we have to attach 917 // it to the view system again. 918 attachTabToContentView(appTab); 919 if (needsLoad) { 920 urlData.loadIn(appTab.getWebView()); 921 } 922 } 923 } 924 return; 925 } 926 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url will be 927 // opened in a new tab unless we have reached MAX_TABS. Then the 928 // url will be opened in the current tab. If a new tab is 929 // created, it will have "true" for exit on close. 930 openTabAndShow(urlData, null, true, appId); 931 } else { 932 if ("about:debug".equals(urlData.mUrl)) { 933 mSettings.toggleDebugSettings(); 934 return; 935 } 936 // If the Window overview is up and we are not in the midst of 937 // an animation, animate away from the Window overview. 938 if (mTabOverview != null && mAnimationCount == 0) { 939 sendAnimateFromOverview(current, false, urlData, 940 TAB_OVERVIEW_DELAY, null); 941 } else { 942 // Get rid of the subwindow if it exists 943 dismissSubWindow(current); 944 urlData.loadIn(current.getWebView()); 945 } 946 } 947 } 948 } 949 950 private int parseUrlShortcut(String url) { 951 if (url == null) return SHORTCUT_INVALID; 952 953 // FIXME: quick search, need to be customized by setting 954 if (url.length() > 2 && url.charAt(1) == ' ') { 955 switch (url.charAt(0)) { 956 case 'g': return SHORTCUT_GOOGLE_SEARCH; 957 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH; 958 case 'd': return SHORTCUT_DICTIONARY_SEARCH; 959 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH; 960 } 961 } 962 return SHORTCUT_INVALID; 963 } 964 965 /** 966 * Launches the default web search activity with the query parameters if the given intent's data 967 * are identified as plain search terms and not URLs/shortcuts. 968 * @return true if the intent was handled and web search activity was launched, false if not. 969 */ 970 private boolean handleWebSearchIntent(Intent intent) { 971 if (intent == null) return false; 972 973 String url = null; 974 final String action = intent.getAction(); 975 if (Intent.ACTION_VIEW.equals(action)) { 976 url = intent.getData().toString(); 977 } else if (Intent.ACTION_SEARCH.equals(action) 978 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action) 979 || Intent.ACTION_WEB_SEARCH.equals(action)) { 980 url = intent.getStringExtra(SearchManager.QUERY); 981 } 982 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA)); 983 } 984 985 /** 986 * Launches the default web search activity with the query parameters if the given url string 987 * was identified as plain search terms and not URL/shortcut. 988 * @return true if the request was handled and web search activity was launched, false if not. 989 */ 990 private boolean handleWebSearchRequest(String inUrl, Bundle appData) { 991 if (inUrl == null) return false; 992 993 // In general, we shouldn't modify URL from Intent. 994 // But currently, we get the user-typed URL from search box as well. 995 String url = fixUrl(inUrl).trim(); 996 997 // URLs and site specific search shortcuts are handled by the regular flow of control, so 998 // return early. 999 if (Regex.WEB_URL_PATTERN.matcher(url).matches() 1000 || ACCEPTED_URI_SCHEMA.matcher(url).matches() 1001 || parseUrlShortcut(url) != SHORTCUT_INVALID) { 1002 return false; 1003 } 1004 1005 Browser.updateVisitedHistory(mResolver, url, false); 1006 Browser.addSearchUrl(mResolver, url); 1007 1008 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH); 1009 intent.addCategory(Intent.CATEGORY_DEFAULT); 1010 intent.putExtra(SearchManager.QUERY, url); 1011 if (appData != null) { 1012 intent.putExtra(SearchManager.APP_DATA, appData); 1013 } 1014 startActivity(intent); 1015 1016 return true; 1017 } 1018 1019 private UrlData getUrlDataFromIntent(Intent intent) { 1020 String url = null; 1021 if (intent != null) { 1022 final String action = intent.getAction(); 1023 if (Intent.ACTION_VIEW.equals(action)) { 1024 url = smartUrlFilter(intent.getData()); 1025 if (url != null && url.startsWith("content:")) { 1026 /* Append mimetype so webview knows how to display */ 1027 String mimeType = intent.resolveType(getContentResolver()); 1028 if (mimeType != null) { 1029 url += "?" + mimeType; 1030 } 1031 } 1032 if ("inline:".equals(url)) { 1033 return new InlinedUrlData( 1034 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT), 1035 intent.getType(), 1036 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING), 1037 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL)); 1038 } 1039 } else if (Intent.ACTION_SEARCH.equals(action) 1040 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action) 1041 || Intent.ACTION_WEB_SEARCH.equals(action)) { 1042 url = intent.getStringExtra(SearchManager.QUERY); 1043 if (url != null) { 1044 mLastEnteredUrl = url; 1045 // Don't add Urls, just search terms. 1046 // Urls will get added when the page is loaded. 1047 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) { 1048 Browser.updateVisitedHistory(mResolver, url, false); 1049 } 1050 // In general, we shouldn't modify URL from Intent. 1051 // But currently, we get the user-typed URL from search box as well. 1052 url = fixUrl(url); 1053 url = smartUrlFilter(url); 1054 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&"; 1055 if (url.contains(searchSource)) { 1056 String source = null; 1057 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA); 1058 if (appData != null) { 1059 source = appData.getString(SearchManager.SOURCE); 1060 } 1061 if (TextUtils.isEmpty(source)) { 1062 source = GOOGLE_SEARCH_SOURCE_UNKNOWN; 1063 } 1064 url = url.replace(searchSource, "&source=android-"+source+"&"); 1065 } 1066 } 1067 } 1068 } 1069 return new UrlData(url); 1070 } 1071 1072 /* package */ static String fixUrl(String inUrl) { 1073 if (inUrl.startsWith("http://") || inUrl.startsWith("https://")) 1074 return inUrl; 1075 if (inUrl.startsWith("http:") || 1076 inUrl.startsWith("https:")) { 1077 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) { 1078 inUrl = inUrl.replaceFirst("/", "//"); 1079 } else inUrl = inUrl.replaceFirst(":", "://"); 1080 } 1081 return inUrl; 1082 } 1083 1084 /** 1085 * Looking for the pattern like this 1086 * 1087 * * 1088 * * * 1089 * *** * ******* 1090 * * * 1091 * * * 1092 * * 1093 */ 1094 private final SensorListener mSensorListener = new SensorListener() { 1095 private long mLastGestureTime; 1096 private float[] mPrev = new float[3]; 1097 private float[] mPrevDiff = new float[3]; 1098 private float[] mDiff = new float[3]; 1099 private float[] mRevertDiff = new float[3]; 1100 1101 public void onSensorChanged(int sensor, float[] values) { 1102 boolean show = false; 1103 float[] diff = new float[3]; 1104 1105 for (int i = 0; i < 3; i++) { 1106 diff[i] = values[i] - mPrev[i]; 1107 if (Math.abs(diff[i]) > 1) { 1108 show = true; 1109 } 1110 if ((diff[i] > 1.0 && mDiff[i] < 0.2) 1111 || (diff[i] < -1.0 && mDiff[i] > -0.2)) { 1112 // start track when there is a big move, or revert 1113 mRevertDiff[i] = mDiff[i]; 1114 mDiff[i] = 0; 1115 } else if (diff[i] > -0.2 && diff[i] < 0.2) { 1116 // reset when it is flat 1117 mDiff[i] = mRevertDiff[i] = 0; 1118 } 1119 mDiff[i] += diff[i]; 1120 mPrevDiff[i] = diff[i]; 1121 mPrev[i] = values[i]; 1122 } 1123 1124 if (false) { 1125 // only shows if we think the delta is big enough, in an attempt 1126 // to detect "serious" moves left/right or up/down 1127 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " (" 1128 + values[0] + ", " + values[1] + ", " + values[2] + ")" 1129 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2] 1130 + ")"); 1131 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " " 1132 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff(" 1133 + mRevertDiff[0] + " " + mRevertDiff[1] + " " 1134 + mRevertDiff[2] + ")"); 1135 } 1136 1137 long now = android.os.SystemClock.uptimeMillis(); 1138 if (now - mLastGestureTime > 1000) { 1139 mLastGestureTime = 0; 1140 1141 float y = mDiff[1]; 1142 float z = mDiff[2]; 1143 float ay = Math.abs(y); 1144 float az = Math.abs(z); 1145 float ry = mRevertDiff[1]; 1146 float rz = mRevertDiff[2]; 1147 float ary = Math.abs(ry); 1148 float arz = Math.abs(rz); 1149 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary; 1150 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz; 1151 1152 if ((gestY || gestZ) && !(gestY && gestZ)) { 1153 WebView view = mTabControl.getCurrentWebView(); 1154 1155 if (view != null) { 1156 if (gestZ) { 1157 if (z < 0) { 1158 view.zoomOut(); 1159 } else { 1160 view.zoomIn(); 1161 } 1162 } else { 1163 view.flingScroll(0, Math.round(y * 100)); 1164 } 1165 } 1166 mLastGestureTime = now; 1167 } 1168 } 1169 } 1170 1171 public void onAccuracyChanged(int sensor, int accuracy) { 1172 // TODO Auto-generated method stub 1173 1174 } 1175 }; 1176 1177 @Override protected void onResume() { 1178 super.onResume(); 1179 if (LOGV_ENABLED) { 1180 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this); 1181 } 1182 1183 if (!mActivityInPause) { 1184 Log.e(LOGTAG, "BrowserActivity is already resumed."); 1185 return; 1186 } 1187 1188 mTabControl.resumeCurrentTab(); 1189 mActivityInPause = false; 1190 resumeWebViewTimers(); 1191 1192 if (mWakeLock.isHeld()) { 1193 mHandler.removeMessages(RELEASE_WAKELOCK); 1194 mWakeLock.release(); 1195 } 1196 1197 if (mCredsDlg != null) { 1198 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) { 1199 // In case credential request never comes back 1200 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000); 1201 } 1202 } 1203 1204 registerReceiver(mNetworkStateIntentReceiver, 1205 mNetworkStateChangedFilter); 1206 WebView.enablePlatformNotifications(); 1207 1208 if (mSettings.doFlick()) { 1209 if (mSensorManager == null) { 1210 mSensorManager = (SensorManager) getSystemService( 1211 Context.SENSOR_SERVICE); 1212 } 1213 mSensorManager.registerListener(mSensorListener, 1214 SensorManager.SENSOR_ACCELEROMETER, 1215 SensorManager.SENSOR_DELAY_FASTEST); 1216 } else { 1217 mSensorManager = null; 1218 } 1219 } 1220 1221 /** 1222 * onSaveInstanceState(Bundle map) 1223 * onSaveInstanceState is called right before onStop(). The map contains 1224 * the saved state. 1225 */ 1226 @Override protected void onSaveInstanceState(Bundle outState) { 1227 if (LOGV_ENABLED) { 1228 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this); 1229 } 1230 // the default implementation requires each view to have an id. As the 1231 // browser handles the state itself and it doesn't use id for the views, 1232 // don't call the default implementation. Otherwise it will trigger the 1233 // warning like this, "couldn't save which view has focus because the 1234 // focused view XXX has no id". 1235 1236 // Save all the tabs 1237 mTabControl.saveState(outState); 1238 } 1239 1240 @Override protected void onPause() { 1241 super.onPause(); 1242 1243 if (mActivityInPause) { 1244 Log.e(LOGTAG, "BrowserActivity is already paused."); 1245 return; 1246 } 1247 1248 mTabControl.pauseCurrentTab(); 1249 mActivityInPause = true; 1250 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) { 1251 mWakeLock.acquire(); 1252 mHandler.sendMessageDelayed(mHandler 1253 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT); 1254 } 1255 1256 // Clear the credentials toast if it is up 1257 if (mCredsDlg != null && mCredsDlg.isShowing()) { 1258 mCredsDlg.dismiss(); 1259 } 1260 mCredsDlg = null; 1261 1262 cancelStopToast(); 1263 1264 // unregister network state listener 1265 unregisterReceiver(mNetworkStateIntentReceiver); 1266 WebView.disablePlatformNotifications(); 1267 1268 if (mSensorManager != null) { 1269 mSensorManager.unregisterListener(mSensorListener); 1270 } 1271 } 1272 1273 @Override protected void onDestroy() { 1274 if (LOGV_ENABLED) { 1275 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this); 1276 } 1277 super.onDestroy(); 1278 // Remove the current tab and sub window 1279 TabControl.Tab t = mTabControl.getCurrentTab(); 1280 if (t != null) { 1281 dismissSubWindow(t); 1282 removeTabFromContentView(t); 1283 } 1284 // Destroy all the tabs 1285 mTabControl.destroy(); 1286 WebIconDatabase.getInstance().close(); 1287 if (mGlsConnection != null) { 1288 unbindService(mGlsConnection); 1289 mGlsConnection = null; 1290 } 1291 1292 // 1293 // stop MASF proxy service 1294 // 1295 //Intent proxyServiceIntent = new Intent(); 1296 //proxyServiceIntent.setComponent 1297 // (new ComponentName( 1298 // "com.android.masfproxyservice", 1299 // "com.android.masfproxyservice.MasfProxyService")); 1300 //stopService(proxyServiceIntent); 1301 1302 unregisterReceiver(mPackageInstallationReceiver); 1303 } 1304 1305 @Override 1306 public void onConfigurationChanged(Configuration newConfig) { 1307 super.onConfigurationChanged(newConfig); 1308 1309 if (mPageInfoDialog != null) { 1310 mPageInfoDialog.dismiss(); 1311 showPageInfo( 1312 mPageInfoView, 1313 mPageInfoFromShowSSLCertificateOnError.booleanValue()); 1314 } 1315 if (mSSLCertificateDialog != null) { 1316 mSSLCertificateDialog.dismiss(); 1317 showSSLCertificate( 1318 mSSLCertificateView); 1319 } 1320 if (mSSLCertificateOnErrorDialog != null) { 1321 mSSLCertificateOnErrorDialog.dismiss(); 1322 showSSLCertificateOnError( 1323 mSSLCertificateOnErrorView, 1324 mSSLCertificateOnErrorHandler, 1325 mSSLCertificateOnErrorError); 1326 } 1327 if (mHttpAuthenticationDialog != null) { 1328 String title = ((TextView) mHttpAuthenticationDialog 1329 .findViewById(com.android.internal.R.id.alertTitle)).getText() 1330 .toString(); 1331 String name = ((TextView) mHttpAuthenticationDialog 1332 .findViewById(R.id.username_edit)).getText().toString(); 1333 String password = ((TextView) mHttpAuthenticationDialog 1334 .findViewById(R.id.password_edit)).getText().toString(); 1335 int focusId = mHttpAuthenticationDialog.getCurrentFocus() 1336 .getId(); 1337 mHttpAuthenticationDialog.dismiss(); 1338 showHttpAuthentication(mHttpAuthHandler, null, null, title, 1339 name, password, focusId); 1340 } 1341 if (mFindDialog != null && mFindDialog.isShowing()) { 1342 mFindDialog.onConfigurationChanged(newConfig); 1343 } 1344 } 1345 1346 @Override public void onLowMemory() { 1347 super.onLowMemory(); 1348 mTabControl.freeMemory(); 1349 } 1350 1351 private boolean resumeWebViewTimers() { 1352 if ((!mActivityInPause && !mPageStarted) || 1353 (mActivityInPause && mPageStarted)) { 1354 CookieSyncManager.getInstance().startSync(); 1355 WebView w = mTabControl.getCurrentWebView(); 1356 if (w != null) { 1357 w.resumeTimers(); 1358 } 1359 return true; 1360 } else { 1361 return false; 1362 } 1363 } 1364 1365 private boolean pauseWebViewTimers() { 1366 if (mActivityInPause && !mPageStarted) { 1367 CookieSyncManager.getInstance().stopSync(); 1368 WebView w = mTabControl.getCurrentWebView(); 1369 if (w != null) { 1370 w.pauseTimers(); 1371 } 1372 return true; 1373 } else { 1374 return false; 1375 } 1376 } 1377 1378 /* 1379 * This function is called when we are launching for the first time. We 1380 * are waiting for the login credentials before loading Google home 1381 * pages. This way the user will be logged in straight away. 1382 */ 1383 private void waitForCredentials() { 1384 // Show a toast 1385 mCredsDlg = new ProgressDialog(this); 1386 mCredsDlg.setIndeterminate(true); 1387 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg)); 1388 // If the user cancels the operation, then cancel the Google 1389 // Credentials request. 1390 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST)); 1391 mCredsDlg.show(); 1392 1393 // We set a timeout for the retrieval of credentials in onResume() 1394 // as that is when we have freed up some CPU time to get 1395 // the login credentials. 1396 } 1397 1398 /* 1399 * If we have received the credentials or we have timed out and we are 1400 * showing the credentials dialog, then it is time to move on. 1401 */ 1402 private void resumeAfterCredentials() { 1403 if (mCredsDlg == null) { 1404 return; 1405 } 1406 1407 // Clear the toast 1408 if (mCredsDlg.isShowing()) { 1409 mCredsDlg.dismiss(); 1410 } 1411 mCredsDlg = null; 1412 1413 // Clear any pending timeout 1414 mHandler.removeMessages(CANCEL_CREDS_REQUEST); 1415 1416 // Load the page 1417 WebView w = mTabControl.getCurrentWebView(); 1418 if (w != null) { 1419 w.loadUrl(mSettings.getHomePage()); 1420 } 1421 1422 // Update the settings, need to do this last as it can take a moment 1423 // to persist the settings. In the mean time we could be loading 1424 // content. 1425 mSettings.setLoginInitialized(this); 1426 } 1427 1428 // Open the icon database and retain all the icons for visited sites. 1429 private void retainIconsOnStartup() { 1430 final WebIconDatabase db = WebIconDatabase.getInstance(); 1431 db.open(getDir("icons", 0).getPath()); 1432 try { 1433 Cursor c = Browser.getAllBookmarks(mResolver); 1434 if (!c.moveToFirst()) { 1435 c.deactivate(); 1436 return; 1437 } 1438 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL); 1439 do { 1440 String url = c.getString(urlIndex); 1441 db.retainIconForPageUrl(url); 1442 } while (c.moveToNext()); 1443 c.deactivate(); 1444 } catch (IllegalStateException e) { 1445 Log.e(LOGTAG, "retainIconsOnStartup", e); 1446 } 1447 } 1448 1449 // Helper method for getting the top window. 1450 WebView getTopWindow() { 1451 return mTabControl.getCurrentTopWebView(); 1452 } 1453 1454 @Override 1455 public boolean onCreateOptionsMenu(Menu menu) { 1456 super.onCreateOptionsMenu(menu); 1457 1458 MenuInflater inflater = getMenuInflater(); 1459 inflater.inflate(R.menu.browser, menu); 1460 mMenu = menu; 1461 updateInLoadMenuItems(); 1462 return true; 1463 } 1464 1465 /** 1466 * As the menu can be open when loading state changes 1467 * we must manually update the state of the stop/reload menu 1468 * item 1469 */ 1470 private void updateInLoadMenuItems() { 1471 if (mMenu == null) { 1472 return; 1473 } 1474 MenuItem src = mInLoad ? 1475 mMenu.findItem(R.id.stop_menu_id): 1476 mMenu.findItem(R.id.reload_menu_id); 1477 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id); 1478 dest.setIcon(src.getIcon()); 1479 dest.setTitle(src.getTitle()); 1480 } 1481 1482 @Override 1483 public boolean onContextItemSelected(MenuItem item) { 1484 // chording is not an issue with context menus, but we use the same 1485 // options selector, so set mCanChord to true so we can access them. 1486 mCanChord = true; 1487 int id = item.getItemId(); 1488 final WebView webView = getTopWindow(); 1489 if (null == webView) { 1490 return false; 1491 } 1492 final HashMap hrefMap = new HashMap(); 1493 hrefMap.put("webview", webView); 1494 final Message msg = mHandler.obtainMessage( 1495 FOCUS_NODE_HREF, id, 0, hrefMap); 1496 switch (id) { 1497 // -- Browser context menu 1498 case R.id.open_context_menu_id: 1499 case R.id.open_newtab_context_menu_id: 1500 case R.id.bookmark_context_menu_id: 1501 case R.id.save_link_context_menu_id: 1502 case R.id.share_link_context_menu_id: 1503 case R.id.copy_link_context_menu_id: 1504 webView.requestFocusNodeHref(msg); 1505 break; 1506 1507 default: 1508 // For other context menus 1509 return onOptionsItemSelected(item); 1510 } 1511 mCanChord = false; 1512 return true; 1513 } 1514 1515 private Bundle createGoogleSearchSourceBundle(String source) { 1516 Bundle bundle = new Bundle(); 1517 bundle.putString(SearchManager.SOURCE, source); 1518 return bundle; 1519 } 1520 1521 /** 1522 * Overriding this to insert a local information bundle 1523 */ 1524 @Override 1525 public boolean onSearchRequested() { 1526 String url = getTopWindow().getUrl(); 1527 startSearch(mSettings.getHomePage().equals(url) ? null : url, false, 1528 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false); 1529 return true; 1530 } 1531 1532 @Override 1533 public void startSearch(String initialQuery, boolean selectInitialQuery, 1534 Bundle appSearchData, boolean globalSearch) { 1535 if (appSearchData == null) { 1536 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE); 1537 } 1538 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch); 1539 } 1540 1541 @Override 1542 public boolean onOptionsItemSelected(MenuItem item) { 1543 if (!mCanChord) { 1544 // The user has already fired a shortcut with this hold down of the 1545 // menu key. 1546 return false; 1547 } 1548 if (null == mTabOverview && null == getTopWindow()) { 1549 return false; 1550 } 1551 switch (item.getItemId()) { 1552 // -- Main menu 1553 case R.id.goto_menu_id: { 1554 String url = getTopWindow().getUrl(); 1555 startSearch(mSettings.getHomePage().equals(url) ? null : url, true, 1556 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_GOTO), false); 1557 } 1558 break; 1559 1560 case R.id.bookmarks_menu_id: 1561 bookmarksOrHistoryPicker(false); 1562 break; 1563 1564 case R.id.windows_menu_id: 1565 if (mTabControl.getTabCount() == 1) { 1566 openTabAndShow(mSettings.getHomePage(), null, false, null); 1567 } else { 1568 tabPicker(true, mTabControl.getCurrentIndex(), false); 1569 } 1570 break; 1571 1572 case R.id.stop_reload_menu_id: 1573 if (mInLoad) { 1574 stopLoading(); 1575 } else { 1576 getTopWindow().reload(); 1577 } 1578 break; 1579 1580 case R.id.back_menu_id: 1581 getTopWindow().goBack(); 1582 break; 1583 1584 case R.id.forward_menu_id: 1585 getTopWindow().goForward(); 1586 break; 1587 1588 case R.id.close_menu_id: 1589 // Close the subwindow if it exists. 1590 if (mTabControl.getCurrentSubWindow() != null) { 1591 dismissSubWindow(mTabControl.getCurrentTab()); 1592 break; 1593 } 1594 final int currentIndex = mTabControl.getCurrentIndex(); 1595 final TabControl.Tab parent = 1596 mTabControl.getCurrentTab().getParentTab(); 1597 int indexToShow = -1; 1598 if (parent != null) { 1599 indexToShow = mTabControl.getTabIndex(parent); 1600 } else { 1601 // Get the last tab in the list. If it is the current tab, 1602 // subtract 1 more. 1603 indexToShow = mTabControl.getTabCount() - 1; 1604 if (currentIndex == indexToShow) { 1605 indexToShow--; 1606 } 1607 } 1608 switchTabs(currentIndex, indexToShow, true); 1609 break; 1610 1611 case R.id.homepage_menu_id: 1612 TabControl.Tab current = mTabControl.getCurrentTab(); 1613 if (current != null) { 1614 dismissSubWindow(current); 1615 current.getWebView().loadUrl(mSettings.getHomePage()); 1616 } 1617 break; 1618 1619 case R.id.preferences_menu_id: 1620 Intent intent = new Intent(this, 1621 BrowserPreferencesPage.class); 1622 startActivityForResult(intent, PREFERENCES_PAGE); 1623 break; 1624 1625 case R.id.find_menu_id: 1626 if (null == mFindDialog) { 1627 mFindDialog = new FindDialog(this); 1628 } 1629 mFindDialog.setWebView(getTopWindow()); 1630 mFindDialog.show(); 1631 mMenuState = EMPTY_MENU; 1632 break; 1633 1634 case R.id.select_text_id: 1635 getTopWindow().emulateShiftHeld(); 1636 break; 1637 case R.id.page_info_menu_id: 1638 showPageInfo(mTabControl.getCurrentTab(), false); 1639 break; 1640 1641 case R.id.classic_history_menu_id: 1642 bookmarksOrHistoryPicker(true); 1643 break; 1644 1645 case R.id.share_page_menu_id: 1646 Browser.sendString(this, getTopWindow().getUrl()); 1647 break; 1648 1649 case R.id.dump_nav_menu_id: 1650 getTopWindow().debugDump(); 1651 break; 1652 1653 case R.id.zoom_in_menu_id: 1654 getTopWindow().zoomIn(); 1655 break; 1656 1657 case R.id.zoom_out_menu_id: 1658 getTopWindow().zoomOut(); 1659 break; 1660 1661 case R.id.view_downloads_menu_id: 1662 viewDownloads(null); 1663 break; 1664 1665 // -- Tab menu 1666 case R.id.view_tab_menu_id: 1667 if (mTabListener != null && mTabOverview != null) { 1668 int pos = mTabOverview.getContextMenuPosition(item); 1669 mTabOverview.setCurrentIndex(pos); 1670 mTabListener.onClick(pos); 1671 } 1672 break; 1673 1674 case R.id.remove_tab_menu_id: 1675 if (mTabListener != null && mTabOverview != null) { 1676 int pos = mTabOverview.getContextMenuPosition(item); 1677 mTabListener.remove(pos); 1678 } 1679 break; 1680 1681 case R.id.new_tab_menu_id: 1682 // No need to check for mTabOverview here since we are not 1683 // dependent on it for a position. 1684 if (mTabListener != null) { 1685 // If the overview happens to be non-null, make the "New 1686 // Tab" cell visible. 1687 if (mTabOverview != null) { 1688 mTabOverview.setCurrentIndex(ImageGrid.NEW_TAB); 1689 } 1690 mTabListener.onClick(ImageGrid.NEW_TAB); 1691 } 1692 break; 1693 1694 case R.id.bookmark_tab_menu_id: 1695 if (mTabListener != null && mTabOverview != null) { 1696 int pos = mTabOverview.getContextMenuPosition(item); 1697 TabControl.Tab t = mTabControl.getTab(pos); 1698 // Since we called populatePickerData for all of the 1699 // tabs, getTitle and getUrl will return appropriate 1700 // values. 1701 Browser.saveBookmark(BrowserActivity.this, t.getTitle(), 1702 t.getUrl()); 1703 } 1704 break; 1705 1706 case R.id.history_tab_menu_id: 1707 bookmarksOrHistoryPicker(true); 1708 break; 1709 1710 case R.id.bookmarks_tab_menu_id: 1711 bookmarksOrHistoryPicker(false); 1712 break; 1713 1714 case R.id.properties_tab_menu_id: 1715 if (mTabListener != null && mTabOverview != null) { 1716 int pos = mTabOverview.getContextMenuPosition(item); 1717 showPageInfo(mTabControl.getTab(pos), false); 1718 } 1719 break; 1720 1721 case R.id.window_one_menu_id: 1722 case R.id.window_two_menu_id: 1723 case R.id.window_three_menu_id: 1724 case R.id.window_four_menu_id: 1725 case R.id.window_five_menu_id: 1726 case R.id.window_six_menu_id: 1727 case R.id.window_seven_menu_id: 1728 case R.id.window_eight_menu_id: 1729 { 1730 int menuid = item.getItemId(); 1731 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) { 1732 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) { 1733 TabControl.Tab desiredTab = mTabControl.getTab(id); 1734 if (desiredTab != null && 1735 desiredTab != mTabControl.getCurrentTab()) { 1736 switchTabs(mTabControl.getCurrentIndex(), id, false); 1737 } 1738 break; 1739 } 1740 } 1741 } 1742 break; 1743 1744 default: 1745 if (!super.onOptionsItemSelected(item)) { 1746 return false; 1747 } 1748 // Otherwise fall through. 1749 } 1750 mCanChord = false; 1751 return true; 1752 } 1753 1754 public void closeFind() { 1755 mMenuState = R.id.MAIN_MENU; 1756 } 1757 1758 @Override public boolean onPrepareOptionsMenu(Menu menu) 1759 { 1760 // This happens when the user begins to hold down the menu key, so 1761 // allow them to chord to get a shortcut. 1762 mCanChord = true; 1763 // Note: setVisible will decide whether an item is visible; while 1764 // setEnabled() will decide whether an item is enabled, which also means 1765 // whether the matching shortcut key will function. 1766 super.onPrepareOptionsMenu(menu); 1767 switch (mMenuState) { 1768 case R.id.TAB_MENU: 1769 if (mCurrentMenuState != mMenuState) { 1770 menu.setGroupVisible(R.id.MAIN_MENU, false); 1771 menu.setGroupEnabled(R.id.MAIN_MENU, false); 1772 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false); 1773 menu.setGroupVisible(R.id.TAB_MENU, true); 1774 menu.setGroupEnabled(R.id.TAB_MENU, true); 1775 } 1776 boolean newT = mTabControl.getTabCount() < TabControl.MAX_TABS; 1777 final MenuItem tab = menu.findItem(R.id.new_tab_menu_id); 1778 tab.setVisible(newT); 1779 tab.setEnabled(newT); 1780 break; 1781 case EMPTY_MENU: 1782 if (mCurrentMenuState != mMenuState) { 1783 menu.setGroupVisible(R.id.MAIN_MENU, false); 1784 menu.setGroupEnabled(R.id.MAIN_MENU, false); 1785 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false); 1786 menu.setGroupVisible(R.id.TAB_MENU, false); 1787 menu.setGroupEnabled(R.id.TAB_MENU, false); 1788 } 1789 break; 1790 default: 1791 if (mCurrentMenuState != mMenuState) { 1792 menu.setGroupVisible(R.id.MAIN_MENU, true); 1793 menu.setGroupEnabled(R.id.MAIN_MENU, true); 1794 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true); 1795 menu.setGroupVisible(R.id.TAB_MENU, false); 1796 menu.setGroupEnabled(R.id.TAB_MENU, false); 1797 } 1798 final WebView w = getTopWindow(); 1799 boolean canGoBack = false; 1800 boolean canGoForward = false; 1801 boolean isHome = false; 1802 if (w != null) { 1803 canGoBack = w.canGoBack(); 1804 canGoForward = w.canGoForward(); 1805 isHome = mSettings.getHomePage().equals(w.getUrl()); 1806 } 1807 final MenuItem back = menu.findItem(R.id.back_menu_id); 1808 back.setEnabled(canGoBack); 1809 1810 final MenuItem home = menu.findItem(R.id.homepage_menu_id); 1811 home.setEnabled(!isHome); 1812 1813 menu.findItem(R.id.forward_menu_id) 1814 .setEnabled(canGoForward); 1815 1816 // decide whether to show the share link option 1817 PackageManager pm = getPackageManager(); 1818 Intent send = new Intent(Intent.ACTION_SEND); 1819 send.setType("text/plain"); 1820 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY); 1821 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null); 1822 1823 // If there is only 1 window, the text will be "New window" 1824 final MenuItem windows = menu.findItem(R.id.windows_menu_id); 1825 windows.setTitleCondensed(mTabControl.getTabCount() > 1 ? 1826 getString(R.string.view_tabs_condensed) : 1827 getString(R.string.tab_picker_new_tab)); 1828 1829 boolean isNavDump = mSettings.isNavDump(); 1830 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id); 1831 nav.setVisible(isNavDump); 1832 nav.setEnabled(isNavDump); 1833 break; 1834 } 1835 mCurrentMenuState = mMenuState; 1836 return true; 1837 } 1838 1839 @Override 1840 public void onCreateContextMenu(ContextMenu menu, View v, 1841 ContextMenuInfo menuInfo) { 1842 WebView webview = (WebView) v; 1843 WebView.HitTestResult result = webview.getHitTestResult(); 1844 if (result == null) { 1845 return; 1846 } 1847 1848 int type = result.getType(); 1849 if (type == WebView.HitTestResult.UNKNOWN_TYPE) { 1850 Log.w(LOGTAG, 1851 "We should not show context menu when nothing is touched"); 1852 return; 1853 } 1854 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) { 1855 // let TextView handles context menu 1856 return; 1857 } 1858 1859 // Note, http://b/issue?id=1106666 is requesting that 1860 // an inflated menu can be used again. This is not available 1861 // yet, so inflate each time (yuk!) 1862 MenuInflater inflater = getMenuInflater(); 1863 inflater.inflate(R.menu.browsercontext, menu); 1864 1865 // Show the correct menu group 1866 String extra = result.getExtra(); 1867 menu.setGroupVisible(R.id.PHONE_MENU, 1868 type == WebView.HitTestResult.PHONE_TYPE); 1869 menu.setGroupVisible(R.id.EMAIL_MENU, 1870 type == WebView.HitTestResult.EMAIL_TYPE); 1871 menu.setGroupVisible(R.id.GEO_MENU, 1872 type == WebView.HitTestResult.GEO_TYPE); 1873 menu.setGroupVisible(R.id.IMAGE_MENU, 1874 type == WebView.HitTestResult.IMAGE_TYPE 1875 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE); 1876 menu.setGroupVisible(R.id.ANCHOR_MENU, 1877 type == WebView.HitTestResult.SRC_ANCHOR_TYPE 1878 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE); 1879 1880 // Setup custom handling depending on the type 1881 switch (type) { 1882 case WebView.HitTestResult.PHONE_TYPE: 1883 menu.setHeaderTitle(Uri.decode(extra)); 1884 menu.findItem(R.id.dial_context_menu_id).setIntent( 1885 new Intent(Intent.ACTION_VIEW, Uri 1886 .parse(WebView.SCHEME_TEL + extra))); 1887 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT); 1888 addIntent.putExtra(Insert.PHONE, Uri.decode(extra)); 1889 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE); 1890 menu.findItem(R.id.add_contact_context_menu_id).setIntent( 1891 addIntent); 1892 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener( 1893 new Copy(extra)); 1894 break; 1895 1896 case WebView.HitTestResult.EMAIL_TYPE: 1897 menu.setHeaderTitle(extra); 1898 menu.findItem(R.id.email_context_menu_id).setIntent( 1899 new Intent(Intent.ACTION_VIEW, Uri 1900 .parse(WebView.SCHEME_MAILTO + extra))); 1901 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener( 1902 new Copy(extra)); 1903 break; 1904 1905 case WebView.HitTestResult.GEO_TYPE: 1906 menu.setHeaderTitle(extra); 1907 menu.findItem(R.id.map_context_menu_id).setIntent( 1908 new Intent(Intent.ACTION_VIEW, Uri 1909 .parse(WebView.SCHEME_GEO 1910 + URLEncoder.encode(extra)))); 1911 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener( 1912 new Copy(extra)); 1913 break; 1914 1915 case WebView.HitTestResult.SRC_ANCHOR_TYPE: 1916 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE: 1917 TextView titleView = (TextView) LayoutInflater.from(this) 1918 .inflate(android.R.layout.browser_link_context_header, 1919 null); 1920 titleView.setText(extra); 1921 menu.setHeaderView(titleView); 1922 // decide whether to show the open link in new tab option 1923 menu.findItem(R.id.open_newtab_context_menu_id).setVisible( 1924 mTabControl.getTabCount() < TabControl.MAX_TABS); 1925 PackageManager pm = getPackageManager(); 1926 Intent send = new Intent(Intent.ACTION_SEND); 1927 send.setType("text/plain"); 1928 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY); 1929 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null); 1930 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) { 1931 break; 1932 } 1933 // otherwise fall through to handle image part 1934 case WebView.HitTestResult.IMAGE_TYPE: 1935 if (type == WebView.HitTestResult.IMAGE_TYPE) { 1936 menu.setHeaderTitle(extra); 1937 } 1938 menu.findItem(R.id.view_image_context_menu_id).setIntent( 1939 new Intent(Intent.ACTION_VIEW, Uri.parse(extra))); 1940 menu.findItem(R.id.download_context_menu_id). 1941 setOnMenuItemClickListener(new Download(extra)); 1942 break; 1943 1944 default: 1945 Log.w(LOGTAG, "We should not get here."); 1946 break; 1947 } 1948 } 1949 1950 // Attach the given tab to the content view. 1951 private void attachTabToContentView(TabControl.Tab t) { 1952 final WebView main = t.getWebView(); 1953 // Attach the main WebView. 1954 mContentView.addView(main, COVER_SCREEN_PARAMS); 1955 // Attach the sub window if necessary 1956 attachSubWindow(t); 1957 // Request focus on the top window. 1958 t.getTopWindow().requestFocus(); 1959 } 1960 1961 // Attach a sub window to the main WebView of the given tab. 1962 private void attachSubWindow(TabControl.Tab t) { 1963 // If a sub window exists, attach it to the content view. 1964 final WebView subView = t.getSubWebView(); 1965 if (subView != null) { 1966 final View container = t.getSubWebViewContainer(); 1967 mContentView.addView(container, COVER_SCREEN_PARAMS); 1968 subView.requestFocus(); 1969 } 1970 } 1971 1972 // Remove the given tab from the content view. 1973 private void removeTabFromContentView(TabControl.Tab t) { 1974 // Remove the main WebView. 1975 mContentView.removeView(t.getWebView()); 1976 // Remove the sub window if it exists. 1977 if (t.getSubWebView() != null) { 1978 mContentView.removeView(t.getSubWebViewContainer()); 1979 } 1980 } 1981 1982 // Remove the sub window if it exists. Also called by TabControl when the 1983 // user clicks the 'X' to dismiss a sub window. 1984 /* package */ void dismissSubWindow(TabControl.Tab t) { 1985 final WebView mainView = t.getWebView(); 1986 if (t.getSubWebView() != null) { 1987 // Remove the container view and request focus on the main WebView. 1988 mContentView.removeView(t.getSubWebViewContainer()); 1989 mainView.requestFocus(); 1990 // Tell the TabControl to dismiss the subwindow. This will destroy 1991 // the WebView. 1992 mTabControl.dismissSubWindow(t); 1993 } 1994 } 1995 1996 // Send the ANIMTE_FROM_OVERVIEW message after changing the current tab. 1997 private void sendAnimateFromOverview(final TabControl.Tab tab, 1998 final boolean newTab, final UrlData urlData, final int delay, 1999 final Message msg) { 2000 // Set the current tab. 2001 mTabControl.setCurrentTab(tab); 2002 // Attach the WebView so it will layout. 2003 attachTabToContentView(tab); 2004 // Set the view to invisibile for now. 2005 tab.getWebView().setVisibility(View.INVISIBLE); 2006 // If there is a sub window, make it invisible too. 2007 if (tab.getSubWebView() != null) { 2008 tab.getSubWebViewContainer().setVisibility(View.INVISIBLE); 2009 } 2010 // Create our fake animating view. 2011 final AnimatingView view = new AnimatingView(this, tab); 2012 // Attach it to the view system and make in invisible so it will 2013 // layout but not flash white on the screen. 2014 mContentView.addView(view, COVER_SCREEN_PARAMS); 2015 view.setVisibility(View.INVISIBLE); 2016 // Send the animate message. 2017 final HashMap map = new HashMap(); 2018 map.put("view", view); 2019 // Load the url after the AnimatingView has captured the picture. This 2020 // prevents any bad layout or bad scale from being used during 2021 // animation. 2022 if (!urlData.isEmpty()) { 2023 dismissSubWindow(tab); 2024 urlData.loadIn(tab.getWebView()); 2025 } 2026 map.put("msg", msg); 2027 mHandler.sendMessageDelayed(mHandler.obtainMessage( 2028 ANIMATE_FROM_OVERVIEW, newTab ? 1 : 0, 0, map), delay); 2029 // Increment the count to indicate that we are in an animation. 2030 mAnimationCount++; 2031 // Remove the listener so we don't get any more tab changes. 2032 mTabOverview.setListener(null); 2033 mTabListener = null; 2034 // Make the menu empty until the animation completes. 2035 mMenuState = EMPTY_MENU; 2036 2037 } 2038 2039 // 500ms animation with 800ms delay 2040 private static final int TAB_ANIMATION_DURATION = 200; 2041 private static final int TAB_OVERVIEW_DELAY = 500; 2042 2043 // Called by TabControl when a tab is requesting focus 2044 /* package */ void showTab(TabControl.Tab t) { 2045 showTab(t, EMPTY_URL_DATA); 2046 } 2047 2048 private void showTab(TabControl.Tab t, UrlData urlData) { 2049 // Disallow focus change during a tab animation. 2050 if (mAnimationCount > 0) { 2051 return; 2052 } 2053 int delay = 0; 2054 if (mTabOverview == null) { 2055 // Add a delay so the tab overview can be shown before the second 2056 // animation begins. 2057 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY; 2058 tabPicker(false, mTabControl.getTabIndex(t), false); 2059 } 2060 sendAnimateFromOverview(t, false, urlData, delay, null); 2061 } 2062 2063 // A wrapper function of {@link #openTabAndShow(UrlData, Message, boolean, String)} 2064 // that accepts url as string. 2065 private TabControl.Tab openTabAndShow(String url, final Message msg, 2066 boolean closeOnExit, String appId) { 2067 return openTabAndShow(new UrlData(url), msg, closeOnExit, appId); 2068 } 2069 2070 // This method does a ton of stuff. It will attempt to create a new tab 2071 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If 2072 // url isn't null, it will load the given url. If the tab overview is not 2073 // showing, it will animate to the tab overview, create a new tab and 2074 // animate away from it. After the animation completes, it will dispatch 2075 // the given Message. If the tab overview is already showing (i.e. this 2076 // method is called from TabListener.onClick(), the method will animate 2077 // away from the tab overview. 2078 private TabControl.Tab openTabAndShow(UrlData urlData, final Message msg, 2079 boolean closeOnExit, String appId) { 2080 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS; 2081 final TabControl.Tab currentTab = mTabControl.getCurrentTab(); 2082 if (newTab) { 2083 int delay = 0; 2084 // If the tab overview is up and there are animations, just load 2085 // the url. 2086 if (mTabOverview != null && mAnimationCount > 0) { 2087 if (!urlData.isEmpty()) { 2088 // We should not have a msg here since onCreateWindow 2089 // checks the animation count and every other caller passes 2090 // null. 2091 assert msg == null; 2092 // just dismiss the subwindow and load the given url. 2093 dismissSubWindow(currentTab); 2094 urlData.loadIn(currentTab.getWebView()); 2095 } 2096 } else { 2097 // show mTabOverview if it is not there. 2098 if (mTabOverview == null) { 2099 // We have to delay the animation from the tab picker by the 2100 // length of the tab animation. Add a delay so the tab 2101 // overview can be shown before the second animation begins. 2102 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY; 2103 tabPicker(false, ImageGrid.NEW_TAB, false); 2104 } 2105 // Animate from the Tab overview after any animations have 2106 // finished. 2107 final TabControl.Tab tab = mTabControl.createNewTab( 2108 closeOnExit, appId, urlData.mUrl); 2109 sendAnimateFromOverview(tab, true, urlData, delay, msg); 2110 return tab; 2111 } 2112 } else if (!urlData.isEmpty()) { 2113 // We should not have a msg here. 2114 assert msg == null; 2115 if (mTabOverview != null && mAnimationCount == 0) { 2116 sendAnimateFromOverview(currentTab, false, urlData, 2117 TAB_OVERVIEW_DELAY, null); 2118 } else { 2119 // Get rid of the subwindow if it exists 2120 dismissSubWindow(currentTab); 2121 // Load the given url. 2122 urlData.loadIn(currentTab.getWebView()); 2123 } 2124 } 2125 return currentTab; 2126 } 2127 2128 private Animation createTabAnimation(final AnimatingView view, 2129 final View cell, boolean scaleDown) { 2130 final AnimationSet set = new AnimationSet(true); 2131 final float scaleX = (float) cell.getWidth() / view.getWidth(); 2132 final float scaleY = (float) cell.getHeight() / view.getHeight(); 2133 if (scaleDown) { 2134 set.addAnimation(new ScaleAnimation(1.0f, scaleX, 1.0f, scaleY)); 2135 set.addAnimation(new TranslateAnimation(0, cell.getLeft(), 0, 2136 cell.getTop())); 2137 } else { 2138 set.addAnimation(new ScaleAnimation(scaleX, 1.0f, scaleY, 1.0f)); 2139 set.addAnimation(new TranslateAnimation(cell.getLeft(), 0, 2140 cell.getTop(), 0)); 2141 } 2142 set.setDuration(TAB_ANIMATION_DURATION); 2143 set.setInterpolator(new DecelerateInterpolator()); 2144 return set; 2145 } 2146 2147 // Animate to the tab overview. currentIndex tells us which position to 2148 // animate to and newIndex is the position that should be selected after 2149 // the animation completes. 2150 // If remove is true, after the animation stops, a confirmation dialog will 2151 // be displayed to the user. 2152 private void animateToTabOverview(final int newIndex, final boolean remove, 2153 final AnimatingView view) { 2154 // Find the view in the ImageGrid allowing for the "New Tab" cell. 2155 int position = mTabControl.getTabIndex(view.mTab); 2156 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) { 2157 position++; 2158 } 2159 2160 // Offset the tab position with the first visible position to get a 2161 // number between 0 and 3. 2162 position -= mTabOverview.getFirstVisiblePosition(); 2163 2164 // Grab the view that we are going to animate to. 2165 final View v = mTabOverview.getChildAt(position); 2166 2167 final Animation.AnimationListener l = 2168 new Animation.AnimationListener() { 2169 public void onAnimationStart(Animation a) { 2170 if (mTabOverview != null) { 2171 mTabOverview.requestFocus(); 2172 // Clear the listener so we don't trigger a tab 2173 // selection. 2174 mTabOverview.setListener(null); 2175 } 2176 } 2177 public void onAnimationRepeat(Animation a) {} 2178 public void onAnimationEnd(Animation a) { 2179 // We are no longer animating so decrement the count. 2180 mAnimationCount--; 2181 // Make the view GONE so that it will not draw between 2182 // now and when the Runnable is handled. 2183 view.setVisibility(View.GONE); 2184 // Post a runnable since we can't modify the view 2185 // hierarchy during this callback. 2186 mHandler.post(new Runnable() { 2187 public void run() { 2188 // Remove the AnimatingView. 2189 mContentView.removeView(view); 2190 if (mTabOverview != null) { 2191 // Make newIndex visible. 2192 mTabOverview.setCurrentIndex(newIndex); 2193 // Restore the listener. 2194 mTabOverview.setListener(mTabListener); 2195 // Change the menu to TAB_MENU if the 2196 // ImageGrid is interactive. 2197 if (mTabOverview.isLive()) { 2198 mMenuState = R.id.TAB_MENU; 2199 mTabOverview.requestFocus(); 2200 } 2201 } 2202 // If a remove was requested, remove the tab. 2203 if (remove) { 2204 // During a remove, the current tab has 2205 // already changed. Remember the current one 2206 // here. 2207 final TabControl.Tab currentTab = 2208 mTabControl.getCurrentTab(); 2209 // Remove the tab at newIndex from 2210 // TabControl and the tab overview. 2211 final TabControl.Tab tab = 2212 mTabControl.getTab(newIndex); 2213 mTabControl.removeTab(tab); 2214 // Restore the current tab. 2215 if (currentTab != tab) { 2216 mTabControl.setCurrentTab(currentTab); 2217 } 2218 if (mTabOverview != null) { 2219 mTabOverview.remove(newIndex); 2220 // Make the current tab visible. 2221 mTabOverview.setCurrentIndex( 2222 mTabControl.getCurrentIndex()); 2223 } 2224 } 2225 } 2226 }); 2227 } 2228 }; 2229 2230 // Do an animation if there is a view to animate to. 2231 if (v != null) { 2232 // Create our animation 2233 final Animation anim = createTabAnimation(view, v, true); 2234 anim.setAnimationListener(l); 2235 // Start animating 2236 view.startAnimation(anim); 2237 } else { 2238 // If something goes wrong and we didn't find a view to animate to, 2239 // just do everything here. 2240 l.onAnimationStart(null); 2241 l.onAnimationEnd(null); 2242 } 2243 } 2244 2245 // Animate from the tab picker. The index supplied is the index to animate 2246 // from. 2247 private void animateFromTabOverview(final AnimatingView view, 2248 final boolean newTab, final Message msg) { 2249 // firstVisible is the first visible tab on the screen. This helps 2250 // to know which corner of the screen the selected tab is. 2251 int firstVisible = mTabOverview.getFirstVisiblePosition(); 2252 // tabPosition is the 0-based index of of the tab being opened 2253 int tabPosition = mTabControl.getTabIndex(view.mTab); 2254 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) { 2255 // Add one to make room for the "New Tab" cell. 2256 tabPosition++; 2257 } 2258 // If this is a new tab, animate from the "New Tab" cell. 2259 if (newTab) { 2260 tabPosition = 0; 2261 } 2262 // Location corresponds to the four corners of the screen. 2263 // A new tab or 0 is upper left, 0 for an old tab is upper 2264 // right, 1 is lower left, and 2 is lower right 2265 int location = tabPosition - firstVisible; 2266 2267 // Find the view at this location. 2268 final View v = mTabOverview.getChildAt(location); 2269 2270 // Wait until the animation completes to replace the AnimatingView. 2271 final Animation.AnimationListener l = 2272 new Animation.AnimationListener() { 2273 public void onAnimationStart(Animation a) {} 2274 public void onAnimationRepeat(Animation a) {} 2275 public void onAnimationEnd(Animation a) { 2276 mHandler.post(new Runnable() { 2277 public void run() { 2278 mContentView.removeView(view); 2279 // Dismiss the tab overview. If the cell at the 2280 // given location is null, set the fade 2281 // parameter to true. 2282 dismissTabOverview(v == null); 2283 TabControl.Tab t = 2284 mTabControl.getCurrentTab(); 2285 mMenuState = R.id.MAIN_MENU; 2286 // Resume regular updates. 2287 t.getWebView().resumeTimers(); 2288 // Dispatch the message after the animation 2289 // completes. 2290 if (msg != null) { 2291 msg.sendToTarget(); 2292 } 2293 // The animation is done and the tab overview is 2294 // gone so allow key events and other animations 2295 // to begin. 2296 mAnimationCount--; 2297 // Reset all the title bar info. 2298 resetTitle(); 2299 } 2300 }); 2301 } 2302 }; 2303 2304 if (v != null) { 2305 final Animation anim = createTabAnimation(view, v, false); 2306 // Set the listener and start animating 2307 anim.setAnimationListener(l); 2308 view.startAnimation(anim); 2309 // Make the view VISIBLE during the animation. 2310 view.setVisibility(View.VISIBLE); 2311 } else { 2312 // Go ahead and do all the cleanup. 2313 l.onAnimationEnd(null); 2314 } 2315 } 2316 2317 // Dismiss the tab overview applying a fade if needed. 2318 private void dismissTabOverview(final boolean fade) { 2319 if (fade) { 2320 AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f); 2321 anim.setDuration(500); 2322 anim.startNow(); 2323 mTabOverview.startAnimation(anim); 2324 } 2325 // Just in case there was a problem with animating away from the tab 2326 // overview 2327 WebView current = mTabControl.getCurrentWebView(); 2328 if (current != null) { 2329 current.setVisibility(View.VISIBLE); 2330 } else { 2331 Log.e(LOGTAG, "No current WebView in dismissTabOverview"); 2332 } 2333 // Make the sub window container visible. 2334 if (mTabControl.getCurrentSubWindow() != null) { 2335 mTabControl.getCurrentTab().getSubWebViewContainer() 2336 .setVisibility(View.VISIBLE); 2337 } 2338 mContentView.removeView(mTabOverview); 2339 // Clear all the data for tab picker so next time it will be 2340 // recreated. 2341 mTabControl.wipeAllPickerData(); 2342 mTabOverview.clear(); 2343 mTabOverview = null; 2344 mTabListener = null; 2345 } 2346 2347 private TabControl.Tab openTab(String url) { 2348 if (mSettings.openInBackground()) { 2349 TabControl.Tab t = mTabControl.createNewTab(); 2350 if (t != null) { 2351 t.getWebView().loadUrl(url); 2352 } 2353 return t; 2354 } else { 2355 return openTabAndShow(url, null, false, null); 2356 } 2357 } 2358 2359 private class Copy implements OnMenuItemClickListener { 2360 private CharSequence mText; 2361 2362 public boolean onMenuItemClick(MenuItem item) { 2363 copy(mText); 2364 return true; 2365 } 2366 2367 public Copy(CharSequence toCopy) { 2368 mText = toCopy; 2369 } 2370 } 2371 2372 private class Download implements OnMenuItemClickListener { 2373 private String mText; 2374 2375 public boolean onMenuItemClick(MenuItem item) { 2376 onDownloadStartNoStream(mText, null, null, null, -1); 2377 return true; 2378 } 2379 2380 public Download(String toDownload) { 2381 mText = toDownload; 2382 } 2383 } 2384 2385 private void copy(CharSequence text) { 2386 try { 2387 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard")); 2388 if (clip != null) { 2389 clip.setClipboardText(text); 2390 } 2391 } catch (android.os.RemoteException e) { 2392 Log.e(LOGTAG, "Copy failed", e); 2393 } 2394 } 2395 2396 /** 2397 * Resets the browser title-view to whatever it must be (for example, if we 2398 * load a page from history). 2399 */ 2400 private void resetTitle() { 2401 resetLockIcon(); 2402 resetTitleIconAndProgress(); 2403 } 2404 2405 /** 2406 * Resets the browser title-view to whatever it must be 2407 * (for example, if we had a loading error) 2408 * When we have a new page, we call resetTitle, when we 2409 * have to reset the titlebar to whatever it used to be 2410 * (for example, if the user chose to stop loading), we 2411 * call resetTitleAndRevertLockIcon. 2412 */ 2413 /* package */ void resetTitleAndRevertLockIcon() { 2414 revertLockIcon(); 2415 resetTitleIconAndProgress(); 2416 } 2417 2418 /** 2419 * Reset the title, favicon, and progress. 2420 */ 2421 private void resetTitleIconAndProgress() { 2422 WebView current = mTabControl.getCurrentWebView(); 2423 if (current == null) { 2424 return; 2425 } 2426 resetTitleAndIcon(current); 2427 int progress = current.getProgress(); 2428 mWebChromeClient.onProgressChanged(current, progress); 2429 } 2430 2431 // Reset the title and the icon based on the given item. 2432 private void resetTitleAndIcon(WebView view) { 2433 WebHistoryItem item = view.copyBackForwardList().getCurrentItem(); 2434 if (item != null) { 2435 setUrlTitle(item.getUrl(), item.getTitle()); 2436 setFavicon(item.getFavicon()); 2437 } else { 2438 setUrlTitle(null, null); 2439 setFavicon(null); 2440 } 2441 } 2442 2443 /** 2444 * Sets a title composed of the URL and the title string. 2445 * @param url The URL of the site being loaded. 2446 * @param title The title of the site being loaded. 2447 */ 2448 private void setUrlTitle(String url, String title) { 2449 mUrl = url; 2450 mTitle = title; 2451 2452 // While the tab overview is animating or being shown, block changes 2453 // to the title. 2454 if (mAnimationCount == 0 && mTabOverview == null) { 2455 if (CUSTOM_BROWSER_BAR) { 2456 mTitleBar.setTitleAndUrl(title, url); 2457 } else { 2458 setTitle(buildUrlTitle(url, title)); 2459 } 2460 } 2461 } 2462 2463 /** 2464 * Builds and returns the page title, which is some 2465 * combination of the page URL and title. 2466 * @param url The URL of the site being loaded. 2467 * @param title The title of the site being loaded. 2468 * @return The page title. 2469 */ 2470 private String buildUrlTitle(String url, String title) { 2471 String urlTitle = ""; 2472 2473 if (url != null) { 2474 String titleUrl = buildTitleUrl(url); 2475 2476 if (title != null && 0 < title.length()) { 2477 if (titleUrl != null && 0 < titleUrl.length()) { 2478 urlTitle = titleUrl + ": " + title; 2479 } else { 2480 urlTitle = title; 2481 } 2482 } else { 2483 if (titleUrl != null) { 2484 urlTitle = titleUrl; 2485 } 2486 } 2487 } 2488 2489 return urlTitle; 2490 } 2491 2492 /** 2493 * @param url The URL to build a title version of the URL from. 2494 * @return The title version of the URL or null if fails. 2495 * The title version of the URL can be either the URL hostname, 2496 * or the hostname with an "https://" prefix (for secure URLs), 2497 * or an empty string if, for example, the URL in question is a 2498 * file:// URL with no hostname. 2499 */ 2500 /* package */ static String buildTitleUrl(String url) { 2501 String titleUrl = null; 2502 2503 if (url != null) { 2504 try { 2505 // parse the url string 2506 URL urlObj = new URL(url); 2507 if (urlObj != null) { 2508 titleUrl = ""; 2509 2510 String protocol = urlObj.getProtocol(); 2511 String host = urlObj.getHost(); 2512 2513 if (host != null && 0 < host.length()) { 2514 titleUrl = host; 2515 if (protocol != null) { 2516 // if a secure site, add an "https://" prefix! 2517 if (protocol.equalsIgnoreCase("https")) { 2518 titleUrl = protocol + "://" + host; 2519 } 2520 } 2521 } 2522 } 2523 } catch (MalformedURLException e) {} 2524 } 2525 2526 return titleUrl; 2527 } 2528 2529 // Set the favicon in the title bar. 2530 private void setFavicon(Bitmap icon) { 2531 // While the tab overview is animating or being shown, block changes to 2532 // the favicon. 2533 if (mAnimationCount > 0 || mTabOverview != null) { 2534 return; 2535 } 2536 if (CUSTOM_BROWSER_BAR) { 2537 Drawable[] array = new Drawable[3]; 2538 array[0] = new PaintDrawable(Color.BLACK); 2539 PaintDrawable p = new PaintDrawable(Color.WHITE); 2540 array[1] = p; 2541 if (icon == null) { 2542 array[2] = mGenericFavicon; 2543 } else { 2544 array[2] = new BitmapDrawable(icon); 2545 } 2546 LayerDrawable d = new LayerDrawable(array); 2547 d.setLayerInset(1, 1, 1, 1, 1); 2548 d.setLayerInset(2, 2, 2, 2, 2); 2549 mTitleBar.setFavicon(d); 2550 } else { 2551 Drawable[] array = new Drawable[2]; 2552 PaintDrawable p = new PaintDrawable(Color.WHITE); 2553 p.setCornerRadius(3f); 2554 array[0] = p; 2555 if (icon == null) { 2556 array[1] = mGenericFavicon; 2557 } else { 2558 array[1] = new BitmapDrawable(icon); 2559 } 2560 LayerDrawable d = new LayerDrawable(array); 2561 d.setLayerInset(1, 2, 2, 2, 2); 2562 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, d); 2563 } 2564 } 2565 2566 /** 2567 * Saves the current lock-icon state before resetting 2568 * the lock icon. If we have an error, we may need to 2569 * roll back to the previous state. 2570 */ 2571 private void saveLockIcon() { 2572 mPrevLockType = mLockIconType; 2573 } 2574 2575 /** 2576 * Reverts the lock-icon state to the last saved state, 2577 * for example, if we had an error, and need to cancel 2578 * the load. 2579 */ 2580 private void revertLockIcon() { 2581 mLockIconType = mPrevLockType; 2582 2583 if (LOGV_ENABLED) { 2584 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" + 2585 " revert lock icon to " + mLockIconType); 2586 } 2587 2588 updateLockIconImage(mLockIconType); 2589 } 2590 2591 private void switchTabs(int indexFrom, int indexToShow, boolean remove) { 2592 int delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY; 2593 // Animate to the tab picker, remove the current tab, then 2594 // animate away from the tab picker to the parent WebView. 2595 tabPicker(false, indexFrom, remove); 2596 // Change to the parent tab 2597 final TabControl.Tab tab = mTabControl.getTab(indexToShow); 2598 if (tab != null) { 2599 sendAnimateFromOverview(tab, false, EMPTY_URL_DATA, delay, null); 2600 } else { 2601 // Increment this here so that no other animations can happen in 2602 // between the end of the tab picker transition and the beginning 2603 // of openTabAndShow. This has a matching decrement in the handler 2604 // of OPEN_TAB_AND_SHOW. 2605 mAnimationCount++; 2606 // Send a message to open a new tab. 2607 mHandler.sendMessageDelayed( 2608 mHandler.obtainMessage(OPEN_TAB_AND_SHOW, 2609 mSettings.getHomePage()), delay); 2610 } 2611 } 2612 2613 private void goBackOnePageOrQuit() { 2614 TabControl.Tab current = mTabControl.getCurrentTab(); 2615 if (current == null) { 2616 /* 2617 * Instead of finishing the activity, simply push this to the back 2618 * of the stack and let ActivityManager to choose the foreground 2619 * activity. As BrowserActivity is singleTask, it will be always the 2620 * root of the task. So we can use either true or false for 2621 * moveTaskToBack(). 2622 */ 2623 moveTaskToBack(true); 2624 } 2625 WebView w = current.getWebView(); 2626 if (w.canGoBack()) { 2627 w.goBack(); 2628 } else { 2629 // Check to see if we are closing a window that was created by 2630 // another window. If so, we switch back to that window. 2631 TabControl.Tab parent = current.getParentTab(); 2632 if (parent != null) { 2633 switchTabs(mTabControl.getCurrentIndex(), 2634 mTabControl.getTabIndex(parent), true); 2635 } else { 2636 if (current.closeOnExit()) { 2637 if (mTabControl.getTabCount() == 1) { 2638 finish(); 2639 return; 2640 } 2641 // call pauseWebViewTimers() now, we won't be able to call 2642 // it in onPause() as the WebView won't be valid. 2643 pauseWebViewTimers(); 2644 removeTabFromContentView(current); 2645 mTabControl.removeTab(current); 2646 } 2647 /* 2648 * Instead of finishing the activity, simply push this to the back 2649 * of the stack and let ActivityManager to choose the foreground 2650 * activity. As BrowserActivity is singleTask, it will be always the 2651 * root of the task. So we can use either true or false for 2652 * moveTaskToBack(). 2653 */ 2654 moveTaskToBack(true); 2655 } 2656 } 2657 } 2658 2659 public KeyTracker.State onKeyTracker(int keyCode, 2660 KeyEvent event, 2661 KeyTracker.Stage stage, 2662 int duration) { 2663 // if onKeyTracker() is called after activity onStop() 2664 // because of accumulated key events, 2665 // we should ignore it as browser is not active any more. 2666 WebView topWindow = getTopWindow(); 2667 if (topWindow == null && mCustomView == null) 2668 return KeyTracker.State.NOT_TRACKING; 2669 2670 if (keyCode == KeyEvent.KEYCODE_BACK) { 2671 // Check if a custom view is currently showing and, if it is, hide it. 2672 if (mCustomView != null) { 2673 mWebChromeClient.onHideCustomView(); 2674 return KeyTracker.State.DONE_TRACKING; 2675 } 2676 // During animations, block the back key so that other animations 2677 // are not triggered and so that we don't end up destroying all the 2678 // WebViews before finishing the animation. 2679 if (mAnimationCount > 0) { 2680 return KeyTracker.State.DONE_TRACKING; 2681 } 2682 if (stage == KeyTracker.Stage.LONG_REPEAT) { 2683 bookmarksOrHistoryPicker(true); 2684 return KeyTracker.State.DONE_TRACKING; 2685 } else if (stage == KeyTracker.Stage.UP) { 2686 // FIXME: Currently, we do not have a notion of the 2687 // history picker for the subwindow, but maybe we 2688 // should? 2689 WebView subwindow = mTabControl.getCurrentSubWindow(); 2690 if (subwindow != null) { 2691 if (subwindow.canGoBack()) { 2692 subwindow.goBack(); 2693 } else { 2694 dismissSubWindow(mTabControl.getCurrentTab()); 2695 } 2696 } else { 2697 goBackOnePageOrQuit(); 2698 } 2699 return KeyTracker.State.DONE_TRACKING; 2700 } 2701 return KeyTracker.State.KEEP_TRACKING; 2702 } 2703 return KeyTracker.State.NOT_TRACKING; 2704 } 2705 2706 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { 2707 if (keyCode == KeyEvent.KEYCODE_MENU) { 2708 mMenuIsDown = true; 2709 } 2710 boolean handled = mKeyTracker.doKeyDown(keyCode, event); 2711 if (!handled) { 2712 switch (keyCode) { 2713 case KeyEvent.KEYCODE_SPACE: 2714 if (event.isShiftPressed()) { 2715 getTopWindow().pageUp(false); 2716 } else { 2717 getTopWindow().pageDown(false); 2718 } 2719 handled = true; 2720 break; 2721 2722 default: 2723 break; 2724 } 2725 } 2726 return handled || super.onKeyDown(keyCode, event); 2727 } 2728 2729 @Override public boolean onKeyUp(int keyCode, KeyEvent event) { 2730 if (keyCode == KeyEvent.KEYCODE_MENU) { 2731 mMenuIsDown = false; 2732 } 2733 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event); 2734 } 2735 2736 private void stopLoading() { 2737 resetTitleAndRevertLockIcon(); 2738 WebView w = getTopWindow(); 2739 w.stopLoading(); 2740 mWebViewClient.onPageFinished(w, w.getUrl()); 2741 2742 cancelStopToast(); 2743 mStopToast = Toast 2744 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT); 2745 mStopToast.show(); 2746 } 2747 2748 private void cancelStopToast() { 2749 if (mStopToast != null) { 2750 mStopToast.cancel(); 2751 mStopToast = null; 2752 } 2753 } 2754 2755 // called by a non-UI thread to post the message 2756 public void postMessage(int what, int arg1, int arg2, Object obj) { 2757 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj)); 2758 } 2759 2760 // public message ids 2761 public final static int LOAD_URL = 1001; 2762 public final static int STOP_LOAD = 1002; 2763 2764 // Message Ids 2765 private static final int FOCUS_NODE_HREF = 102; 2766 private static final int CANCEL_CREDS_REQUEST = 103; 2767 private static final int ANIMATE_FROM_OVERVIEW = 104; 2768 private static final int ANIMATE_TO_OVERVIEW = 105; 2769 private static final int OPEN_TAB_AND_SHOW = 106; 2770 private static final int CHECK_MEMORY = 107; 2771 private static final int RELEASE_WAKELOCK = 108; 2772 2773 // Private handler for handling javascript and saving passwords 2774 private Handler mHandler = new Handler() { 2775 2776 public void handleMessage(Message msg) { 2777 switch (msg.what) { 2778 case ANIMATE_FROM_OVERVIEW: 2779 final HashMap map = (HashMap) msg.obj; 2780 animateFromTabOverview((AnimatingView) map.get("view"), 2781 msg.arg1 == 1, (Message) map.get("msg")); 2782 break; 2783 2784 case ANIMATE_TO_OVERVIEW: 2785 animateToTabOverview(msg.arg1, msg.arg2 == 1, 2786 (AnimatingView) msg.obj); 2787 break; 2788 2789 case OPEN_TAB_AND_SHOW: 2790 // Decrement mAnimationCount before openTabAndShow because 2791 // the method relies on the value being 0 to start the next 2792 // animation. 2793 mAnimationCount--; 2794 openTabAndShow((String) msg.obj, null, false, null); 2795 break; 2796 2797 case FOCUS_NODE_HREF: 2798 String url = (String) msg.getData().get("url"); 2799 if (url == null || url.length() == 0) { 2800 break; 2801 } 2802 HashMap focusNodeMap = (HashMap) msg.obj; 2803 WebView view = (WebView) focusNodeMap.get("webview"); 2804 // Only apply the action if the top window did not change. 2805 if (getTopWindow() != view) { 2806 break; 2807 } 2808 switch (msg.arg1) { 2809 case R.id.open_context_menu_id: 2810 case R.id.view_image_context_menu_id: 2811 loadURL(getTopWindow(), url); 2812 break; 2813 case R.id.open_newtab_context_menu_id: 2814 final TabControl.Tab parent = mTabControl 2815 .getCurrentTab(); 2816 final TabControl.Tab newTab = openTab(url); 2817 if (newTab != parent) { 2818 parent.addChildTab(newTab); 2819 } 2820 break; 2821 case R.id.bookmark_context_menu_id: 2822 Intent intent = new Intent(BrowserActivity.this, 2823 AddBookmarkPage.class); 2824 intent.putExtra("url", url); 2825 startActivity(intent); 2826 break; 2827 case R.id.share_link_context_menu_id: 2828 Browser.sendString(BrowserActivity.this, url); 2829 break; 2830 case R.id.copy_link_context_menu_id: 2831 copy(url); 2832 break; 2833 case R.id.save_link_context_menu_id: 2834 case R.id.download_context_menu_id: 2835 onDownloadStartNoStream(url, null, null, null, -1); 2836 break; 2837 } 2838 break; 2839 2840 case LOAD_URL: 2841 loadURL(getTopWindow(), (String) msg.obj); 2842 break; 2843 2844 case STOP_LOAD: 2845 stopLoading(); 2846 break; 2847 2848 case CANCEL_CREDS_REQUEST: 2849 resumeAfterCredentials(); 2850 break; 2851 2852 case CHECK_MEMORY: 2853 // reschedule to check memory condition 2854 mHandler.removeMessages(CHECK_MEMORY); 2855 mHandler.sendMessageDelayed(mHandler.obtainMessage 2856 (CHECK_MEMORY), CHECK_MEMORY_INTERVAL); 2857 checkMemory(); 2858 break; 2859 2860 case RELEASE_WAKELOCK: 2861 if (mWakeLock.isHeld()) { 2862 mWakeLock.release(); 2863 } 2864 break; 2865 } 2866 } 2867 }; 2868 2869 // ------------------------------------------------------------------------- 2870 // WebViewClient implementation. 2871 //------------------------------------------------------------------------- 2872 2873 // Use in overrideUrlLoading 2874 /* package */ final static String SCHEME_WTAI = "wtai://wp/"; 2875 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;"; 2876 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;"; 2877 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;"; 2878 2879 /* package */ WebViewClient getWebViewClient() { 2880 return mWebViewClient; 2881 } 2882 2883 private void updateIcon(String url, Bitmap icon) { 2884 if (icon != null) { 2885 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver, 2886 url, icon); 2887 } 2888 setFavicon(icon); 2889 } 2890 2891 private final WebViewClient mWebViewClient = new WebViewClient() { 2892 @Override 2893 public void onPageStarted(WebView view, String url, Bitmap favicon) { 2894 resetLockIcon(url); 2895 setUrlTitle(url, null); 2896 // Call updateIcon instead of setFavicon so the bookmark 2897 // database can be updated. 2898 updateIcon(url, favicon); 2899 2900 if (mSettings.isTracing() == true) { 2901 // FIXME: we should save the trace file somewhere other than data. 2902 // I can't use "/tmp" as it competes for system memory. 2903 File file = getDir("browserTrace", 0); 2904 String baseDir = file.getPath(); 2905 if (!baseDir.endsWith(File.separator)) baseDir += File.separator; 2906 String host; 2907 try { 2908 WebAddress uri = new WebAddress(url); 2909 host = uri.mHost; 2910 } catch (android.net.ParseException ex) { 2911 host = "unknown_host"; 2912 } 2913 host = host.replace('.', '_'); 2914 baseDir = baseDir + host; 2915 file = new File(baseDir+".data"); 2916 if (file.exists() == true) { 2917 file.delete(); 2918 } 2919 file = new File(baseDir+".key"); 2920 if (file.exists() == true) { 2921 file.delete(); 2922 } 2923 mInTrace = true; 2924 Debug.startMethodTracing(baseDir, 8 * 1024 * 1024); 2925 } 2926 2927 // Performance probe 2928 if (false) { 2929 mStart = SystemClock.uptimeMillis(); 2930 mProcessStart = Process.getElapsedCpuTime(); 2931 long[] sysCpu = new long[7]; 2932 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null, 2933 sysCpu, null)) { 2934 mUserStart = sysCpu[0] + sysCpu[1]; 2935 mSystemStart = sysCpu[2]; 2936 mIdleStart = sysCpu[3]; 2937 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6]; 2938 } 2939 mUiStart = SystemClock.currentThreadTimeMillis(); 2940 } 2941 2942 if (!mPageStarted) { 2943 mPageStarted = true; 2944 // if onResume() has been called, resumeWebViewTimers() does 2945 // nothing. 2946 resumeWebViewTimers(); 2947 } 2948 2949 // reset sync timer to avoid sync starts during loading a page 2950 CookieSyncManager.getInstance().resetSync(); 2951 2952 mInLoad = true; 2953 updateInLoadMenuItems(); 2954 if (!mIsNetworkUp) { 2955 if ( mAlertDialog == null) { 2956 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this) 2957 .setTitle(R.string.loadSuspendedTitle) 2958 .setMessage(R.string.loadSuspended) 2959 .setPositiveButton(R.string.ok, null) 2960 .show(); 2961 } 2962 if (view != null) { 2963 view.setNetworkAvailable(false); 2964 } 2965 } 2966 2967 // schedule to check memory condition 2968 mHandler.sendMessageDelayed(mHandler.obtainMessage(CHECK_MEMORY), 2969 CHECK_MEMORY_INTERVAL); 2970 } 2971 2972 @Override 2973 public void onPageFinished(WebView view, String url) { 2974 // Reset the title and icon in case we stopped a provisional 2975 // load. 2976 resetTitleAndIcon(view); 2977 2978 // Update the lock icon image only once we are done loading 2979 updateLockIconImage(mLockIconType); 2980 2981 // If this is a bookmarked site, add a screenshot to the database. 2982 // FIXME: When should we update? Every time? 2983 String original = view.getOriginalUrl(); 2984 if (original != null) { 2985 // copied from BrowserBookmarksAdapter 2986 int query = original.indexOf('?'); 2987 String noQuery = original; 2988 if (query != -1) { 2989 noQuery = original.substring(0, query); 2990 } 2991 String URL = noQuery + '?'; 2992 String[] selArgs = new String[] { noQuery, URL }; 2993 final String where = "(url == ? OR url GLOB ? || '*') AND bookmark == 1"; 2994 final String[] projection = new String[] { Browser.BookmarkColumns._ID }; 2995 ContentResolver cr = getContentResolver(); 2996 final Cursor c = cr.query(Browser.BOOKMARKS_URI, projection, where, selArgs, null); 2997 boolean succeed = c.moveToFirst(); 2998 ContentValues values = null; 2999 while (succeed) { 3000 if (values == null) { 3001 final ByteArrayOutputStream os = new ByteArrayOutputStream(); 3002 Picture thumbnail = view.capturePicture(); 3003 // Height was arbitrarily chosen 3004 Bitmap bm = Bitmap.createBitmap(100, 100, 3005 Bitmap.Config.ARGB_4444); 3006 Canvas canvas = new Canvas(bm); 3007 // Scale chosen to be about one third, since we want 3008 // roughly three rows/columns for bookmark page 3009 canvas.scale(.3f, .3f); 3010 thumbnail.draw(canvas); 3011 bm.compress(Bitmap.CompressFormat.PNG, 100, os); 3012 values = new ContentValues(); 3013 values.put(Browser.BookmarkColumns.THUMBNAIL, 3014 os.toByteArray()); 3015 } 3016 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI, 3017 c.getInt(0)), values, null, null); 3018 succeed = c.moveToNext(); 3019 } 3020 c.close(); 3021 } 3022 3023 // Performance probe 3024 if (false) { 3025 long[] sysCpu = new long[7]; 3026 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null, 3027 sysCpu, null)) { 3028 String uiInfo = "UI thread used " 3029 + (SystemClock.currentThreadTimeMillis() - mUiStart) 3030 + " ms"; 3031 if (LOGD_ENABLED) { 3032 Log.d(LOGTAG, uiInfo); 3033 } 3034 //The string that gets written to the log 3035 String performanceString = "It took total " 3036 + (SystemClock.uptimeMillis() - mStart) 3037 + " ms clock time to load the page." 3038 + "\nbrowser process used " 3039 + (Process.getElapsedCpuTime() - mProcessStart) 3040 + " ms, user processes used " 3041 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10 3042 + " ms, kernel used " 3043 + (sysCpu[2] - mSystemStart) * 10 3044 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10 3045 + " ms and irq took " 3046 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart) 3047 * 10 + " ms, " + uiInfo; 3048 if (LOGD_ENABLED) { 3049 Log.d(LOGTAG, performanceString + "\nWebpage: " + url); 3050 } 3051 if (url != null) { 3052 // strip the url to maintain consistency 3053 String newUrl = new String(url); 3054 if (newUrl.startsWith("http://www.")) { 3055 newUrl = newUrl.substring(11); 3056 } else if (newUrl.startsWith("http://")) { 3057 newUrl = newUrl.substring(7); 3058 } else if (newUrl.startsWith("https://www.")) { 3059 newUrl = newUrl.substring(12); 3060 } else if (newUrl.startsWith("https://")) { 3061 newUrl = newUrl.substring(8); 3062 } 3063 if (LOGD_ENABLED) { 3064 Log.d(LOGTAG, newUrl + " loaded"); 3065 } 3066 /* 3067 if (sWhiteList.contains(newUrl)) { 3068 // The string that gets pushed to the statistcs 3069 // service 3070 performanceString = performanceString 3071 + "\nWebpage: " 3072 + newUrl 3073 + "\nCarrier: " 3074 + android.os.SystemProperties 3075 .get("gsm.sim.operator.alpha"); 3076 if (mWebView != null 3077 && mWebView.getContext() != null 3078 && mWebView.getContext().getSystemService( 3079 Context.CONNECTIVITY_SERVICE) != null) { 3080 ConnectivityManager cManager = 3081 (ConnectivityManager) mWebView 3082 .getContext().getSystemService( 3083 Context.CONNECTIVITY_SERVICE); 3084 NetworkInfo nInfo = cManager 3085 .getActiveNetworkInfo(); 3086 if (nInfo != null) { 3087 performanceString = performanceString 3088 + "\nNetwork Type: " 3089 + nInfo.getType().toString(); 3090 } 3091 } 3092 Checkin.logEvent(mResolver, 3093 Checkin.Events.Tag.WEBPAGE_LOAD, 3094 performanceString); 3095 Log.w(LOGTAG, "pushed to the statistics service"); 3096 } 3097 */ 3098 } 3099 } 3100 } 3101 3102 if (mInTrace) { 3103 mInTrace = false; 3104 Debug.stopMethodTracing(); 3105 } 3106 3107 if (mPageStarted) { 3108 mPageStarted = false; 3109 // pauseWebViewTimers() will do nothing and return false if 3110 // onPause() is not called yet. 3111 if (pauseWebViewTimers()) { 3112 if (mWakeLock.isHeld()) { 3113 mHandler.removeMessages(RELEASE_WAKELOCK); 3114 mWakeLock.release(); 3115 } 3116 } 3117 } 3118 3119 mHandler.removeMessages(CHECK_MEMORY); 3120 checkMemory(); 3121 } 3122 3123 // return true if want to hijack the url to let another app to handle it 3124 @Override 3125 public boolean shouldOverrideUrlLoading(WebView view, String url) { 3126 if (url.startsWith(SCHEME_WTAI)) { 3127 // wtai://wp/mc;number 3128 // number=string(phone-number) 3129 if (url.startsWith(SCHEME_WTAI_MC)) { 3130 Intent intent = new Intent(Intent.ACTION_VIEW, 3131 Uri.parse(WebView.SCHEME_TEL + 3132 url.substring(SCHEME_WTAI_MC.length()))); 3133 startActivity(intent); 3134 return true; 3135 } 3136 // wtai://wp/sd;dtmf 3137 // dtmf=string(dialstring) 3138 if (url.startsWith(SCHEME_WTAI_SD)) { 3139 // TODO 3140 // only send when there is active voice connection 3141 return false; 3142 } 3143 // wtai://wp/ap;number;name 3144 // number=string(phone-number) 3145 // name=string 3146 if (url.startsWith(SCHEME_WTAI_AP)) { 3147 // TODO 3148 return false; 3149 } 3150 } 3151 3152 // The "about:" schemes are internal to the browser; don't 3153 // want these to be dispatched to other apps. 3154 if (url.startsWith("about:")) { 3155 return false; 3156 } 3157 3158 Intent intent; 3159 3160 // perform generic parsing of the URI to turn it into an Intent. 3161 try { 3162 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME); 3163 } catch (URISyntaxException ex) { 3164 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage()); 3165 return false; 3166 } 3167 3168 // check whether the intent can be resolved. If not, we will see 3169 // whether we can download it from the Market. 3170 if (getPackageManager().resolveActivity(intent, 0) == null) { 3171 String packagename = intent.getPackage(); 3172 if (packagename != null) { 3173 intent = new Intent(Intent.ACTION_VIEW, Uri 3174 .parse("market://search?q=pname:" + packagename)); 3175 intent.addCategory(Intent.CATEGORY_BROWSABLE); 3176 startActivity(intent); 3177 return true; 3178 } else { 3179 return false; 3180 } 3181 } 3182 3183 // sanitize the Intent, ensuring web pages can not bypass browser 3184 // security (only access to BROWSABLE activities). 3185 intent.addCategory(Intent.CATEGORY_BROWSABLE); 3186 intent.setComponent(null); 3187 try { 3188 if (startActivityIfNeeded(intent, -1)) { 3189 return true; 3190 } 3191 } catch (ActivityNotFoundException ex) { 3192 // ignore the error. If no application can handle the URL, 3193 // eg about:blank, assume the browser can handle it. 3194 } 3195 3196 if (mMenuIsDown) { 3197 openTab(url); 3198 closeOptionsMenu(); 3199 return true; 3200 } 3201 3202 return false; 3203 } 3204 3205 /** 3206 * Updates the lock icon. This method is called when we discover another 3207 * resource to be loaded for this page (for example, javascript). While 3208 * we update the icon type, we do not update the lock icon itself until 3209 * we are done loading, it is slightly more secure this way. 3210 */ 3211 @Override 3212 public void onLoadResource(WebView view, String url) { 3213 if (url != null && url.length() > 0) { 3214 // It is only if the page claims to be secure 3215 // that we may have to update the lock: 3216 if (mLockIconType == LOCK_ICON_SECURE) { 3217 // If NOT a 'safe' url, change the lock to mixed content! 3218 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) { 3219 mLockIconType = LOCK_ICON_MIXED; 3220 if (LOGV_ENABLED) { 3221 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" + 3222 " updated lock icon to " + mLockIconType + " due to " + url); 3223 } 3224 } 3225 } 3226 } 3227 } 3228 3229 /** 3230 * Show the dialog, asking the user if they would like to continue after 3231 * an excessive number of HTTP redirects. 3232 */ 3233 @Override 3234 public void onTooManyRedirects(WebView view, final Message cancelMsg, 3235 final Message continueMsg) { 3236 new AlertDialog.Builder(BrowserActivity.this) 3237 .setTitle(R.string.browserFrameRedirect) 3238 .setMessage(R.string.browserFrame307Post) 3239 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { 3240 public void onClick(DialogInterface dialog, int which) { 3241 continueMsg.sendToTarget(); 3242 }}) 3243 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { 3244 public void onClick(DialogInterface dialog, int which) { 3245 cancelMsg.sendToTarget(); 3246 }}) 3247 .setOnCancelListener(new OnCancelListener() { 3248 public void onCancel(DialogInterface dialog) { 3249 cancelMsg.sendToTarget(); 3250 }}) 3251 .show(); 3252 } 3253 3254 // Container class for the next error dialog that needs to be 3255 // displayed. 3256 class ErrorDialog { 3257 public final int mTitle; 3258 public final String mDescription; 3259 public final int mError; 3260 ErrorDialog(int title, String desc, int error) { 3261 mTitle = title; 3262 mDescription = desc; 3263 mError = error; 3264 } 3265 }; 3266 3267 private void processNextError() { 3268 if (mQueuedErrors == null) { 3269 return; 3270 } 3271 // The first one is currently displayed so just remove it. 3272 mQueuedErrors.removeFirst(); 3273 if (mQueuedErrors.size() == 0) { 3274 mQueuedErrors = null; 3275 return; 3276 } 3277 showError(mQueuedErrors.getFirst()); 3278 } 3279 3280 private DialogInterface.OnDismissListener mDialogListener = 3281 new DialogInterface.OnDismissListener() { 3282 public void onDismiss(DialogInterface d) { 3283 processNextError(); 3284 } 3285 }; 3286 private LinkedList<ErrorDialog> mQueuedErrors; 3287 3288 private void queueError(int err, String desc) { 3289 if (mQueuedErrors == null) { 3290 mQueuedErrors = new LinkedList<ErrorDialog>(); 3291 } 3292 for (ErrorDialog d : mQueuedErrors) { 3293 if (d.mError == err) { 3294 // Already saw a similar error, ignore the new one. 3295 return; 3296 } 3297 } 3298 ErrorDialog errDialog = new ErrorDialog( 3299 err == EventHandler.FILE_NOT_FOUND_ERROR ? 3300 R.string.browserFrameFileErrorLabel : 3301 R.string.browserFrameNetworkErrorLabel, 3302 desc, err); 3303 mQueuedErrors.addLast(errDialog); 3304 3305 // Show the dialog now if the queue was empty. 3306 if (mQueuedErrors.size() == 1) { 3307 showError(errDialog); 3308 } 3309 } 3310 3311 private void showError(ErrorDialog errDialog) { 3312 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this) 3313 .setTitle(errDialog.mTitle) 3314 .setMessage(errDialog.mDescription) 3315 .setPositiveButton(R.string.ok, null) 3316 .create(); 3317 d.setOnDismissListener(mDialogListener); 3318 d.show(); 3319 } 3320 3321 /** 3322 * Show a dialog informing the user of the network error reported by 3323 * WebCore. 3324 */ 3325 @Override 3326 public void onReceivedError(WebView view, int errorCode, 3327 String description, String failingUrl) { 3328 if (errorCode != EventHandler.ERROR_LOOKUP && 3329 errorCode != EventHandler.ERROR_CONNECT && 3330 errorCode != EventHandler.ERROR_BAD_URL && 3331 errorCode != EventHandler.ERROR_UNSUPPORTED_SCHEME && 3332 errorCode != EventHandler.FILE_ERROR) { 3333 queueError(errorCode, description); 3334 } 3335 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl 3336 + " " + description); 3337 3338 // We need to reset the title after an error. 3339 resetTitleAndRevertLockIcon(); 3340 } 3341 3342 /** 3343 * Check with the user if it is ok to resend POST data as the page they 3344 * are trying to navigate to is the result of a POST. 3345 */ 3346 @Override 3347 public void onFormResubmission(WebView view, final Message dontResend, 3348 final Message resend) { 3349 new AlertDialog.Builder(BrowserActivity.this) 3350 .setTitle(R.string.browserFrameFormResubmitLabel) 3351 .setMessage(R.string.browserFrameFormResubmitMessage) 3352 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { 3353 public void onClick(DialogInterface dialog, int which) { 3354 resend.sendToTarget(); 3355 }}) 3356 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { 3357 public void onClick(DialogInterface dialog, int which) { 3358 dontResend.sendToTarget(); 3359 }}) 3360 .setOnCancelListener(new OnCancelListener() { 3361 public void onCancel(DialogInterface dialog) { 3362 dontResend.sendToTarget(); 3363 }}) 3364 .show(); 3365 } 3366 3367 /** 3368 * Insert the url into the visited history database. 3369 * @param url The url to be inserted. 3370 * @param isReload True if this url is being reloaded. 3371 * FIXME: Not sure what to do when reloading the page. 3372 */ 3373 @Override 3374 public void doUpdateVisitedHistory(WebView view, String url, 3375 boolean isReload) { 3376 if (url.regionMatches(true, 0, "about:", 0, 6)) { 3377 return; 3378 } 3379 Browser.updateVisitedHistory(mResolver, url, true); 3380 WebIconDatabase.getInstance().retainIconForPageUrl(url); 3381 } 3382 3383 /** 3384 * Displays SSL error(s) dialog to the user. 3385 */ 3386 @Override 3387 public void onReceivedSslError( 3388 final WebView view, final SslErrorHandler handler, final SslError error) { 3389 3390 if (mSettings.showSecurityWarnings()) { 3391 final LayoutInflater factory = 3392 LayoutInflater.from(BrowserActivity.this); 3393 final View warningsView = 3394 factory.inflate(R.layout.ssl_warnings, null); 3395 final LinearLayout placeholder = 3396 (LinearLayout)warningsView.findViewById(R.id.placeholder); 3397 3398 if (error.hasError(SslError.SSL_UNTRUSTED)) { 3399 LinearLayout ll = (LinearLayout)factory 3400 .inflate(R.layout.ssl_warning, null); 3401 ((TextView)ll.findViewById(R.id.warning)) 3402 .setText(R.string.ssl_untrusted); 3403 placeholder.addView(ll); 3404 } 3405 3406 if (error.hasError(SslError.SSL_IDMISMATCH)) { 3407 LinearLayout ll = (LinearLayout)factory 3408 .inflate(R.layout.ssl_warning, null); 3409 ((TextView)ll.findViewById(R.id.warning)) 3410 .setText(R.string.ssl_mismatch); 3411 placeholder.addView(ll); 3412 } 3413 3414 if (error.hasError(SslError.SSL_EXPIRED)) { 3415 LinearLayout ll = (LinearLayout)factory 3416 .inflate(R.layout.ssl_warning, null); 3417 ((TextView)ll.findViewById(R.id.warning)) 3418 .setText(R.string.ssl_expired); 3419 placeholder.addView(ll); 3420 } 3421 3422 if (error.hasError(SslError.SSL_NOTYETVALID)) { 3423 LinearLayout ll = (LinearLayout)factory 3424 .inflate(R.layout.ssl_warning, null); 3425 ((TextView)ll.findViewById(R.id.warning)) 3426 .setText(R.string.ssl_not_yet_valid); 3427 placeholder.addView(ll); 3428 } 3429 3430 new AlertDialog.Builder(BrowserActivity.this) 3431 .setTitle(R.string.security_warning) 3432 .setIcon(android.R.drawable.ic_dialog_alert) 3433 .setView(warningsView) 3434 .setPositiveButton(R.string.ssl_continue, 3435 new DialogInterface.OnClickListener() { 3436 public void onClick(DialogInterface dialog, int whichButton) { 3437 handler.proceed(); 3438 } 3439 }) 3440 .setNeutralButton(R.string.view_certificate, 3441 new DialogInterface.OnClickListener() { 3442 public void onClick(DialogInterface dialog, int whichButton) { 3443 showSSLCertificateOnError(view, handler, error); 3444 } 3445 }) 3446 .setNegativeButton(R.string.cancel, 3447 new DialogInterface.OnClickListener() { 3448 public void onClick(DialogInterface dialog, int whichButton) { 3449 handler.cancel(); 3450 BrowserActivity.this.resetTitleAndRevertLockIcon(); 3451 } 3452 }) 3453 .setOnCancelListener( 3454 new DialogInterface.OnCancelListener() { 3455 public void onCancel(DialogInterface dialog) { 3456 handler.cancel(); 3457 BrowserActivity.this.resetTitleAndRevertLockIcon(); 3458 } 3459 }) 3460 .show(); 3461 } else { 3462 handler.proceed(); 3463 } 3464 } 3465 3466 /** 3467 * Handles an HTTP authentication request. 3468 * 3469 * @param handler The authentication handler 3470 * @param host The host 3471 * @param realm The realm 3472 */ 3473 @Override 3474 public void onReceivedHttpAuthRequest(WebView view, 3475 final HttpAuthHandler handler, final String host, final String realm) { 3476 String username = null; 3477 String password = null; 3478 3479 boolean reuseHttpAuthUsernamePassword = 3480 handler.useHttpAuthUsernamePassword(); 3481 3482 if (reuseHttpAuthUsernamePassword && 3483 (mTabControl.getCurrentWebView() != null)) { 3484 String[] credentials = 3485 mTabControl.getCurrentWebView() 3486 .getHttpAuthUsernamePassword(host, realm); 3487 if (credentials != null && credentials.length == 2) { 3488 username = credentials[0]; 3489 password = credentials[1]; 3490 } 3491 } 3492 3493 if (username != null && password != null) { 3494 handler.proceed(username, password); 3495 } else { 3496 showHttpAuthentication(handler, host, realm, null, null, null, 0); 3497 } 3498 } 3499 3500 @Override 3501 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) { 3502 if (mMenuIsDown) { 3503 // only check shortcut key when MENU is held 3504 return getWindow().isShortcutKey(event.getKeyCode(), event); 3505 } else { 3506 return false; 3507 } 3508 } 3509 3510 @Override 3511 public void onUnhandledKeyEvent(WebView view, KeyEvent event) { 3512 if (view != mTabControl.getCurrentTopWebView()) { 3513 return; 3514 } 3515 if (event.isDown()) { 3516 BrowserActivity.this.onKeyDown(event.getKeyCode(), event); 3517 } else { 3518 BrowserActivity.this.onKeyUp(event.getKeyCode(), event); 3519 } 3520 } 3521 }; 3522 3523 //-------------------------------------------------------------------------- 3524 // WebChromeClient implementation 3525 //-------------------------------------------------------------------------- 3526 3527 /* package */ WebChromeClient getWebChromeClient() { 3528 return mWebChromeClient; 3529 } 3530 3531 private final WebChromeClient mWebChromeClient = new WebChromeClient() { 3532 // Helper method to create a new tab or sub window. 3533 private void createWindow(final boolean dialog, final Message msg) { 3534 if (dialog) { 3535 mTabControl.createSubWindow(); 3536 final TabControl.Tab t = mTabControl.getCurrentTab(); 3537 attachSubWindow(t); 3538 WebView.WebViewTransport transport = 3539 (WebView.WebViewTransport) msg.obj; 3540 transport.setWebView(t.getSubWebView()); 3541 msg.sendToTarget(); 3542 } else { 3543 final TabControl.Tab parent = mTabControl.getCurrentTab(); 3544 // openTabAndShow will dispatch the message after creating the 3545 // new WebView. This will prevent another request from coming 3546 // in during the animation. 3547 final TabControl.Tab newTab = 3548 openTabAndShow(EMPTY_URL_DATA, msg, false, null); 3549 if (newTab != parent) { 3550 parent.addChildTab(newTab); 3551 } 3552 WebView.WebViewTransport transport = 3553 (WebView.WebViewTransport) msg.obj; 3554 transport.setWebView(mTabControl.getCurrentWebView()); 3555 } 3556 } 3557 3558 @Override 3559 public boolean onCreateWindow(WebView view, final boolean dialog, 3560 final boolean userGesture, final Message resultMsg) { 3561 // Ignore these requests during tab animations or if the tab 3562 // overview is showing. 3563 if (mAnimationCount > 0 || mTabOverview != null) { 3564 return false; 3565 } 3566 // Short-circuit if we can't create any more tabs or sub windows. 3567 if (dialog && mTabControl.getCurrentSubWindow() != null) { 3568 new AlertDialog.Builder(BrowserActivity.this) 3569 .setTitle(R.string.too_many_subwindows_dialog_title) 3570 .setIcon(android.R.drawable.ic_dialog_alert) 3571 .setMessage(R.string.too_many_subwindows_dialog_message) 3572 .setPositiveButton(R.string.ok, null) 3573 .show(); 3574 return false; 3575 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) { 3576 new AlertDialog.Builder(BrowserActivity.this) 3577 .setTitle(R.string.too_many_windows_dialog_title) 3578 .setIcon(android.R.drawable.ic_dialog_alert) 3579 .setMessage(R.string.too_many_windows_dialog_message) 3580 .setPositiveButton(R.string.ok, null) 3581 .show(); 3582 return false; 3583 } 3584 3585 // Short-circuit if this was a user gesture. 3586 if (userGesture) { 3587 // createWindow will call openTabAndShow for new Windows and 3588 // that will call tabPicker which will increment 3589 // mAnimationCount. 3590 createWindow(dialog, resultMsg); 3591 return true; 3592 } 3593 3594 // Allow the popup and create the appropriate window. 3595 final AlertDialog.OnClickListener allowListener = 3596 new AlertDialog.OnClickListener() { 3597 public void onClick(DialogInterface d, 3598 int which) { 3599 // Same comment as above for setting 3600 // mAnimationCount. 3601 createWindow(dialog, resultMsg); 3602 // Since we incremented mAnimationCount while the 3603 // dialog was up, we have to decrement it here. 3604 mAnimationCount--; 3605 } 3606 }; 3607 3608 // Block the popup by returning a null WebView. 3609 final AlertDialog.OnClickListener blockListener = 3610 new AlertDialog.OnClickListener() { 3611 public void onClick(DialogInterface d, int which) { 3612 resultMsg.sendToTarget(); 3613 // We are not going to trigger an animation so 3614 // unblock keys and animation requests. 3615 mAnimationCount--; 3616 } 3617 }; 3618 3619 // Build a confirmation dialog to display to the user. 3620 final AlertDialog d = 3621 new AlertDialog.Builder(BrowserActivity.this) 3622 .setTitle(R.string.attention) 3623 .setIcon(android.R.drawable.ic_dialog_alert) 3624 .setMessage(R.string.popup_window_attempt) 3625 .setPositiveButton(R.string.allow, allowListener) 3626 .setNegativeButton(R.string.block, blockListener) 3627 .setCancelable(false) 3628 .create(); 3629 3630 // Show the confirmation dialog. 3631 d.show(); 3632 // We want to increment mAnimationCount here to prevent a 3633 // potential race condition. If the user allows a pop-up from a 3634 // site and that pop-up then triggers another pop-up, it is 3635 // possible to get the BACK key between here and when the dialog 3636 // appears. 3637 mAnimationCount++; 3638 return true; 3639 } 3640 3641 @Override 3642 public void onCloseWindow(WebView window) { 3643 final int currentIndex = mTabControl.getCurrentIndex(); 3644 final TabControl.Tab parent = 3645 mTabControl.getCurrentTab().getParentTab(); 3646 if (parent != null) { 3647 // JavaScript can only close popup window. 3648 switchTabs(currentIndex, mTabControl.getTabIndex(parent), true); 3649 } 3650 } 3651 3652 @Override 3653 public void onProgressChanged(WebView view, int newProgress) { 3654 // Block progress updates to the title bar while the tab overview 3655 // is animating or being displayed. 3656 if (mAnimationCount == 0 && mTabOverview == null) { 3657 if (CUSTOM_BROWSER_BAR) { 3658 mTitleBar.setProgress(newProgress); 3659 } else { 3660 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, 3661 newProgress * 100); 3662 3663 } 3664 } 3665 3666 if (newProgress == 100) { 3667 // onProgressChanged() is called for sub-frame too while 3668 // onPageFinished() is only called for the main frame. sync 3669 // cookie and cache promptly here. 3670 CookieSyncManager.getInstance().sync(); 3671 if (mInLoad) { 3672 mInLoad = false; 3673 updateInLoadMenuItems(); 3674 } 3675 } else { 3676 // onPageFinished may have already been called but a subframe 3677 // is still loading and updating the progress. Reset mInLoad 3678 // and update the menu items. 3679 if (!mInLoad) { 3680 mInLoad = true; 3681 updateInLoadMenuItems(); 3682 } 3683 } 3684 } 3685 3686 @Override 3687 public void onReceivedTitle(WebView view, String title) { 3688 String url = view.getUrl(); 3689 3690 // here, if url is null, we want to reset the title 3691 setUrlTitle(url, title); 3692 3693 if (url == null || 3694 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) { 3695 return; 3696 } 3697 // See if we can find the current url in our history database and 3698 // add the new title to it. 3699 if (url.startsWith("http://www.")) { 3700 url = url.substring(11); 3701 } else if (url.startsWith("http://")) { 3702 url = url.substring(4); 3703 } 3704 try { 3705 url = "%" + url; 3706 String [] selArgs = new String[] { url }; 3707 3708 String where = Browser.BookmarkColumns.URL + " LIKE ? AND " 3709 + Browser.BookmarkColumns.BOOKMARK + " = 0"; 3710 Cursor c = mResolver.query(Browser.BOOKMARKS_URI, 3711 Browser.HISTORY_PROJECTION, where, selArgs, null); 3712 if (c.moveToFirst()) { 3713 // Current implementation of database only has one entry per 3714 // url. 3715 ContentValues map = new ContentValues(); 3716 map.put(Browser.BookmarkColumns.TITLE, title); 3717 mResolver.update(Browser.BOOKMARKS_URI, map, 3718 "_id = " + c.getInt(0), null); 3719 } 3720 c.close(); 3721 } catch (IllegalStateException e) { 3722 Log.e(LOGTAG, "BrowserActivity onReceived title", e); 3723 } catch (SQLiteException ex) { 3724 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex); 3725 } 3726 } 3727 3728 @Override 3729 public void onReceivedIcon(WebView view, Bitmap icon) { 3730 updateIcon(view.getUrl(), icon); 3731 } 3732 3733 @Override 3734 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) { 3735 if (mCustomView != null) 3736 return; 3737 3738 // Add the custom view to its container. 3739 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER); 3740 mCustomView = view; 3741 mCustomViewCallback = callback; 3742 // Save the menu state and set it to empty while the custom 3743 // view is showing. 3744 mOldMenuState = mMenuState; 3745 mMenuState = EMPTY_MENU; 3746 // Hide the content view. 3747 mContentView.setVisibility(View.GONE); 3748 // Finally show the custom view container. 3749 mCustomViewContainer.setVisibility(View.VISIBLE); 3750 mCustomViewContainer.bringToFront(); 3751 } 3752 3753 @Override 3754 public void onHideCustomView() { 3755 if (mCustomView == null) 3756 return; 3757 3758 // Hide the custom view. 3759 mCustomView.setVisibility(View.GONE); 3760 // Remove the custom view from its container. 3761 mCustomViewContainer.removeView(mCustomView); 3762 mCustomView = null; 3763 // Reset the old menu state. 3764 mMenuState = mOldMenuState; 3765 mOldMenuState = EMPTY_MENU; 3766 mCustomViewContainer.setVisibility(View.GONE); 3767 mCustomViewCallback.onCustomViewHidden(); 3768 // Show the content view. 3769 mContentView.setVisibility(View.VISIBLE); 3770 } 3771 3772 /** 3773 * The origin has exceeded it's database quota. 3774 * @param url the URL that exceeded the quota 3775 * @param databaseIdentifier the identifier of the database on 3776 * which the transaction that caused the quota overflow was run 3777 * @param currentQuota the current quota for the origin. 3778 * @param quotaUpdater The callback to run when a decision to allow or 3779 * deny quota has been made. Don't forget to call this! 3780 */ 3781 @Override 3782 public void onExceededDatabaseQuota(String url, 3783 String databaseIdentifier, long currentQuota, 3784 WebStorage.QuotaUpdater quotaUpdater) { 3785 if(LOGV_ENABLED) { 3786 Log.v(LOGTAG, 3787 "BrowserActivity received onExceededDatabaseQuota for " 3788 + url + 3789 ":" 3790 + databaseIdentifier + 3791 "(current quota: " 3792 + currentQuota + 3793 ")"); 3794 } 3795 mWebStorageQuotaUpdater = quotaUpdater; 3796 String DIALOG_PACKAGE = "com.android.browser"; 3797 String DIALOG_CLASS = DIALOG_PACKAGE + ".PermissionDialog"; 3798 Intent intent = new Intent(); 3799 intent.setClassName(DIALOG_PACKAGE, DIALOG_CLASS); 3800 intent.putExtra(PermissionDialog.PARAM_ORIGIN, url); 3801 intent.putExtra(PermissionDialog.PARAM_QUOTA, currentQuota); 3802 startActivityForResult(intent, WEBSTORAGE_QUOTA_DIALOG); 3803 } 3804 3805 /* Adds a JavaScript error message to the system log. 3806 * @param message The error message to report. 3807 * @param lineNumber The line number of the error. 3808 * @param sourceID The name of the source file that caused the error. 3809 */ 3810 @Override 3811 public void addMessageToConsole(String message, int lineNumber, String sourceID) { 3812 Log.w(LOGTAG, "Console: " + message + " (" + sourceID + ":" + lineNumber + ")"); 3813 } 3814 3815 }; 3816 3817 /** 3818 * Notify the host application a download should be done, or that 3819 * the data should be streamed if a streaming viewer is available. 3820 * @param url The full url to the content that should be downloaded 3821 * @param contentDisposition Content-disposition http header, if 3822 * present. 3823 * @param mimetype The mimetype of the content reported by the server 3824 * @param contentLength The file size reported by the server 3825 */ 3826 public void onDownloadStart(String url, String userAgent, 3827 String contentDisposition, String mimetype, long contentLength) { 3828 // if we're dealing wih A/V content that's not explicitly marked 3829 // for download, check if it's streamable. 3830 if (contentDisposition == null 3831 || !contentDisposition.regionMatches(true, 0, "attachment", 0, 10)) { 3832 // query the package manager to see if there's a registered handler 3833 // that matches. 3834 Intent intent = new Intent(Intent.ACTION_VIEW); 3835 intent.setDataAndType(Uri.parse(url), mimetype); 3836 if (getPackageManager().resolveActivity(intent, 3837 PackageManager.MATCH_DEFAULT_ONLY) != null) { 3838 // someone knows how to handle this mime type with this scheme, don't download. 3839 try { 3840 startActivity(intent); 3841 return; 3842 } catch (ActivityNotFoundException ex) { 3843 if (LOGD_ENABLED) { 3844 Log.d(LOGTAG, "activity not found for " + mimetype 3845 + " over " + Uri.parse(url).getScheme(), ex); 3846 } 3847 // Best behavior is to fall back to a download in this case 3848 } 3849 } 3850 } 3851 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength); 3852 } 3853 3854 /** 3855 * Notify the host application a download should be done, even if there 3856 * is a streaming viewer available for thise type. 3857 * @param url The full url to the content that should be downloaded 3858 * @param contentDisposition Content-disposition http header, if 3859 * present. 3860 * @param mimetype The mimetype of the content reported by the server 3861 * @param contentLength The file size reported by the server 3862 */ 3863 /*package */ void onDownloadStartNoStream(String url, String userAgent, 3864 String contentDisposition, String mimetype, long contentLength) { 3865 3866 String filename = URLUtil.guessFileName(url, 3867 contentDisposition, mimetype); 3868 3869 // Check to see if we have an SDCard 3870 String status = Environment.getExternalStorageState(); 3871 if (!status.equals(Environment.MEDIA_MOUNTED)) { 3872 int title; 3873 String msg; 3874 3875 // Check to see if the SDCard is busy, same as the music app 3876 if (status.equals(Environment.MEDIA_SHARED)) { 3877 msg = getString(R.string.download_sdcard_busy_dlg_msg); 3878 title = R.string.download_sdcard_busy_dlg_title; 3879 } else { 3880 msg = getString(R.string.download_no_sdcard_dlg_msg, filename); 3881 title = R.string.download_no_sdcard_dlg_title; 3882 } 3883 3884 new AlertDialog.Builder(this) 3885 .setTitle(title) 3886 .setIcon(android.R.drawable.ic_dialog_alert) 3887 .setMessage(msg) 3888 .setPositiveButton(R.string.ok, null) 3889 .show(); 3890 return; 3891 } 3892 3893 // java.net.URI is a lot stricter than KURL so we have to undo 3894 // KURL's percent-encoding and redo the encoding using java.net.URI. 3895 URI uri = null; 3896 try { 3897 // Undo the percent-encoding that KURL may have done. 3898 String newUrl = new String(URLUtil.decode(url.getBytes())); 3899 // Parse the url into pieces 3900 WebAddress w = new WebAddress(newUrl); 3901 String frag = null; 3902 String query = null; 3903 String path = w.mPath; 3904 // Break the path into path, query, and fragment 3905 if (path.length() > 0) { 3906 // Strip the fragment 3907 int idx = path.lastIndexOf('#'); 3908 if (idx != -1) { 3909 frag = path.substring(idx + 1); 3910 path = path.substring(0, idx); 3911 } 3912 idx = path.lastIndexOf('?'); 3913 if (idx != -1) { 3914 query = path.substring(idx + 1); 3915 path = path.substring(0, idx); 3916 } 3917 } 3918 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path, 3919 query, frag); 3920 } catch (Exception e) { 3921 Log.e(LOGTAG, "Could not parse url for download: " + url, e); 3922 return; 3923 } 3924 3925 // XXX: Have to use the old url since the cookies were stored using the 3926 // old percent-encoded url. 3927 String cookies = CookieManager.getInstance().getCookie(url); 3928 3929 ContentValues values = new ContentValues(); 3930 values.put(Downloads.COLUMN_URI, uri.toString()); 3931 values.put(Downloads.COLUMN_COOKIE_DATA, cookies); 3932 values.put(Downloads.COLUMN_USER_AGENT, userAgent); 3933 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE, 3934 getPackageName()); 3935 values.put(Downloads.COLUMN_NOTIFICATION_CLASS, 3936 BrowserDownloadPage.class.getCanonicalName()); 3937 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); 3938 values.put(Downloads.COLUMN_MIME_TYPE, mimetype); 3939 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename); 3940 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost()); 3941 if (contentLength > 0) { 3942 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength); 3943 } 3944 if (mimetype == null) { 3945 // We must have long pressed on a link or image to download it. We 3946 // are not sure of the mimetype in this case, so do a head request 3947 new FetchUrlMimeType(this).execute(values); 3948 } else { 3949 final Uri contentUri = 3950 getContentResolver().insert(Downloads.CONTENT_URI, values); 3951 viewDownloads(contentUri); 3952 } 3953 3954 } 3955 3956 /** 3957 * Resets the lock icon. This method is called when we start a new load and 3958 * know the url to be loaded. 3959 */ 3960 private void resetLockIcon(String url) { 3961 // Save the lock-icon state (we revert to it if the load gets cancelled) 3962 saveLockIcon(); 3963 3964 mLockIconType = LOCK_ICON_UNSECURE; 3965 if (URLUtil.isHttpsUrl(url)) { 3966 mLockIconType = LOCK_ICON_SECURE; 3967 if (LOGV_ENABLED) { 3968 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" + 3969 " reset lock icon to " + mLockIconType); 3970 } 3971 } 3972 3973 updateLockIconImage(LOCK_ICON_UNSECURE); 3974 } 3975 3976 /** 3977 * Resets the lock icon. This method is called when the icon needs to be 3978 * reset but we do not know whether we are loading a secure or not secure 3979 * page. 3980 */ 3981 private void resetLockIcon() { 3982 // Save the lock-icon state (we revert to it if the load gets cancelled) 3983 saveLockIcon(); 3984 3985 mLockIconType = LOCK_ICON_UNSECURE; 3986 3987 if (LOGV_ENABLED) { 3988 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" + 3989 " reset lock icon to " + mLockIconType); 3990 } 3991 3992 updateLockIconImage(LOCK_ICON_UNSECURE); 3993 } 3994 3995 /** 3996 * Updates the lock-icon image in the title-bar. 3997 */ 3998 private void updateLockIconImage(int lockIconType) { 3999 Drawable d = null; 4000 if (lockIconType == LOCK_ICON_SECURE) { 4001 d = mSecLockIcon; 4002 } else if (lockIconType == LOCK_ICON_MIXED) { 4003 d = mMixLockIcon; 4004 } 4005 // If the tab overview is animating or being shown, do not update the 4006 // lock icon. 4007 if (mAnimationCount == 0 && mTabOverview == null) { 4008 if (CUSTOM_BROWSER_BAR) { 4009 mTitleBar.setLock(d); 4010 } else { 4011 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, d); 4012 } 4013 } 4014 } 4015 4016 /** 4017 * Displays a page-info dialog. 4018 * @param tab The tab to show info about 4019 * @param fromShowSSLCertificateOnError The flag that indicates whether 4020 * this dialog was opened from the SSL-certificate-on-error dialog or 4021 * not. This is important, since we need to know whether to return to 4022 * the parent dialog or simply dismiss. 4023 */ 4024 private void showPageInfo(final TabControl.Tab tab, 4025 final boolean fromShowSSLCertificateOnError) { 4026 final LayoutInflater factory = LayoutInflater 4027 .from(this); 4028 4029 final View pageInfoView = factory.inflate(R.layout.page_info, null); 4030 4031 final WebView view = tab.getWebView(); 4032 4033 String url = null; 4034 String title = null; 4035 4036 if (view == null) { 4037 url = tab.getUrl(); 4038 title = tab.getTitle(); 4039 } else if (view == mTabControl.getCurrentWebView()) { 4040 // Use the cached title and url if this is the current WebView 4041 url = mUrl; 4042 title = mTitle; 4043 } else { 4044 url = view.getUrl(); 4045 title = view.getTitle(); 4046 } 4047 4048 if (url == null) { 4049 url = ""; 4050 } 4051 if (title == null) { 4052 title = ""; 4053 } 4054 4055 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url); 4056 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title); 4057 4058 mPageInfoView = tab; 4059 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError); 4060 4061 AlertDialog.Builder alertDialogBuilder = 4062 new AlertDialog.Builder(this) 4063 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info) 4064 .setView(pageInfoView) 4065 .setPositiveButton( 4066 R.string.ok, 4067 new DialogInterface.OnClickListener() { 4068 public void onClick(DialogInterface dialog, 4069 int whichButton) { 4070 mPageInfoDialog = null; 4071 mPageInfoView = null; 4072 mPageInfoFromShowSSLCertificateOnError = null; 4073 4074 // if we came here from the SSL error dialog 4075 if (fromShowSSLCertificateOnError) { 4076 // go back to the SSL error dialog 4077 showSSLCertificateOnError( 4078 mSSLCertificateOnErrorView, 4079 mSSLCertificateOnErrorHandler, 4080 mSSLCertificateOnErrorError); 4081 } 4082 } 4083 }) 4084 .setOnCancelListener( 4085 new DialogInterface.OnCancelListener() { 4086 public void onCancel(DialogInterface dialog) { 4087 mPageInfoDialog = null; 4088 mPageInfoView = null; 4089 mPageInfoFromShowSSLCertificateOnError = null; 4090 4091 // if we came here from the SSL error dialog 4092 if (fromShowSSLCertificateOnError) { 4093 // go back to the SSL error dialog 4094 showSSLCertificateOnError( 4095 mSSLCertificateOnErrorView, 4096 mSSLCertificateOnErrorHandler, 4097 mSSLCertificateOnErrorError); 4098 } 4099 } 4100 }); 4101 4102 // if we have a main top-level page SSL certificate set or a certificate 4103 // error 4104 if (fromShowSSLCertificateOnError || 4105 (view != null && view.getCertificate() != null)) { 4106 // add a 'View Certificate' button 4107 alertDialogBuilder.setNeutralButton( 4108 R.string.view_certificate, 4109 new DialogInterface.OnClickListener() { 4110 public void onClick(DialogInterface dialog, 4111 int whichButton) { 4112 mPageInfoDialog = null; 4113 mPageInfoView = null; 4114 mPageInfoFromShowSSLCertificateOnError = null; 4115 4116 // if we came here from the SSL error dialog 4117 if (fromShowSSLCertificateOnError) { 4118 // go back to the SSL error dialog 4119 showSSLCertificateOnError( 4120 mSSLCertificateOnErrorView, 4121 mSSLCertificateOnErrorHandler, 4122 mSSLCertificateOnErrorError); 4123 } else { 4124 // otherwise, display the top-most certificate from 4125 // the chain 4126 if (view.getCertificate() != null) { 4127 showSSLCertificate(tab); 4128 } 4129 } 4130 } 4131 }); 4132 } 4133 4134 mPageInfoDialog = alertDialogBuilder.show(); 4135 } 4136 4137 /** 4138 * Displays the main top-level page SSL certificate dialog 4139 * (accessible from the Page-Info dialog). 4140 * @param tab The tab to show certificate for. 4141 */ 4142 private void showSSLCertificate(final TabControl.Tab tab) { 4143 final View certificateView = 4144 inflateCertificateView(tab.getWebView().getCertificate()); 4145 if (certificateView == null) { 4146 return; 4147 } 4148 4149 LayoutInflater factory = LayoutInflater.from(this); 4150 4151 final LinearLayout placeholder = 4152 (LinearLayout)certificateView.findViewById(R.id.placeholder); 4153 4154 LinearLayout ll = (LinearLayout) factory.inflate( 4155 R.layout.ssl_success, placeholder); 4156 ((TextView)ll.findViewById(R.id.success)) 4157 .setText(R.string.ssl_certificate_is_valid); 4158 4159 mSSLCertificateView = tab; 4160 mSSLCertificateDialog = 4161 new AlertDialog.Builder(this) 4162 .setTitle(R.string.ssl_certificate).setIcon( 4163 R.drawable.ic_dialog_browser_certificate_secure) 4164 .setView(certificateView) 4165 .setPositiveButton(R.string.ok, 4166 new DialogInterface.OnClickListener() { 4167 public void onClick(DialogInterface dialog, 4168 int whichButton) { 4169 mSSLCertificateDialog = null; 4170 mSSLCertificateView = null; 4171 4172 showPageInfo(tab, false); 4173 } 4174 }) 4175 .setOnCancelListener( 4176 new DialogInterface.OnCancelListener() { 4177 public void onCancel(DialogInterface dialog) { 4178 mSSLCertificateDialog = null; 4179 mSSLCertificateView = null; 4180 4181 showPageInfo(tab, false); 4182 } 4183 }) 4184 .show(); 4185 } 4186 4187 /** 4188 * Displays the SSL error certificate dialog. 4189 * @param view The target web-view. 4190 * @param handler The SSL error handler responsible for cancelling the 4191 * connection that resulted in an SSL error or proceeding per user request. 4192 * @param error The SSL error object. 4193 */ 4194 private void showSSLCertificateOnError( 4195 final WebView view, final SslErrorHandler handler, final SslError error) { 4196 4197 final View certificateView = 4198 inflateCertificateView(error.getCertificate()); 4199 if (certificateView == null) { 4200 return; 4201 } 4202 4203 LayoutInflater factory = LayoutInflater.from(this); 4204 4205 final LinearLayout placeholder = 4206 (LinearLayout)certificateView.findViewById(R.id.placeholder); 4207 4208 if (error.hasError(SslError.SSL_UNTRUSTED)) { 4209 LinearLayout ll = (LinearLayout)factory 4210 .inflate(R.layout.ssl_warning, placeholder); 4211 ((TextView)ll.findViewById(R.id.warning)) 4212 .setText(R.string.ssl_untrusted); 4213 } 4214 4215 if (error.hasError(SslError.SSL_IDMISMATCH)) { 4216 LinearLayout ll = (LinearLayout)factory 4217 .inflate(R.layout.ssl_warning, placeholder); 4218 ((TextView)ll.findViewById(R.id.warning)) 4219 .setText(R.string.ssl_mismatch); 4220 } 4221 4222 if (error.hasError(SslError.SSL_EXPIRED)) { 4223 LinearLayout ll = (LinearLayout)factory 4224 .inflate(R.layout.ssl_warning, placeholder); 4225 ((TextView)ll.findViewById(R.id.warning)) 4226 .setText(R.string.ssl_expired); 4227 } 4228 4229 if (error.hasError(SslError.SSL_NOTYETVALID)) { 4230 LinearLayout ll = (LinearLayout)factory 4231 .inflate(R.layout.ssl_warning, placeholder); 4232 ((TextView)ll.findViewById(R.id.warning)) 4233 .setText(R.string.ssl_not_yet_valid); 4234 } 4235 4236 mSSLCertificateOnErrorHandler = handler; 4237 mSSLCertificateOnErrorView = view; 4238 mSSLCertificateOnErrorError = error; 4239 mSSLCertificateOnErrorDialog = 4240 new AlertDialog.Builder(this) 4241 .setTitle(R.string.ssl_certificate).setIcon( 4242 R.drawable.ic_dialog_browser_certificate_partially_secure) 4243 .setView(certificateView) 4244 .setPositiveButton(R.string.ok, 4245 new DialogInterface.OnClickListener() { 4246 public void onClick(DialogInterface dialog, 4247 int whichButton) { 4248 mSSLCertificateOnErrorDialog = null; 4249 mSSLCertificateOnErrorView = null; 4250 mSSLCertificateOnErrorHandler = null; 4251 mSSLCertificateOnErrorError = null; 4252 4253 mWebViewClient.onReceivedSslError( 4254 view, handler, error); 4255 } 4256 }) 4257 .setNeutralButton(R.string.page_info_view, 4258 new DialogInterface.OnClickListener() { 4259 public void onClick(DialogInterface dialog, 4260 int whichButton) { 4261 mSSLCertificateOnErrorDialog = null; 4262 4263 // do not clear the dialog state: we will 4264 // need to show the dialog again once the 4265 // user is done exploring the page-info details 4266 4267 showPageInfo(mTabControl.getTabFromView(view), 4268 true); 4269 } 4270 }) 4271 .setOnCancelListener( 4272 new DialogInterface.OnCancelListener() { 4273 public void onCancel(DialogInterface dialog) { 4274 mSSLCertificateOnErrorDialog = null; 4275 mSSLCertificateOnErrorView = null; 4276 mSSLCertificateOnErrorHandler = null; 4277 mSSLCertificateOnErrorError = null; 4278 4279 mWebViewClient.onReceivedSslError( 4280 view, handler, error); 4281 } 4282 }) 4283 .show(); 4284 } 4285 4286 /** 4287 * Inflates the SSL certificate view (helper method). 4288 * @param certificate The SSL certificate. 4289 * @return The resultant certificate view with issued-to, issued-by, 4290 * issued-on, expires-on, and possibly other fields set. 4291 * If the input certificate is null, returns null. 4292 */ 4293 private View inflateCertificateView(SslCertificate certificate) { 4294 if (certificate == null) { 4295 return null; 4296 } 4297 4298 LayoutInflater factory = LayoutInflater.from(this); 4299 4300 View certificateView = factory.inflate( 4301 R.layout.ssl_certificate, null); 4302 4303 // issued to: 4304 SslCertificate.DName issuedTo = certificate.getIssuedTo(); 4305 if (issuedTo != null) { 4306 ((TextView) certificateView.findViewById(R.id.to_common)) 4307 .setText(issuedTo.getCName()); 4308 ((TextView) certificateView.findViewById(R.id.to_org)) 4309 .setText(issuedTo.getOName()); 4310 ((TextView) certificateView.findViewById(R.id.to_org_unit)) 4311 .setText(issuedTo.getUName()); 4312 } 4313 4314 // issued by: 4315 SslCertificate.DName issuedBy = certificate.getIssuedBy(); 4316 if (issuedBy != null) { 4317 ((TextView) certificateView.findViewById(R.id.by_common)) 4318 .setText(issuedBy.getCName()); 4319 ((TextView) certificateView.findViewById(R.id.by_org)) 4320 .setText(issuedBy.getOName()); 4321 ((TextView) certificateView.findViewById(R.id.by_org_unit)) 4322 .setText(issuedBy.getUName()); 4323 } 4324 4325 // issued on: 4326 String issuedOn = reformatCertificateDate( 4327 certificate.getValidNotBefore()); 4328 ((TextView) certificateView.findViewById(R.id.issued_on)) 4329 .setText(issuedOn); 4330 4331 // expires on: 4332 String expiresOn = reformatCertificateDate( 4333 certificate.getValidNotAfter()); 4334 ((TextView) certificateView.findViewById(R.id.expires_on)) 4335 .setText(expiresOn); 4336 4337 return certificateView; 4338 } 4339 4340 /** 4341 * Re-formats the certificate date (Date.toString()) string to 4342 * a properly localized date string. 4343 * @return Properly localized version of the certificate date string and 4344 * the original certificate date string if fails to localize. 4345 * If the original string is null, returns an empty string "". 4346 */ 4347 private String reformatCertificateDate(String certificateDate) { 4348 String reformattedDate = null; 4349 4350 if (certificateDate != null) { 4351 Date date = null; 4352 try { 4353 date = java.text.DateFormat.getInstance().parse(certificateDate); 4354 } catch (ParseException e) { 4355 date = null; 4356 } 4357 4358 if (date != null) { 4359 reformattedDate = 4360 DateFormat.getDateFormat(this).format(date); 4361 } 4362 } 4363 4364 return reformattedDate != null ? reformattedDate : 4365 (certificateDate != null ? certificateDate : ""); 4366 } 4367 4368 /** 4369 * Displays an http-authentication dialog. 4370 */ 4371 private void showHttpAuthentication(final HttpAuthHandler handler, 4372 final String host, final String realm, final String title, 4373 final String name, final String password, int focusId) { 4374 LayoutInflater factory = LayoutInflater.from(this); 4375 final View v = factory 4376 .inflate(R.layout.http_authentication, null); 4377 if (name != null) { 4378 ((EditText) v.findViewById(R.id.username_edit)).setText(name); 4379 } 4380 if (password != null) { 4381 ((EditText) v.findViewById(R.id.password_edit)).setText(password); 4382 } 4383 4384 String titleText = title; 4385 if (titleText == null) { 4386 titleText = getText(R.string.sign_in_to).toString().replace( 4387 "%s1", host).replace("%s2", realm); 4388 } 4389 4390 mHttpAuthHandler = handler; 4391 AlertDialog dialog = new AlertDialog.Builder(this) 4392 .setTitle(titleText) 4393 .setIcon(android.R.drawable.ic_dialog_alert) 4394 .setView(v) 4395 .setPositiveButton(R.string.action, 4396 new DialogInterface.OnClickListener() { 4397 public void onClick(DialogInterface dialog, 4398 int whichButton) { 4399 String nm = ((EditText) v 4400 .findViewById(R.id.username_edit)) 4401 .getText().toString(); 4402 String pw = ((EditText) v 4403 .findViewById(R.id.password_edit)) 4404 .getText().toString(); 4405 BrowserActivity.this.setHttpAuthUsernamePassword 4406 (host, realm, nm, pw); 4407 handler.proceed(nm, pw); 4408 mHttpAuthenticationDialog = null; 4409 mHttpAuthHandler = null; 4410 }}) 4411 .setNegativeButton(R.string.cancel, 4412 new DialogInterface.OnClickListener() { 4413 public void onClick(DialogInterface dialog, 4414 int whichButton) { 4415 handler.cancel(); 4416 BrowserActivity.this.resetTitleAndRevertLockIcon(); 4417 mHttpAuthenticationDialog = null; 4418 mHttpAuthHandler = null; 4419 }}) 4420 .setOnCancelListener(new DialogInterface.OnCancelListener() { 4421 public void onCancel(DialogInterface dialog) { 4422 handler.cancel(); 4423 BrowserActivity.this.resetTitleAndRevertLockIcon(); 4424 mHttpAuthenticationDialog = null; 4425 mHttpAuthHandler = null; 4426 }}) 4427 .create(); 4428 // Make the IME appear when the dialog is displayed if applicable. 4429 dialog.getWindow().setSoftInputMode( 4430 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); 4431 dialog.show(); 4432 if (focusId != 0) { 4433 dialog.findViewById(focusId).requestFocus(); 4434 } else { 4435 v.findViewById(R.id.username_edit).requestFocus(); 4436 } 4437 mHttpAuthenticationDialog = dialog; 4438 } 4439 4440 public int getProgress() { 4441 WebView w = mTabControl.getCurrentWebView(); 4442 if (w != null) { 4443 return w.getProgress(); 4444 } else { 4445 return 100; 4446 } 4447 } 4448 4449 /** 4450 * Set HTTP authentication password. 4451 * 4452 * @param host The host for the password 4453 * @param realm The realm for the password 4454 * @param username The username for the password. If it is null, it means 4455 * password can't be saved. 4456 * @param password The password 4457 */ 4458 public void setHttpAuthUsernamePassword(String host, String realm, 4459 String username, 4460 String password) { 4461 WebView w = mTabControl.getCurrentWebView(); 4462 if (w != null) { 4463 w.setHttpAuthUsernamePassword(host, realm, username, password); 4464 } 4465 } 4466 4467 /** 4468 * connectivity manager says net has come or gone... inform the user 4469 * @param up true if net has come up, false if net has gone down 4470 */ 4471 public void onNetworkToggle(boolean up) { 4472 if (up == mIsNetworkUp) { 4473 return; 4474 } else if (up) { 4475 mIsNetworkUp = true; 4476 if (mAlertDialog != null) { 4477 mAlertDialog.cancel(); 4478 mAlertDialog = null; 4479 } 4480 } else { 4481 mIsNetworkUp = false; 4482 if (mInLoad && mAlertDialog == null) { 4483 mAlertDialog = new AlertDialog.Builder(this) 4484 .setTitle(R.string.loadSuspendedTitle) 4485 .setMessage(R.string.loadSuspended) 4486 .setPositiveButton(R.string.ok, null) 4487 .show(); 4488 } 4489 } 4490 WebView w = mTabControl.getCurrentWebView(); 4491 if (w != null) { 4492 w.setNetworkAvailable(up); 4493 } 4494 } 4495 4496 @Override 4497 protected void onActivityResult(int requestCode, int resultCode, 4498 Intent intent) { 4499 switch (requestCode) { 4500 case COMBO_PAGE: 4501 if (resultCode == RESULT_OK && intent != null) { 4502 String data = intent.getAction(); 4503 Bundle extras = intent.getExtras(); 4504 if (extras != null && extras.getBoolean("new_window", false)) { 4505 openTab(data); 4506 } else { 4507 final TabControl.Tab currentTab = 4508 mTabControl.getCurrentTab(); 4509 // If the Window overview is up and we are not in the 4510 // middle of an animation, animate away from it to the 4511 // current tab. 4512 if (mTabOverview != null && mAnimationCount == 0) { 4513 sendAnimateFromOverview(currentTab, false, 4514 new UrlData(data), TAB_OVERVIEW_DELAY, null); 4515 } else { 4516 dismissSubWindow(currentTab); 4517 if (data != null && data.length() != 0) { 4518 getTopWindow().loadUrl(data); 4519 } 4520 } 4521 } 4522 } 4523 break; 4524 case WEBSTORAGE_QUOTA_DIALOG: 4525 long currentQuota = 0; 4526 if (resultCode == RESULT_OK && intent != null) { 4527 currentQuota = intent.getLongExtra( 4528 PermissionDialog.PARAM_QUOTA, currentQuota); 4529 } 4530 mWebStorageQuotaUpdater.updateQuota(currentQuota); 4531 break; 4532 default: 4533 break; 4534 } 4535 getTopWindow().requestFocus(); 4536 } 4537 4538 /* 4539 * This method is called as a result of the user selecting the options 4540 * menu to see the download window, or when a download changes state. It 4541 * shows the download window ontop of the current window. 4542 */ 4543 /* package */ void viewDownloads(Uri downloadRecord) { 4544 Intent intent = new Intent(this, 4545 BrowserDownloadPage.class); 4546 intent.setData(downloadRecord); 4547 startActivityForResult(intent, this.DOWNLOAD_PAGE); 4548 4549 } 4550 4551 /** 4552 * Handle results from Tab Switcher mTabOverview tool 4553 */ 4554 private class TabListener implements ImageGrid.Listener { 4555 public void remove(int position) { 4556 // Note: Remove is not enabled if we have only one tab. 4557 if (DEBUG && mTabControl.getTabCount() == 1) { 4558 throw new AssertionError(); 4559 } 4560 4561 // Remember the current tab. 4562 TabControl.Tab current = mTabControl.getCurrentTab(); 4563 final TabControl.Tab remove = mTabControl.getTab(position); 4564 mTabControl.removeTab(remove); 4565 // If we removed the current tab, use the tab at position - 1 if 4566 // possible. 4567 if (current == remove) { 4568 // If the user removes the last tab, act like the New Tab item 4569 // was clicked on. 4570 if (mTabControl.getTabCount() == 0) { 4571 current = mTabControl.createNewTab(); 4572 sendAnimateFromOverview(current, true, new UrlData( 4573 mSettings.getHomePage()), TAB_OVERVIEW_DELAY, null); 4574 } else { 4575 final int index = position > 0 ? (position - 1) : 0; 4576 current = mTabControl.getTab(index); 4577 } 4578 } 4579 4580 // The tab overview could have been dismissed before this method is 4581 // called. 4582 if (mTabOverview != null) { 4583 // Remove the tab and change the index. 4584 mTabOverview.remove(position); 4585 mTabOverview.setCurrentIndex(mTabControl.getTabIndex(current)); 4586 } 4587 4588 // Only the current tab ensures its WebView is non-null. This 4589 // implies that we are reloading the freed tab. 4590 mTabControl.setCurrentTab(current); 4591 } 4592 public void onClick(int index) { 4593 // Change the tab if necessary. 4594 // Index equals ImageGrid.CANCEL when pressing back from the tab 4595 // overview. 4596 if (index == ImageGrid.CANCEL) { 4597 index = mTabControl.getCurrentIndex(); 4598 // The current index is -1 if the current tab was removed. 4599 if (index == -1) { 4600 // Take the last tab as a fallback. 4601 index = mTabControl.getTabCount() - 1; 4602 } 4603 } 4604 4605 // NEW_TAB means that the "New Tab" cell was clicked on. 4606 if (index == ImageGrid.NEW_TAB) { 4607 openTabAndShow(mSettings.getHomePage(), null, false, null); 4608 } else { 4609 sendAnimateFromOverview(mTabControl.getTab(index), false, 4610 EMPTY_URL_DATA, 0, null); 4611 } 4612 } 4613 } 4614 4615 // A fake View that draws the WebView's picture with a fast zoom filter. 4616 // The View is used in case the tab is freed during the animation because 4617 // of low memory. 4618 private static class AnimatingView extends View { 4619 private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG | 4620 Paint.DITHER_FLAG | Paint.SUBPIXEL_TEXT_FLAG; 4621 private static final DrawFilter sZoomFilter = 4622 new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG); 4623 private final Picture mPicture; 4624 private final float mScale; 4625 private final int mScrollX; 4626 private final int mScrollY; 4627 final TabControl.Tab mTab; 4628 4629 AnimatingView(Context ctxt, TabControl.Tab t) { 4630 super(ctxt); 4631 mTab = t; 4632 if (t != null && t.getTopWindow() != null) { 4633 // Use the top window in the animation since the tab overview 4634 // will display the top window in each cell. 4635 final WebView w = t.getTopWindow(); 4636 mPicture = w.capturePicture(); 4637 mScale = w.getScale() / w.getWidth(); 4638 mScrollX = w.getScrollX(); 4639 mScrollY = w.getScrollY(); 4640 } else { 4641 mPicture = null; 4642 mScale = 1.0f; 4643 mScrollX = mScrollY = 0; 4644 } 4645 } 4646 4647 @Override 4648 protected void onDraw(Canvas canvas) { 4649 canvas.save(); 4650 canvas.drawColor(Color.WHITE); 4651 if (mPicture != null) { 4652 canvas.setDrawFilter(sZoomFilter); 4653 float scale = getWidth() * mScale; 4654 canvas.scale(scale, scale); 4655 canvas.translate(-mScrollX, -mScrollY); 4656 canvas.drawPicture(mPicture); 4657 } 4658 canvas.restore(); 4659 } 4660 } 4661 4662 /** 4663 * Open the tab picker. This function will always use the current tab in 4664 * its animation. 4665 * @param stay boolean stating whether the tab picker is to remain open 4666 * (in which case it needs a listener and its menu) or not. 4667 * @param index The index of the tab to show as the selection in the tab 4668 * overview. 4669 * @param remove If true, the tab at index will be removed after the 4670 * animation completes. 4671 */ 4672 private void tabPicker(final boolean stay, final int index, 4673 final boolean remove) { 4674 if (mTabOverview != null) { 4675 return; 4676 } 4677 4678 int size = mTabControl.getTabCount(); 4679 4680 TabListener l = null; 4681 if (stay) { 4682 l = mTabListener = new TabListener(); 4683 } 4684 mTabOverview = new ImageGrid(this, stay, l); 4685 4686 for (int i = 0; i < size; i++) { 4687 final TabControl.Tab t = mTabControl.getTab(i); 4688 mTabControl.populatePickerData(t); 4689 mTabOverview.add(t); 4690 } 4691 4692 // Tell the tab overview to show the current tab, the tab overview will 4693 // handle the "New Tab" case. 4694 int currentIndex = mTabControl.getCurrentIndex(); 4695 mTabOverview.setCurrentIndex(currentIndex); 4696 4697 // Attach the tab overview. 4698 mContentView.addView(mTabOverview, COVER_SCREEN_PARAMS); 4699 4700 // Create a fake AnimatingView to animate the WebView's picture. 4701 final TabControl.Tab current = mTabControl.getCurrentTab(); 4702 final AnimatingView v = new AnimatingView(this, current); 4703 mContentView.addView(v, COVER_SCREEN_PARAMS); 4704 removeTabFromContentView(current); 4705 // Pause timers to get the animation smoother. 4706 current.getWebView().pauseTimers(); 4707 4708 // Send a message so the tab picker has a chance to layout and get 4709 // positions for all the cells. 4710 mHandler.sendMessage(mHandler.obtainMessage(ANIMATE_TO_OVERVIEW, 4711 index, remove ? 1 : 0, v)); 4712 // Setting this will indicate that we are animating to the overview. We 4713 // set it here to prevent another request to animate from coming in 4714 // between now and when ANIMATE_TO_OVERVIEW is handled. 4715 mAnimationCount++; 4716 // Always change the title bar to the window overview title while 4717 // animating. 4718 if (CUSTOM_BROWSER_BAR) { 4719 mTitleBar.setToTabPicker(); 4720 } else { 4721 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, null); 4722 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, null); 4723 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, 4724 Window.PROGRESS_VISIBILITY_OFF); 4725 setTitle(R.string.tab_picker_title); 4726 } 4727 // Make the menu empty until the animation completes. 4728 mMenuState = EMPTY_MENU; 4729 } 4730 4731 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) { 4732 WebView current = mTabControl.getCurrentWebView(); 4733 if (current == null) { 4734 return; 4735 } 4736 Intent intent = new Intent(this, 4737 CombinedBookmarkHistoryActivity.class); 4738 String title = current.getTitle(); 4739 String url = current.getUrl(); 4740 // Just in case the user opens bookmarks before a page finishes loading 4741 // so the current history item, and therefore the page, is null. 4742 if (null == url) { 4743 url = mLastEnteredUrl; 4744 // This can happen. 4745 if (null == url) { 4746 url = mSettings.getHomePage(); 4747 } 4748 } 4749 // In case the web page has not yet received its associated title. 4750 if (title == null) { 4751 title = url; 4752 } 4753 intent.putExtra("title", title); 4754 intent.putExtra("url", url); 4755 intent.putExtra("maxTabsOpen", 4756 mTabControl.getTabCount() >= TabControl.MAX_TABS); 4757 if (startWithHistory) { 4758 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB, 4759 CombinedBookmarkHistoryActivity.HISTORY_TAB); 4760 } 4761 startActivityForResult(intent, COMBO_PAGE); 4762 } 4763 4764 // Called when loading from context menu or LOAD_URL message 4765 private void loadURL(WebView view, String url) { 4766 // In case the user enters nothing. 4767 if (url != null && url.length() != 0 && view != null) { 4768 url = smartUrlFilter(url); 4769 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) { 4770 view.loadUrl(url); 4771 } 4772 } 4773 } 4774 4775 private void checkMemory() { 4776 ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo(); 4777 ((ActivityManager) getSystemService(ACTIVITY_SERVICE)) 4778 .getMemoryInfo(mi); 4779 // FIXME: mi.lowMemory is too aggressive, use (mi.availMem < 4780 // mi.threshold) for now 4781 // if (mi.lowMemory) { 4782 if (mi.availMem < mi.threshold) { 4783 Log.w(LOGTAG, "Browser is freeing memory now because: available=" 4784 + (mi.availMem / 1024) + "K threshold=" 4785 + (mi.threshold / 1024) + "K"); 4786 mTabControl.freeMemory(); 4787 } 4788 } 4789 4790 private String smartUrlFilter(Uri inUri) { 4791 if (inUri != null) { 4792 return smartUrlFilter(inUri.toString()); 4793 } 4794 return null; 4795 } 4796 4797 4798 // get window count 4799 4800 int getWindowCount(){ 4801 if(mTabControl != null){ 4802 return mTabControl.getTabCount(); 4803 } 4804 return 0; 4805 } 4806 4807 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile( 4808 "(?i)" + // switch on case insensitive matching 4809 "(" + // begin group for schema 4810 "(?:http|https|file):\\/\\/" + 4811 "|(?:inline|data|about|content|javascript):" + 4812 ")" + 4813 "(.*)" ); 4814 4815 /** 4816 * Attempts to determine whether user input is a URL or search 4817 * terms. Anything with a space is passed to search. 4818 * 4819 * Converts to lowercase any mistakenly uppercased schema (i.e., 4820 * "Http://" converts to "http://" 4821 * 4822 * @return Original or modified URL 4823 * 4824 */ 4825 String smartUrlFilter(String url) { 4826 4827 String inUrl = url.trim(); 4828 boolean hasSpace = inUrl.indexOf(' ') != -1; 4829 4830 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl); 4831 if (matcher.matches()) { 4832 // force scheme to lowercase 4833 String scheme = matcher.group(1); 4834 String lcScheme = scheme.toLowerCase(); 4835 if (!lcScheme.equals(scheme)) { 4836 inUrl = lcScheme + matcher.group(2); 4837 } 4838 if (hasSpace) { 4839 inUrl = inUrl.replace(" ", "%20"); 4840 } 4841 return inUrl; 4842 } 4843 if (hasSpace) { 4844 // FIXME: Is this the correct place to add to searches? 4845 // what if someone else calls this function? 4846 int shortcut = parseUrlShortcut(inUrl); 4847 if (shortcut != SHORTCUT_INVALID) { 4848 Browser.addSearchUrl(mResolver, inUrl); 4849 String query = inUrl.substring(2); 4850 switch (shortcut) { 4851 case SHORTCUT_GOOGLE_SEARCH: 4852 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER); 4853 case SHORTCUT_WIKIPEDIA_SEARCH: 4854 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER); 4855 case SHORTCUT_DICTIONARY_SEARCH: 4856 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER); 4857 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH: 4858 // FIXME: we need location in this case 4859 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER); 4860 } 4861 } 4862 } else { 4863 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) { 4864 return URLUtil.guessUrl(inUrl); 4865 } 4866 } 4867 4868 Browser.addSearchUrl(mResolver, inUrl); 4869 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER); 4870 } 4871 4872 private final static int LOCK_ICON_UNSECURE = 0; 4873 private final static int LOCK_ICON_SECURE = 1; 4874 private final static int LOCK_ICON_MIXED = 2; 4875 4876 private int mLockIconType = LOCK_ICON_UNSECURE; 4877 private int mPrevLockType = LOCK_ICON_UNSECURE; 4878 4879 private BrowserSettings mSettings; 4880 private TabControl mTabControl; 4881 private ContentResolver mResolver; 4882 private FrameLayout mContentView; 4883 private ImageGrid mTabOverview; 4884 private View mCustomView; 4885 private FrameLayout mCustomViewContainer; 4886 private WebChromeClient.CustomViewCallback mCustomViewCallback; 4887 4888 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of 4889 // view, we should rewrite this. 4890 private int mCurrentMenuState = 0; 4891 private int mMenuState = R.id.MAIN_MENU; 4892 private int mOldMenuState = EMPTY_MENU; 4893 private static final int EMPTY_MENU = -1; 4894 private Menu mMenu; 4895 4896 private FindDialog mFindDialog; 4897 // Used to prevent chording to result in firing two shortcuts immediately 4898 // one after another. Fixes bug 1211714. 4899 boolean mCanChord; 4900 4901 private boolean mInLoad; 4902 private boolean mIsNetworkUp; 4903 4904 private boolean mPageStarted; 4905 private boolean mActivityInPause = true; 4906 4907 private boolean mMenuIsDown; 4908 4909 private final KeyTracker mKeyTracker = new KeyTracker(this); 4910 4911 // As trackball doesn't send repeat down, we have to track it ourselves 4912 private boolean mTrackTrackball; 4913 4914 private static boolean mInTrace; 4915 4916 // Performance probe 4917 private static final int[] SYSTEM_CPU_FORMAT = new int[] { 4918 Process.PROC_SPACE_TERM | Process.PROC_COMBINE, 4919 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time 4920 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time 4921 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time 4922 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time 4923 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time 4924 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time 4925 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time 4926 }; 4927 4928 private long mStart; 4929 private long mProcessStart; 4930 private long mUserStart; 4931 private long mSystemStart; 4932 private long mIdleStart; 4933 private long mIrqStart; 4934 4935 private long mUiStart; 4936 4937 private Drawable mMixLockIcon; 4938 private Drawable mSecLockIcon; 4939 private Drawable mGenericFavicon; 4940 4941 /* hold a ref so we can auto-cancel if necessary */ 4942 private AlertDialog mAlertDialog; 4943 4944 // Wait for credentials before loading google.com 4945 private ProgressDialog mCredsDlg; 4946 4947 // The up-to-date URL and title (these can be different from those stored 4948 // in WebView, since it takes some time for the information in WebView to 4949 // get updated) 4950 private String mUrl; 4951 private String mTitle; 4952 4953 // As PageInfo has different style for landscape / portrait, we have 4954 // to re-open it when configuration changed 4955 private AlertDialog mPageInfoDialog; 4956 private TabControl.Tab mPageInfoView; 4957 // If the Page-Info dialog is launched from the SSL-certificate-on-error 4958 // dialog, we should not just dismiss it, but should get back to the 4959 // SSL-certificate-on-error dialog. This flag is used to store this state 4960 private Boolean mPageInfoFromShowSSLCertificateOnError; 4961 4962 // as SSLCertificateOnError has different style for landscape / portrait, 4963 // we have to re-open it when configuration changed 4964 private AlertDialog mSSLCertificateOnErrorDialog; 4965 private WebView mSSLCertificateOnErrorView; 4966 private SslErrorHandler mSSLCertificateOnErrorHandler; 4967 private SslError mSSLCertificateOnErrorError; 4968 4969 // as SSLCertificate has different style for landscape / portrait, we 4970 // have to re-open it when configuration changed 4971 private AlertDialog mSSLCertificateDialog; 4972 private TabControl.Tab mSSLCertificateView; 4973 4974 // as HttpAuthentication has different style for landscape / portrait, we 4975 // have to re-open it when configuration changed 4976 private AlertDialog mHttpAuthenticationDialog; 4977 private HttpAuthHandler mHttpAuthHandler; 4978 4979 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = 4980 new FrameLayout.LayoutParams( 4981 ViewGroup.LayoutParams.FILL_PARENT, 4982 ViewGroup.LayoutParams.FILL_PARENT); 4983 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = 4984 new FrameLayout.LayoutParams( 4985 ViewGroup.LayoutParams.FILL_PARENT, 4986 ViewGroup.LayoutParams.FILL_PARENT, 4987 Gravity.CENTER); 4988 // Google search 4989 final static String QuickSearch_G = "http://www.google.com/m?q=%s"; 4990 // Wikipedia search 4991 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go"; 4992 // Dictionary search 4993 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s"; 4994 // Google Mobile Local search 4995 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view"; 4996 4997 final static String QUERY_PLACE_HOLDER = "%s"; 4998 4999 // "source" parameter for Google search through search key 5000 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key"; 5001 // "source" parameter for Google search through goto menu 5002 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto"; 5003 // "source" parameter for Google search through simplily type 5004 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type"; 5005 // "source" parameter for Google search suggested by the browser 5006 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest"; 5007 // "source" parameter for Google search from unknown source 5008 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown"; 5009 5010 private final static String LOGTAG = "browser"; 5011 5012 private TabListener mTabListener; 5013 5014 private String mLastEnteredUrl; 5015 5016 private PowerManager.WakeLock mWakeLock; 5017 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes 5018 5019 private Toast mStopToast; 5020 5021 private TitleBar mTitleBar; 5022 5023 // Used during animations to prevent other animations from being triggered. 5024 // A count is used since the animation to and from the Window overview can 5025 // overlap. A count of 0 means no animation where a count of > 0 means 5026 // there are animations in progress. 5027 private int mAnimationCount; 5028 5029 // As the ids are dynamically created, we can't guarantee that they will 5030 // be in sequence, so this static array maps ids to a window number. 5031 final static private int[] WINDOW_SHORTCUT_ID_ARRAY = 5032 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id, 5033 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id, 5034 R.id.window_seven_menu_id, R.id.window_eight_menu_id }; 5035 5036 // monitor platform changes 5037 private IntentFilter mNetworkStateChangedFilter; 5038 private BroadcastReceiver mNetworkStateIntentReceiver; 5039 5040 private BroadcastReceiver mPackageInstallationReceiver; 5041 5042 // activity requestCode 5043 final static int COMBO_PAGE = 1; 5044 final static int DOWNLOAD_PAGE = 2; 5045 final static int PREFERENCES_PAGE = 3; 5046 final static int WEBSTORAGE_QUOTA_DIALOG = 4; 5047 5048 // the frenquency of checking whether system memory is low 5049 final static int CHECK_MEMORY_INTERVAL = 30000; // 30 seconds 5050 5051 /** 5052 * A UrlData class to abstract how the content will be set to WebView. 5053 * This base class uses loadUrl to show the content. 5054 */ 5055 private static class UrlData { 5056 String mUrl; 5057 byte[] mPostData; 5058 5059 UrlData(String url) { 5060 this.mUrl = url; 5061 } 5062 5063 void setPostData(byte[] postData) { 5064 mPostData = postData; 5065 } 5066 5067 boolean isEmpty() { 5068 return mUrl == null || mUrl.length() == 0; 5069 } 5070 5071 public void loadIn(WebView webView) { 5072 if (mPostData != null) { 5073 webView.postUrl(mUrl, mPostData); 5074 } else { 5075 webView.loadUrl(mUrl); 5076 } 5077 } 5078 }; 5079 5080 /** 5081 * A subclass of UrlData class that can display inlined content using 5082 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}. 5083 */ 5084 private static class InlinedUrlData extends UrlData { 5085 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) { 5086 super(failUrl); 5087 mInlined = inlined; 5088 mMimeType = mimeType; 5089 mEncoding = encoding; 5090 } 5091 String mMimeType; 5092 String mInlined; 5093 String mEncoding; 5094 @Override 5095 boolean isEmpty() { 5096 return mInlined == null || mInlined.length() == 0 || super.isEmpty(); 5097 } 5098 5099 @Override 5100 public void loadIn(WebView webView) { 5101 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl); 5102 } 5103 } 5104 5105 private static final UrlData EMPTY_URL_DATA = new UrlData(null); 5106} 5107