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