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