Merge change I2c5f1e76 into eclair

* changes:
  Fix back button handling in ACTV
diff --git a/api/current.xml b/api/current.xml
index df69ede..e0a0278 100644
--- a/api/current.xml
+++ b/api/current.xml
@@ -27216,7 +27216,7 @@
 </package>
 <package name="android.content"
 >
-<class name="AbstractCursorEntityIterator"
+<class name="AbstractThreadedSyncAdapter"
  extends="java.lang.Object"
  abstract="true"
  static="false"
@@ -27224,44 +27224,42 @@
  deprecated="not deprecated"
  visibility="public"
 >
-<implements name="android.content.EntityIterator">
-</implements>
-<constructor name="AbstractCursorEntityIterator"
- type="android.content.AbstractCursorEntityIterator"
+<constructor name="AbstractThreadedSyncAdapter"
+ type="android.content.AbstractThreadedSyncAdapter"
  static="false"
  final="false"
  deprecated="not deprecated"
  visibility="public"
 >
-<parameter name="db" type="android.database.sqlite.SQLiteDatabase">
+<parameter name="context" type="android.content.Context">
 </parameter>
-<parameter name="entityCursor" type="android.database.Cursor">
+<parameter name="autoInitialize" type="boolean">
 </parameter>
 </constructor>
-<method name="close"
+<method name="getContext"
+ return="android.content.Context"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="getSyncAdapterBinder"
+ return="android.os.IBinder"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="onPerformSync"
  return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-</method>
-<method name="hasNext"
- return="boolean"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-</method>
-<method name="newEntityFromCursorLocked"
- return="android.content.Entity"
  abstract="true"
  native="false"
  synchronized="false"
@@ -27270,33 +27268,28 @@
  deprecated="not deprecated"
  visibility="public"
 >
-<parameter name="cursor" type="android.database.Cursor">
+<parameter name="account" type="android.accounts.Account">
+</parameter>
+<parameter name="extras" type="android.os.Bundle">
+</parameter>
+<parameter name="authority" type="java.lang.String">
+</parameter>
+<parameter name="provider" type="android.content.ContentProviderClient">
+</parameter>
+<parameter name="syncResult" type="android.content.SyncResult">
 </parameter>
 </method>
-<method name="next"
- return="android.content.Entity"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
+<field name="LOG_SYNC_DETAILS"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="2743"
+ static="true"
+ final="true"
  deprecated="not deprecated"
  visibility="public"
 >
-</method>
-<method name="reset"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<exception name="RemoteException" type="android.os.RemoteException">
-</exception>
-</method>
+</field>
 </class>
 <class name="ActivityNotFoundException"
  extends="java.lang.RuntimeException"
@@ -27420,23 +27413,6 @@
 <parameter name="cursor" type="android.database.Cursor">
 </parameter>
 </method>
-<method name="onQueryEntitiesComplete"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="protected"
->
-<parameter name="token" type="int">
-</parameter>
-<parameter name="cookie" type="java.lang.Object">
-</parameter>
-<parameter name="iterator" type="android.content.EntityIterator">
-</parameter>
-</method>
 <method name="onUpdateComplete"
  return="void"
  abstract="false"
@@ -27519,29 +27495,6 @@
 <parameter name="orderBy" type="java.lang.String">
 </parameter>
 </method>
-<method name="startQueryEntities"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="token" type="int">
-</parameter>
-<parameter name="cookie" type="java.lang.Object">
-</parameter>
-<parameter name="uri" type="android.net.Uri">
-</parameter>
-<parameter name="selection" type="java.lang.String">
-</parameter>
-<parameter name="selectionArgs" type="java.lang.String[]">
-</parameter>
-<parameter name="orderBy" type="java.lang.String">
-</parameter>
-</method>
 <method name="startUpdate"
  return="void"
  abstract="false"
@@ -28323,21 +28276,6 @@
 <parameter name="values" type="android.content.ContentValues">
 </parameter>
 </method>
-<method name="insertEntity"
- return="android.net.Uri"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="uri" type="android.net.Uri">
-</parameter>
-<parameter name="entity" type="android.content.Entity">
-</parameter>
-</method>
 <method name="isTemporary"
  return="boolean"
  abstract="false"
@@ -28456,25 +28394,6 @@
 <parameter name="sortOrder" type="java.lang.String">
 </parameter>
 </method>
-<method name="queryEntities"
- return="android.content.EntityIterator"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="uri" type="android.net.Uri">
-</parameter>
-<parameter name="selection" type="java.lang.String">
-</parameter>
-<parameter name="selectionArgs" type="java.lang.String[]">
-</parameter>
-<parameter name="sortOrder" type="java.lang.String">
-</parameter>
-</method>
 <method name="setPathPermissions"
  return="void"
  abstract="false"
@@ -28533,21 +28452,6 @@
 <parameter name="selectionArgs" type="java.lang.String[]">
 </parameter>
 </method>
-<method name="updateEntity"
- return="int"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="uri" type="android.net.Uri">
-</parameter>
-<parameter name="entity" type="android.content.Entity">
-</parameter>
-</method>
 </class>
 <class name="ContentProviderClient"
  extends="java.lang.Object"
@@ -28653,23 +28557,6 @@
 <exception name="RemoteException" type="android.os.RemoteException">
 </exception>
 </method>
-<method name="insertEntity"
- return="android.net.Uri"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="uri" type="android.net.Uri">
-</parameter>
-<parameter name="entity" type="android.content.Entity">
-</parameter>
-<exception name="RemoteException" type="android.os.RemoteException">
-</exception>
-</method>
 <method name="openAssetFile"
  return="android.content.res.AssetFileDescriptor"
  abstract="false"
@@ -28731,27 +28618,6 @@
 <exception name="RemoteException" type="android.os.RemoteException">
 </exception>
 </method>
-<method name="queryEntities"
- return="android.content.EntityIterator"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="uri" type="android.net.Uri">
-</parameter>
-<parameter name="selection" type="java.lang.String">
-</parameter>
-<parameter name="selectionArgs" type="java.lang.String[]">
-</parameter>
-<parameter name="sortOrder" type="java.lang.String">
-</parameter>
-<exception name="RemoteException" type="android.os.RemoteException">
-</exception>
-</method>
 <method name="release"
  return="boolean"
  abstract="false"
@@ -28784,23 +28650,6 @@
 <exception name="RemoteException" type="android.os.RemoteException">
 </exception>
 </method>
-<method name="updateEntity"
- return="int"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="uri" type="android.net.Uri">
-</parameter>
-<parameter name="entity" type="android.content.Entity">
-</parameter>
-<exception name="RemoteException" type="android.os.RemoteException">
-</exception>
-</method>
 </class>
 <class name="ContentProviderOperation"
  extends="java.lang.Object"
@@ -29689,27 +29538,6 @@
 <parameter name="sortOrder" type="java.lang.String">
 </parameter>
 </method>
-<method name="queryEntities"
- return="android.content.EntityIterator"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="uri" type="android.net.Uri">
-</parameter>
-<parameter name="selection" type="java.lang.String">
-</parameter>
-<parameter name="selectionArgs" type="java.lang.String[]">
-</parameter>
-<parameter name="sortOrder" type="java.lang.String">
-</parameter>
-<exception name="RemoteException" type="android.os.RemoteException">
-</exception>
-</method>
 <method name="registerContentObserver"
  return="void"
  abstract="false"
@@ -33171,199 +32999,6 @@
 </parameter>
 </method>
 </interface>
-<class name="Entity"
- extends="java.lang.Object"
- abstract="false"
- static="false"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-<implements name="android.os.Parcelable">
-</implements>
-<constructor name="Entity"
- type="android.content.Entity"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="values" type="android.content.ContentValues">
-</parameter>
-</constructor>
-<method name="addSubValue"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="uri" type="android.net.Uri">
-</parameter>
-<parameter name="values" type="android.content.ContentValues">
-</parameter>
-</method>
-<method name="describeContents"
- return="int"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-</method>
-<method name="getEntityValues"
- return="android.content.ContentValues"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-</method>
-<method name="getSubValues"
- return="java.util.ArrayList&lt;android.content.Entity.NamedContentValues&gt;"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-</method>
-<method name="writeToParcel"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="dest" type="android.os.Parcel">
-</parameter>
-<parameter name="flags" type="int">
-</parameter>
-</method>
-<field name="CREATOR"
- type="android.os.Parcelable.Creator"
- transient="false"
- volatile="false"
- static="true"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-</field>
-</class>
-<class name="Entity.NamedContentValues"
- extends="java.lang.Object"
- abstract="false"
- static="true"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<constructor name="Entity.NamedContentValues"
- type="android.content.Entity.NamedContentValues"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="uri" type="android.net.Uri">
-</parameter>
-<parameter name="values" type="android.content.ContentValues">
-</parameter>
-</constructor>
-<field name="uri"
- type="android.net.Uri"
- transient="false"
- volatile="false"
- static="false"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-</field>
-<field name="values"
- type="android.content.ContentValues"
- transient="false"
- volatile="false"
- static="false"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-</field>
-</class>
-<interface name="EntityIterator"
- abstract="true"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<method name="close"
- return="void"
- abstract="true"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-</method>
-<method name="hasNext"
- return="boolean"
- abstract="true"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<exception name="RemoteException" type="android.os.RemoteException">
-</exception>
-</method>
-<method name="next"
- return="android.content.Entity"
- abstract="true"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<exception name="RemoteException" type="android.os.RemoteException">
-</exception>
-</method>
-<method name="reset"
- return="void"
- abstract="true"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<exception name="RemoteException" type="android.os.RemoteException">
-</exception>
-</method>
-</interface>
 <class name="Intent"
  extends="java.lang.Object"
  abstract="false"
@@ -38532,6 +38167,416 @@
 >
 </field>
 </class>
+<class name="SyncContext"
+ extends="java.lang.Object"
+ abstract="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<method name="getSyncContextBinder"
+ return="android.os.IBinder"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="onFinished"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="result" type="android.content.SyncResult">
+</parameter>
+</method>
+</class>
+<class name="SyncResult"
+ extends="java.lang.Object"
+ abstract="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<implements name="android.os.Parcelable">
+</implements>
+<constructor name="SyncResult"
+ type="android.content.SyncResult"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</constructor>
+<method name="clear"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="describeContents"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="hasError"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="hasHardError"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="hasSoftError"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="madeSomeProgress"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="toDebugString"
+ return="java.lang.String"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="writeToParcel"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="parcel" type="android.os.Parcel">
+</parameter>
+<parameter name="flags" type="int">
+</parameter>
+</method>
+<field name="ALREADY_IN_PROGRESS"
+ type="android.content.SyncResult"
+ transient="false"
+ volatile="false"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CREATOR"
+ type="android.os.Parcelable.Creator"
+ transient="false"
+ volatile="false"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="databaseError"
+ type="boolean"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="fullSyncRequested"
+ type="boolean"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="moreRecordsToGet"
+ type="boolean"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="partialSyncUnavailable"
+ type="boolean"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="stats"
+ type="android.content.SyncStats"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="syncAlreadyInProgress"
+ type="boolean"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="tooManyDeletions"
+ type="boolean"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="tooManyRetries"
+ type="boolean"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+</class>
+<class name="SyncStats"
+ extends="java.lang.Object"
+ abstract="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<implements name="android.os.Parcelable">
+</implements>
+<constructor name="SyncStats"
+ type="android.content.SyncStats"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</constructor>
+<constructor name="SyncStats"
+ type="android.content.SyncStats"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="in" type="android.os.Parcel">
+</parameter>
+</constructor>
+<method name="clear"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="describeContents"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="writeToParcel"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="dest" type="android.os.Parcel">
+</parameter>
+<parameter name="flags" type="int">
+</parameter>
+</method>
+<field name="CREATOR"
+ type="android.os.Parcelable.Creator"
+ transient="false"
+ volatile="false"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="numAuthExceptions"
+ type="long"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="numConflictDetectedExceptions"
+ type="long"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="numDeletes"
+ type="long"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="numEntries"
+ type="long"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="numInserts"
+ type="long"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="numIoExceptions"
+ type="long"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="numParseExceptions"
+ type="long"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="numSkippedEntries"
+ type="long"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="numUpdates"
+ type="long"
+ transient="false"
+ volatile="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+</class>
 <interface name="SyncStatusObserver"
  abstract="true"
  static="false"
@@ -78426,21 +78471,6 @@
  visibility="public"
 >
 </method>
-<method name="invoke"
- return="int"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="request" type="android.os.Parcel">
-</parameter>
-<parameter name="reply" type="android.os.Parcel">
-</parameter>
-</method>
 <method name="isLooping"
  return="boolean"
  abstract="false"
@@ -78463,17 +78493,6 @@
  visibility="public"
 >
 </method>
-<method name="newRequest"
- return="android.os.Parcel"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-</method>
 <method name="pause"
  return="void"
  abstract="false"
@@ -115542,6 +115561,82 @@
 >
 </field>
 </class>
+<class name="ContactsContract.RawContacts.Entity"
+ extends="java.lang.Object"
+ abstract="false"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<implements name="android.provider.BaseColumns">
+</implements>
+<field name="CONTENT_DIRECTORY"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;entity&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="DATA_ID"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;data_id&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+</class>
+<class name="ContactsContract.RawContactsEntity"
+ extends="java.lang.Object"
+ abstract="false"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<implements name="android.provider.BaseColumns">
+</implements>
+<field name="CONTENT_TYPE"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;vnd.android.cursor.dir/raw_contact_entity&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="CONTENT_URI"
+ type="android.net.Uri"
+ transient="false"
+ volatile="false"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="DATA_ID"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;data_id&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+</class>
 <class name="ContactsContract.Settings"
  extends="java.lang.Object"
  abstract="false"
diff --git a/camera/libcameraservice/CameraHardwareStub.cpp b/camera/libcameraservice/CameraHardwareStub.cpp
index 35f4846..8ad1f69 100644
--- a/camera/libcameraservice/CameraHardwareStub.cpp
+++ b/camera/libcameraservice/CameraHardwareStub.cpp
@@ -368,6 +368,12 @@
     return mParameters;
 }
 
+status_t CameraHardwareStub::sendCommand(int32_t command, int32_t arg1,
+                                         int32_t arg2)
+{
+    return BAD_VALUE;
+}
+
 void CameraHardwareStub::release()
 {
 }
diff --git a/camera/libcameraservice/CameraHardwareStub.h b/camera/libcameraservice/CameraHardwareStub.h
index f957fa8..8a67024 100644
--- a/camera/libcameraservice/CameraHardwareStub.h
+++ b/camera/libcameraservice/CameraHardwareStub.h
@@ -57,6 +57,8 @@
     virtual status_t    dump(int fd, const Vector<String16>& args) const;
     virtual status_t    setParameters(const CameraParameters& params);
     virtual CameraParameters  getParameters() const;
+    virtual status_t    sendCommand(int32_t command, int32_t arg1,
+                                    int32_t arg2);
     virtual void release();
 
     static sp<CameraHardwareInterface> createInstance();
diff --git a/camera/libcameraservice/CameraService.cpp b/camera/libcameraservice/CameraService.cpp
index bab7d08..8279914 100644
--- a/camera/libcameraservice/CameraService.cpp
+++ b/camera/libcameraservice/CameraService.cpp
@@ -195,7 +195,7 @@
     android_atomic_dec(&mUsers);
 }
 
-static sp<MediaPlayer> newMediaPlayer(const char *file) 
+static sp<MediaPlayer> newMediaPlayer(const char *file)
 {
     sp<MediaPlayer> mp = new MediaPlayer();
     if (mp->setDataSource(file) == NO_ERROR) {
@@ -267,7 +267,7 @@
 status_t CameraService::Client::unlock()
 {
     int callingPid = getCallingPid();
-    LOGD("unlock from pid %d (mClientPid %d)", callingPid, mClientPid);    
+    LOGD("unlock from pid %d (mClientPid %d)", callingPid, mClientPid);
     Mutex::Autolock _l(mLock);
     // allow anyone to use camera
     status_t result = checkPid();
@@ -648,7 +648,7 @@
 status_t CameraService::Client::startPreview()
 {
     LOGD("startPreview (pid %d)", getCallingPid());
-    
+
     return startCameraMode(CAMERA_PREVIEW_MODE);
 }
 
@@ -1134,6 +1134,21 @@
     return params;
 }
 
+status_t CameraService::Client::sendCommand(int32_t cmd, int32_t arg1, int32_t arg2)
+{
+    LOGD("sendCommand (pid %d)", getCallingPid());
+    Mutex::Autolock lock(mLock);
+    status_t result = checkPid();
+    if (result != NO_ERROR) return result;
+
+    if (mHardware == 0) {
+        LOGE("mHardware is NULL, returning.");
+        return INVALID_OPERATION;
+    }
+
+    return mHardware->sendCommand(cmd, arg1, arg2);
+}
+
 void CameraService::Client::copyFrameAndPostCopiedFrame(sp<IMemoryHeap> heap, size_t offset, size_t size)
 {
     LOGV("copyFrameAndPostCopiedFrame");
diff --git a/camera/libcameraservice/CameraService.h b/camera/libcameraservice/CameraService.h
index 0a909cf..2e3597f 100644
--- a/camera/libcameraservice/CameraService.h
+++ b/camera/libcameraservice/CameraService.h
@@ -122,6 +122,9 @@
         // get preview/capture parameters - key/value pairs
         virtual String8         getParameters() const;
 
+        // send command to camera driver
+        virtual status_t        sendCommand(int32_t cmd, int32_t arg1, int32_t arg2);
+
         // our client...
         const sp<ICameraClient>&    getCameraClient() const { return mCameraClient; }
 
diff --git a/core/java/android/content/AbstractCursorEntityIterator.java b/core/java/android/content/AbstractCursorEntityIterator.java
index c2b13a4..a804f3c 100644
--- a/core/java/android/content/AbstractCursorEntityIterator.java
+++ b/core/java/android/content/AbstractCursorEntityIterator.java
@@ -8,6 +8,7 @@
  * An abstract class that makes it easy to implement an EntityIterator over a cursor.
  * The user must implement {@link #newEntityFromCursorLocked}, which runs inside of a
  * database transaction.
+ * @hide
  */
 public abstract class AbstractCursorEntityIterator implements EntityIterator {
     private final Cursor mEntityCursor;
diff --git a/core/java/android/content/AbstractThreadedSyncAdapter.java b/core/java/android/content/AbstractThreadedSyncAdapter.java
index 6d870da..fb6091a 100644
--- a/core/java/android/content/AbstractThreadedSyncAdapter.java
+++ b/core/java/android/content/AbstractThreadedSyncAdapter.java
@@ -20,6 +20,7 @@
 import android.os.Bundle;
 import android.os.Process;
 import android.os.NetStat;
+import android.os.IBinder;
 import android.util.EventLog;
 
 import java.util.concurrent.atomic.AtomicInteger;
@@ -29,12 +30,10 @@
  * If a sync operation is already in progress when a startSync() request is received then an error
  * will be returned to the new request and the existing request will be allowed to continue.
  * When a startSync() is received and there is no sync operation in progress then a thread
- * will be started to run the operation and {@link #performSync} will be invoked on that thread.
+ * will be started to run the operation and {@link #onPerformSync} will be invoked on that thread.
  * If a cancelSync() is received that matches an existing sync operation then the thread
  * that is running that sync operation will be interrupted, which will indicate to the thread
  * that the sync has been canceled.
- *
- * @hide
  */
 public abstract class AbstractThreadedSyncAdapter {
     private final Context mContext;
@@ -71,7 +70,7 @@
         return mContext;
     }
 
-    class ISyncAdapterImpl extends ISyncAdapter.Stub {
+    private class ISyncAdapterImpl extends ISyncAdapter.Stub {
         public void startSync(ISyncContext syncContext, String authority, Account account,
                 Bundle extras) {
             final SyncContext syncContextClient = new SyncContext(syncContext);
@@ -112,7 +111,7 @@
             // check it and when we use it
             synchronized (mSyncThreadLock) {
                 if (mSyncThread != null
-                        && mSyncThread.mSyncContext.getISyncContext().asBinder()
+                        && mSyncThread.mSyncContext.getSyncContextBinder()
                         == syncContext.asBinder()) {
                     mSyncThread.interrupt();
                 }
@@ -121,9 +120,9 @@
     }
 
     /**
-     * The thread that invokes performSync(). It also acquires the provider for this sync
-     * before calling performSync and releases it afterwards. Cancel this thread in order to
-     * cancel the sync.
+     * The thread that invokes {@link AbstractThreadedSyncAdapter#onPerformSync}. It also acquires
+     * the provider for this sync before calling onPerformSync and releases it afterwards. Cancel
+     * this thread in order to cancel the sync.
      */
     private class SyncThread extends Thread {
         private final SyncContext mSyncContext;
@@ -157,11 +156,10 @@
             try {
                 provider = mContext.getContentResolver().acquireContentProviderClient(mAuthority);
                 if (provider != null) {
-                    AbstractThreadedSyncAdapter.this.performSync(mAccount, mExtras,
+                    AbstractThreadedSyncAdapter.this.onPerformSync(mAccount, mExtras,
                             mAuthority, provider, syncResult);
                 } else {
-                    // TODO(fredq) update the syncResults to indicate that we were unable to
-                    // find the provider. maybe with a ProviderError?
+                    syncResult.databaseError = true;
                 }
             } finally {
                 if (provider != null) {
@@ -170,7 +168,7 @@
                 if (!isCanceled()) {
                     mSyncContext.onFinished(syncResult);
                 }
-                logSyncDetails(NetStat.getUidTxBytes(uid) - mInitialTxBytes,
+                onLogSyncDetails(NetStat.getUidTxBytes(uid) - mInitialTxBytes,
                         NetStat.getUidRxBytes(uid) - mInitialRxBytes, syncResult);
                 // synchronize so that the assignment will be seen by other threads
                 // that also synchronize accesses to mSyncThread
@@ -186,10 +184,10 @@
     }
 
     /**
-     * @return a reference to the ISyncAdapter interface into this SyncAdapter implementation.
+     * @return a reference to the IBinder of the SyncAdapter service.
      */
-    public final ISyncAdapter getISyncAdapter() {
-        return mISyncAdapterImpl;
+    public final IBinder getSyncAdapterBinder() {
+        return mISyncAdapterImpl.asBinder();
     }
 
     /**
@@ -204,7 +202,7 @@
      *   authority
      * @param syncResult SyncAdapter-specific parameters
      */
-    public abstract void performSync(Account account, Bundle extras,
+    public abstract void onPerformSync(Account account, Bundle extras,
             String authority, ContentProviderClient provider, SyncResult syncResult);
 
     /**
@@ -215,9 +213,9 @@
      * @param bytesSent number of bytes the sync sent over the network
      * @param bytesReceived number of bytes the sync received over the network
      * @param result The SyncResult object holding info on the sync
+     * @hide
      */
-    protected void logSyncDetails(long bytesSent, long bytesReceived, SyncResult result) {
+    protected void onLogSyncDetails(long bytesSent, long bytesReceived, SyncResult result) {
         EventLog.writeEvent(SyncAdapter.LOG_SYNC_DETAILS, TAG, bytesSent, bytesReceived, "");
     }
-
-}
\ No newline at end of file
+}
diff --git a/core/java/android/content/AsyncQueryHandler.java b/core/java/android/content/AsyncQueryHandler.java
index 5e88de0..0a4a804 100644
--- a/core/java/android/content/AsyncQueryHandler.java
+++ b/core/java/android/content/AsyncQueryHandler.java
@@ -213,6 +213,7 @@
      * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
      *            (excluding the ORDER BY itself). Passing null will use the
      *            default sort order, which may be unordered.
+     * @hide
      */
     public void startQueryEntities(int token, Object cookie, Uri uri, String selection,
             String[] selectionArgs, String orderBy) {
@@ -344,6 +345,7 @@
      * @param token The token to identify the query.
      * @param cookie The cookie object.
      * @param iterator The iterator holding the query results.
+     * @hide
      */
     protected void onQueryEntitiesComplete(int token, Object cookie, EntityIterator iterator) {
         // Empty
diff --git a/core/java/android/content/ContentProvider.java b/core/java/android/content/ContentProvider.java
index 5b29b97..a341c9b 100644
--- a/core/java/android/content/ContentProvider.java
+++ b/core/java/android/content/ContentProvider.java
@@ -131,6 +131,9 @@
                     selectionArgs, sortOrder);
         }
 
+        /**
+         * @hide
+         */
         public EntityIterator queryEntities(Uri uri, String selection, String[] selectionArgs,
                 String sortOrder) {
             enforceReadPermission(uri);
@@ -152,11 +155,6 @@
             return ContentProvider.this.bulkInsert(uri, initialValues);
         }
 
-        public Uri insertEntity(Uri uri, Entity entities) {
-            enforceWritePermission(uri);
-            return ContentProvider.this.insertEntity(uri, entities);
-        }
-
         public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
                 throws OperationApplicationException {
             for (ContentProviderOperation operation : operations) {
@@ -182,11 +180,6 @@
             return ContentProvider.this.update(uri, values, selection, selectionArgs);
         }
 
-        public int updateEntity(Uri uri, Entity entity) {
-            enforceWritePermission(uri);
-            return ContentProvider.this.updateEntity(uri, entity);
-        }
-
         public ParcelFileDescriptor openFile(Uri uri, String mode)
                 throws FileNotFoundException {
             if (mode != null && mode.startsWith("rw")) enforceWritePermission(uri);
@@ -451,6 +444,9 @@
     public abstract Cursor query(Uri uri, String[] projection,
             String selection, String[] selectionArgs, String sortOrder);
 
+    /**
+     * @hide
+     */
     public EntityIterator queryEntities(Uri uri, String selection, String[] selectionArgs,
             String sortOrder) {
         throw new UnsupportedOperationException();
@@ -506,10 +502,6 @@
         return numValues;
     }
 
-    public Uri insertEntity(Uri uri, Entity entity) {
-        throw new UnsupportedOperationException();
-    }
-
     /**
      * A request to delete one or more rows. The selection clause is applied when performing
      * the deletion, allowing the operation to affect multiple rows in a
@@ -554,14 +546,10 @@
     public abstract int update(Uri uri, ContentValues values, String selection,
             String[] selectionArgs);
 
-    public int updateEntity(Uri uri, Entity entity) {
-        throw new UnsupportedOperationException();
-    }
-
     /**
      * Open a file blob associated with a content URI.
      * This method can be called from multiple
-     * threads, as described in
+     * threads, as described inentity
      * <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals:
      * Processes and Threads</a>.
      * 
diff --git a/core/java/android/content/ContentProviderClient.java b/core/java/android/content/ContentProviderClient.java
index 452653e..403c4d8 100644
--- a/core/java/android/content/ContentProviderClient.java
+++ b/core/java/android/content/ContentProviderClient.java
@@ -89,22 +89,15 @@
         return mContentProvider.openAssetFile(url, mode);
     }
 
-    /** see {@link ContentProvider#queryEntities} */
+    /**
+     * see {@link ContentProvider#queryEntities}
+     * @hide
+     */
     public EntityIterator queryEntities(Uri uri, String selection, String[] selectionArgs,
             String sortOrder) throws RemoteException {
         return mContentProvider.queryEntities(uri, selection, selectionArgs, sortOrder);
     }
 
-    /** see {@link ContentProvider#insertEntity} */
-    public Uri insertEntity(Uri uri, Entity entity) throws RemoteException {
-        return mContentProvider.insertEntity(uri, entity);
-    }
-
-    /** see {@link ContentProvider#updateEntity} */
-    public int updateEntity(Uri uri, Entity entity) throws RemoteException {
-        return mContentProvider.updateEntity(uri, entity);
-    }
-
     /** see {@link ContentProvider#applyBatch} */
     public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
             throws RemoteException, OperationApplicationException {
diff --git a/core/java/android/content/ContentProviderNative.java b/core/java/android/content/ContentProviderNative.java
index e367ceb..adc3f60 100644
--- a/core/java/android/content/ContentProviderNative.java
+++ b/core/java/android/content/ContentProviderNative.java
@@ -155,28 +155,6 @@
                     return true;
                 }
 
-                case INSERT_ENTITIES_TRANSACTION:
-                {
-                    data.enforceInterface(IContentProvider.descriptor);
-                    Uri uri = Uri.CREATOR.createFromParcel(data);
-                    Entity entity = (Entity) data.readParcelable(null);
-                    Uri newUri = insertEntity(uri, entity);
-                    reply.writeNoException();
-                    Uri.writeToParcel(reply, newUri);
-                    return true;
-                }
-
-                case UPDATE_ENTITIES_TRANSACTION:
-                {
-                    data.enforceInterface(IContentProvider.descriptor);
-                    Uri uri = Uri.CREATOR.createFromParcel(data);
-                    Entity entity = (Entity) data.readParcelable(null);
-                    int count = updateEntity(uri, entity);
-                    reply.writeNoException();
-                    reply.writeInt(count);
-                    return true;
-                }
-
                 case APPLY_BATCH_TRANSACTION:
                 {
                     data.enforceInterface(IContentProvider.descriptor);
@@ -267,6 +245,9 @@
         return super.onTransact(code, data, reply, flags);
     }
 
+    /**
+     * @hide
+     */
     private class IEntityIteratorImpl extends IEntityIterator.Stub {
         private final EntityIterator mEntityIterator;
 
@@ -371,6 +352,9 @@
         return adaptor;
     }
 
+    /**
+     * @hide
+     */
     public EntityIterator queryEntities(Uri url, String selection, String[] selectionArgs,
             String sortOrder)
             throws RemoteException {
@@ -396,6 +380,9 @@
         return new RemoteEntityIterator(IEntityIterator.Stub.asInterface(entityIteratorBinder));
     }
 
+    /**
+     * @hide
+     */
     static class RemoteEntityIterator implements EntityIterator {
         private final IEntityIterator mEntityIterator;
         RemoteEntityIterator(IEntityIterator entityIterator) {
@@ -506,44 +493,6 @@
         return results;
     }
 
-    public Uri insertEntity(Uri uri, Entity entity) throws RemoteException {
-        Parcel data = Parcel.obtain();
-        Parcel reply = Parcel.obtain();
-
-        try {
-            data.writeInterfaceToken(IContentProvider.descriptor);
-            uri.writeToParcel(data, 0);
-            data.writeParcelable(entity, 0);
-
-            mRemote.transact(IContentProvider.INSERT_ENTITIES_TRANSACTION, data, reply, 0);
-
-            DatabaseUtils.readExceptionFromParcel(reply);
-            return Uri.CREATOR.createFromParcel(reply);
-        } finally {
-            data.recycle();
-            reply.recycle();
-        }
-    }
-
-    public int updateEntity(Uri uri, Entity entity) throws RemoteException {
-        Parcel data = Parcel.obtain();
-        Parcel reply = Parcel.obtain();
-
-        try {
-            data.writeInterfaceToken(IContentProvider.descriptor);
-            uri.writeToParcel(data, 0);
-            data.writeParcelable(entity, 0);
-
-            mRemote.transact(IContentProvider.UPDATE_ENTITIES_TRANSACTION, data, reply, 0);
-
-            DatabaseUtils.readExceptionFromParcel(reply);
-            return reply.readInt();
-        } finally {
-            data.recycle();
-            reply.recycle();
-        }
-    }
-
     public int delete(Uri url, String selection, String[] selectionArgs)
             throws RemoteException {
         Parcel data = Parcel.obtain();
diff --git a/core/java/android/content/ContentResolver.java b/core/java/android/content/ContentResolver.java
index c9edc41c..c4b0807 100644
--- a/core/java/android/content/ContentResolver.java
+++ b/core/java/android/content/ContentResolver.java
@@ -218,6 +218,7 @@
     /**
      * EntityIterator wrapper that releases the associated ContentProviderClient when the
      * iterator is closed.
+     * @hide
      */
     private class EntityIteratorWrapper implements EntityIterator {
         private final EntityIterator mInner;
@@ -283,6 +284,7 @@
      * @throws RemoteException thrown if a RemoteException is encountered while attempting
      *   to communicate with a remote provider.
      * @throws IllegalArgumentException thrown if there is no provider that matches the uri
+     * @hide
      */
     public final EntityIterator queryEntities(Uri uri,
             String selection, String[] selectionArgs, String sortOrder) throws RemoteException {
diff --git a/core/java/android/content/Entity.java b/core/java/android/content/Entity.java
index 325dce5..ee8112e 100644
--- a/core/java/android/content/Entity.java
+++ b/core/java/android/content/Entity.java
@@ -26,6 +26,7 @@
 /**
  * Objects that pass through the ContentProvider and ContentResolver's methods that deal with
  * Entities must implement this abstract base class and thus themselves be Parcelable.
+ * @hide
  */
 public final class Entity implements Parcelable {
     final private ContentValues mValues;
diff --git a/core/java/android/content/EntityIterator.java b/core/java/android/content/EntityIterator.java
index 3cc1040..1b73439 100644
--- a/core/java/android/content/EntityIterator.java
+++ b/core/java/android/content/EntityIterator.java
@@ -18,6 +18,9 @@
 
 import android.os.RemoteException;
 
+/**
+ * @hide
+ */
 public interface EntityIterator {
     /**
      * Returns whether there are more elements to iterate, i.e. whether the
diff --git a/core/java/android/content/IContentProvider.java b/core/java/android/content/IContentProvider.java
index 7e5aba5..0798adf 100644
--- a/core/java/android/content/IContentProvider.java
+++ b/core/java/android/content/IContentProvider.java
@@ -44,6 +44,9 @@
             CursorWindow window) throws RemoteException;
     public Cursor query(Uri url, String[] projection, String selection,
             String[] selectionArgs, String sortOrder) throws RemoteException;
+    /**
+     * @hide
+     */
     public EntityIterator queryEntities(Uri url, String selection,
             String[] selectionArgs, String sortOrder)
             throws RemoteException;
@@ -51,12 +54,10 @@
     public Uri insert(Uri url, ContentValues initialValues)
             throws RemoteException;
     public int bulkInsert(Uri url, ContentValues[] initialValues) throws RemoteException;
-    public Uri insertEntity(Uri uri, Entity entities) throws RemoteException;
     public int delete(Uri url, String selection, String[] selectionArgs)
             throws RemoteException;
     public int update(Uri url, ContentValues values, String selection,
             String[] selectionArgs) throws RemoteException;
-    public int updateEntity(Uri uri, Entity entity) throws RemoteException;
     public ParcelFileDescriptor openFile(Uri url, String mode)
             throws RemoteException, FileNotFoundException;
     public AssetFileDescriptor openAssetFile(Uri url, String mode)
@@ -75,8 +76,9 @@
     static final int BULK_INSERT_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 12;
     static final int OPEN_FILE_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 13;
     static final int OPEN_ASSET_FILE_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 14;
-    static final int INSERT_ENTITIES_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 16;
-    static final int UPDATE_ENTITIES_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 17;
+    /**
+     * @hide
+     */
     static final int QUERY_ENTITIES_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 18;
     static final int APPLY_BATCH_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 19;
 }
diff --git a/core/java/android/content/SyncContext.java b/core/java/android/content/SyncContext.java
index f4faa04..587586d 100644
--- a/core/java/android/content/SyncContext.java
+++ b/core/java/android/content/SyncContext.java
@@ -18,16 +18,17 @@
 
 import android.os.RemoteException;
 import android.os.SystemClock;
+import android.os.IBinder;
 
-/**
- * @hide
- */
 public class SyncContext {
     private ISyncContext mSyncContext;
     private long mLastHeartbeatSendTime;
 
     private static final long HEARTBEAT_SEND_INTERVAL_IN_MS = 1000;
 
+    /**
+     * @hide
+     */
     public SyncContext(ISyncContext syncContextInterface) {
         mSyncContext = syncContextInterface;
         mLastHeartbeatSendTime = 0;
@@ -38,6 +39,8 @@
      * {@link #updateHeartbeat}, so it also takes the place of a call to that.
      *
      * @param message the current status message for this sync
+     *
+     * @hide
      */
     public void setStatusText(String message) {
         updateHeartbeat();
@@ -48,7 +51,7 @@
      * downloads or sends records to/from the server, this may be called after each record
      * is downloaded or uploaded.
      */
-    public void updateHeartbeat() {
+    private void updateHeartbeat() {
         final long now = SystemClock.elapsedRealtime();
         if (now < mLastHeartbeatSendTime + HEARTBEAT_SEND_INTERVAL_IN_MS) return;
         try {
@@ -67,7 +70,7 @@
         }
     }
 
-    public ISyncContext getISyncContext() {
-        return mSyncContext;
+    public IBinder getSyncContextBinder() {
+        return mSyncContext.asBinder();
     }
 }
diff --git a/core/java/android/content/SyncResult.java b/core/java/android/content/SyncResult.java
index 4c201e6..57161b6 100644
--- a/core/java/android/content/SyncResult.java
+++ b/core/java/android/content/SyncResult.java
@@ -5,8 +5,6 @@
 
 /**
  * This class is used to store information about the result of a sync
- * 
- * @hide
  */
 public final class SyncResult implements Parcelable {
     public final boolean syncAlreadyInProgress;
diff --git a/core/java/android/content/SyncUIContext.java b/core/java/android/content/SyncUIContext.java
deleted file mode 100644
index 6dde004..0000000
--- a/core/java/android/content/SyncUIContext.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2006 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.content;
-
-/**
- * Class with callback methods for SyncAdapters and ContentProviders
- * that are called in response to the calls on SyncContext.  This class
- * is really only meant to be used by the Sync UI activities.
- *
- * <p>All of the onXXX callback methods here are called from a handler
- * on the thread this object was created in.
- *
- * <p>This interface is unused. It should be removed.
- * 
- * @hide
- */
-@Deprecated
-public interface SyncUIContext {
-    
-    void setStatusText(String text);
-
-    Context context();
-}
diff --git a/core/java/android/content/pm/PackageParser.java b/core/java/android/content/pm/PackageParser.java
index 75ba26f..54015c9 100644
--- a/core/java/android/content/pm/PackageParser.java
+++ b/core/java/android/content/pm/PackageParser.java
@@ -27,6 +27,7 @@
 import android.content.res.Resources;
 import android.content.res.TypedArray;
 import android.content.res.XmlResourceParser;
+import android.os.Build;
 import android.os.Bundle;
 import android.os.PatternMatcher;
 import android.util.AttributeSet;
@@ -84,8 +85,9 @@
 
     private String mArchiveSourcePath;
     private String[] mSeparateProcesses;
-    private int mSdkVersion;
-    private String mSdkCodename;
+    private static final int SDK_VERSION = Build.VERSION.SDK_INT;
+    private static final String SDK_CODENAME = "REL".equals(Build.VERSION.CODENAME)
+            ? null : Build.VERSION.CODENAME;
 
     private int mParseError = PackageManager.INSTALL_SUCCEEDED;
 
@@ -152,11 +154,6 @@
         mSeparateProcesses = procs;
     }
 
-    public void setSdkVersion(int sdkVersion, String codename) {
-        mSdkVersion = sdkVersion;
-        mSdkCodename = codename;
-    }
-
     private static final boolean isPackageFilename(String name) {
         return name.endsWith(".apk");
     }
@@ -825,7 +822,7 @@
                 XmlUtils.skipCurrentTag(parser);
 
             } else if (tagName.equals("uses-sdk")) {
-                if (mSdkVersion > 0) {
+                if (SDK_VERSION > 0) {
                     sa = res.obtainAttributes(attrs,
                             com.android.internal.R.styleable.AndroidManifestUsesSdk);
 
@@ -858,15 +855,15 @@
                     
                     int maxVers = sa.getInt(
                             com.android.internal.R.styleable.AndroidManifestUsesSdk_maxSdkVersion,
-                            mSdkVersion);
+                            SDK_VERSION);
 
                     sa.recycle();
 
                     if (minCode != null) {
-                        if (!minCode.equals(mSdkCodename)) {
-                            if (mSdkCodename != null) {
+                        if (!minCode.equals(SDK_CODENAME)) {
+                            if (SDK_CODENAME != null) {
                                 outError[0] = "Requires development platform " + minCode
-                                        + " (current platform is " + mSdkCodename + ")";
+                                        + " (current platform is " + SDK_CODENAME + ")";
                             } else {
                                 outError[0] = "Requires development platform " + minCode
                                         + " but this is a release platform.";
@@ -874,18 +871,18 @@
                             mParseError = PackageManager.INSTALL_FAILED_OLDER_SDK;
                             return null;
                         }
-                    } else if (minVers > mSdkVersion) {
+                    } else if (minVers > SDK_VERSION) {
                         outError[0] = "Requires newer sdk version #" + minVers
-                                + " (current version is #" + mSdkVersion + ")";
+                                + " (current version is #" + SDK_VERSION + ")";
                         mParseError = PackageManager.INSTALL_FAILED_OLDER_SDK;
                         return null;
                     }
                     
                     if (targetCode != null) {
-                        if (!targetCode.equals(mSdkCodename)) {
-                            if (mSdkCodename != null) {
+                        if (!targetCode.equals(SDK_CODENAME)) {
+                            if (SDK_CODENAME != null) {
                                 outError[0] = "Requires development platform " + targetCode
-                                        + " (current platform is " + mSdkCodename + ")";
+                                        + " (current platform is " + SDK_CODENAME + ")";
                             } else {
                                 outError[0] = "Requires development platform " + targetCode
                                         + " but this is a release platform.";
@@ -900,9 +897,9 @@
                         pkg.applicationInfo.targetSdkVersion = targetVers;
                     }
                     
-                    if (maxVers < mSdkVersion) {
+                    if (maxVers < SDK_VERSION) {
                         outError[0] = "Requires older sdk version #" + maxVers
-                                + " (current version is #" + mSdkVersion + ")";
+                                + " (current version is #" + SDK_VERSION + ")";
                         mParseError = PackageManager.INSTALL_FAILED_OLDER_SDK;
                         return null;
                     }
diff --git a/core/java/android/hardware/Camera.java b/core/java/android/hardware/Camera.java
index 66f5740..3806fa8 100644
--- a/core/java/android/hardware/Camera.java
+++ b/core/java/android/hardware/Camera.java
@@ -301,7 +301,7 @@
 
             case CAMERA_MSG_ZOOM:
                 if (mZoomCallback != null) {
-                    mZoomCallback.onZoomUpdate(msg.arg1, mCamera);
+                    mZoomCallback.onZoomUpdate(msg.arg1, msg.arg2 != 0, mCamera);
                 }
                 return;
 
@@ -468,6 +468,26 @@
     }
 
     /**
+     * Zooms to the requested value smoothly. Driver will generate {@link
+     * #ZoomCallback} for the current zoom value and whether zoom is stopped.
+     * The applications can call {@link #stopSmoothZoom} to stop the zoom
+     * earlier. The applications should not call startSmoothZoom again or {@link
+     * android.hardware.Camera.Parameters#setZoom(int)} before the zoom stops.
+     *
+     * @param value zoom value. The valid range is 0 to {@link
+     *              android.hardware.Camera.Parameters#getMaxZoom}.
+     * @hide
+     */
+    public native final void startSmoothZoom(int value);
+
+    /**
+     * Stops the smooth zoom. The applications should wait for the {@link
+     * #ZoomCallback} to know when the zoom is actually stopped.
+     * @hide
+     */
+    public native final void stopSmoothZoom();
+
+    /**
      * Handles the zoom callback.
      *
      * @hide
@@ -476,18 +496,21 @@
     {
         /**
          * Callback for zoom updates
-         * @param zoomLevel   new zoom level in 1/1000 increments,
-         * e.g. a zoom of 3.2x is stored as 3200. Accuracy of the
-         * value is dependent on the hardware implementation. Not
-         * all devices will generate this callback.
+         *
+         * @param zoomValue the current zoom value. In smooth zoom mode, camera
+         *                  generates this callback for every new zoom value.
+         * @param stopped whether smooth zoom is stopped. If the value is true,
+         *                this is the last zoom update for the application.
+         *
          * @param camera  the Camera service object
+         * @see android.hardware.Camera.Parameters#startSmoothZoom
          */
-        void onZoomUpdate(int zoomLevel, Camera camera);
+        void onZoomUpdate(int zoomValue, boolean stopped, Camera camera);
     };
 
     /**
-     * Registers a callback to be invoked when the zoom
-     * level is updated by the camera driver.
+     * Registers a callback to be invoked when the zoom value is updated by the
+     * camera driver during smooth zoom.
      * @param cb the callback to run
      * @hide
      */
@@ -642,20 +665,24 @@
          * Flash will not be fired.
          */
         public static final String FLASH_MODE_OFF = "off";
+
         /**
          * Flash will be fired automatically when required. The flash may be fired
          * during preview, auto-focus, or snapshot depending on the driver.
          */
         public static final String FLASH_MODE_AUTO = "auto";
+
         /**
          * Flash will always be fired during snapshot. The flash may also be
          * fired during preview or auto-focus depending on the driver.
          */
         public static final String FLASH_MODE_ON = "on";
+
         /**
          * Flash will be fired in red-eye reduction mode.
          */
         public static final String FLASH_MODE_RED_EYE = "red-eye";
+
         /**
          * Constant emission of light during preview, auto-focus and snapshot.
          * This can also be used for video recording.
@@ -684,12 +711,14 @@
          * Auto-focus mode.
          */
         public static final String FOCUS_MODE_AUTO = "auto";
+
         /**
          * Focus is set at infinity. Applications should not call
          * {@link #autoFocus(AutoFocusCallback)} in this mode.
          */
         public static final String FOCUS_MODE_INFINITY = "infinity";
         public static final String FOCUS_MODE_MACRO = "macro";
+
         /**
          * Focus is fixed. The camera is always in this mode if the focus is not
          * adjustable. If the camera has auto-focus, this mode can fix the
@@ -1367,6 +1396,80 @@
             return split(str);
         }
 
+        /**
+         * Gets current zoom value. This also works when smooth zoom is in
+         * progress.
+         *
+         * @return the current zoom value. The range is 0 to {@link
+         *          #getMaxZoom}.
+         * @hide
+         */
+        public int getZoom() {
+            return getInt("zoom");
+        }
+
+        /**
+         * Sets current zoom value. If {@link #startSmoothZoom(int)} has been
+         * called and zoom is not stopped yet, applications should not call this
+         * method.
+         *
+         * @param value zoom value. The valid range is 0 to {@link #getMaxZoom}.
+         * @hide
+         */
+        public void setZoom(int value) {
+            set("zoom", value);
+        }
+
+        /**
+         * Returns true if zoom is supported. Applications should call this
+         * before using other zoom methods.
+         *
+         * @return true if zoom is supported.
+         * @hide
+         */
+        public boolean isZoomSupported() {
+            String str = get("zoom-supported");
+            return "true".equals(str);
+        }
+
+        /**
+         * Gets the maximum zoom value allowed for snapshot. This is the maximum
+         * value that applications can set to {@link #setZoom(int)}.
+         *
+         * @return the maximum zoom value supported by the camera.
+         * @hide
+         */
+        public int getMaxZoom() {
+            return getInt("max-zoom");
+        }
+
+        /**
+         * Gets the zoom factors of all zoom values.
+         *
+         * @return the zoom factors in 1/100 increments. Ex: a zoom of 3.2x is
+         *         returned as 320. Accuracy of the value is dependent on the
+         *         hardware implementation. The first element of the list is the
+         *         zoom factor of first zoom value. If the first zoom value is
+         *         0, the zoom factor should be 100. The last element is the
+         *         zoom factor of zoom value {@link #getMaxZoom}.
+         * @hide
+         */
+        public List<Integer> getZoomFactors() {
+            return splitInt(get("zoom-factors"));
+        }
+
+        /**
+         * Returns true if smooth zoom is supported. Applications should call
+         * this before using other smooth zoom methods.
+         *
+         * @return true if smooth zoom is supported.
+         * @hide
+         */
+        public boolean isSmoothZoomSupported() {
+            String str = get("smooth-zoom-supported");
+            return "true".equals(str);
+        }
+
         // Splits a comma delimited string to an ArrayList of String.
         // Return null if the passing string is null or the size is 0.
         private ArrayList<String> split(String str) {
diff --git a/core/java/android/net/MobileDataStateTracker.java b/core/java/android/net/MobileDataStateTracker.java
index b619fee..e5e6db9 100644
--- a/core/java/android/net/MobileDataStateTracker.java
+++ b/core/java/android/net/MobileDataStateTracker.java
@@ -42,7 +42,7 @@
 public class MobileDataStateTracker extends NetworkStateTracker {
 
     private static final String TAG = "MobileDataStateTracker";
-    private static final boolean DBG = false;
+    private static final boolean DBG = true;
 
     private Phone.DataState mMobileDataState;
     private ITelephony mPhoneService;
@@ -142,11 +142,6 @@
 
                     boolean unavailable = intent.getBooleanExtra(Phone.NETWORK_UNAVAILABLE_KEY,
                             false);
-                    if (DBG) Log.d(TAG, mApnType + " Received " + intent.getAction() +
-                            " broadcast - state = " + state + ", oldstate = " + mMobileDataState +
-                            ", unavailable = " + unavailable + ", reason = " +
-                            (reason == null ? "(unspecified)" : reason) +
-                            ", apnTypeList = " + apnTypeList);
 
                     // set this regardless of the apnTypeList.  It's all the same radio/network
                     // underneath
@@ -166,14 +161,17 @@
                                         " for " + mApnType);
                                 mInterfaceName = intent.getStringExtra(Phone.DATA_IFACE_NAME_KEY);
                             }
-                            if (DBG) Log.d(TAG, "  dropped - mEnabled = false");
                             return;
                         }
                     } else {
-                        if (DBG) Log.d(TAG, "  dropped - wrong Apn");
                         return;
                     }
 
+                    if (DBG) Log.d(TAG, mApnType + " Received state= " + state + ", old= " +
+                            mMobileDataState + ", reason= " +
+                            (reason == null ? "(unspecified)" : reason) +
+                            ", apnTypeList= " + apnTypeList);
+
                     if (mMobileDataState != state) {
                         mMobileDataState = state;
                         switch (state) {
diff --git a/core/java/android/provider/ContactsContract.java b/core/java/android/provider/ContactsContract.java
index 1d6c8ef..5ea6539 100644
--- a/core/java/android/provider/ContactsContract.java
+++ b/core/java/android/provider/ContactsContract.java
@@ -673,6 +673,30 @@
              */
             public static final String CONTENT_DIRECTORY = "data";
         }
+
+        /**
+         * A sub-directory of a single raw contact that contains all of their {@link Data} rows.
+         * To access this directory append {@link Entity#CONTENT_DIRECTORY} to the contact URI.
+         */
+        public static final class Entity implements BaseColumns, DataColumns {
+            /**
+             * no public constructor since this is a utility class
+             */
+            private Entity() {
+            }
+
+            /**
+             * The directory twig for this sub-table
+             */
+            public static final String CONTENT_DIRECTORY = "entity";
+
+            /**
+             * The ID of the data column. The value will be null if this raw contact has no
+             * data rows.
+             * <P>Type: INTEGER</P>
+             */
+            public static final String DATA_ID = "data_id";
+        }
     }
 
     private interface StatusColumns extends Im.CommonPresenceColumns {
@@ -869,6 +893,51 @@
         }
     }
 
+    /**
+     * Constants for the raw contacts entities table, which can be though of as an outer join
+     * of the raw_contacts table with the data table.
+     */
+    public final static class RawContactsEntity
+            implements BaseColumns, DataColumns, RawContactsColumns {
+        /**
+         * This utility class cannot be instantiated
+         */
+        private RawContactsEntity() {}
+
+        /**
+         * The content:// style URI for this table
+         */
+        public static final Uri CONTENT_URI =
+                Uri.withAppendedPath(AUTHORITY_URI, "raw_contact_entities");
+
+        /**
+         * The MIME type of {@link #CONTENT_URI} providing a directory of raw contact entities.
+         */
+        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/raw_contact_entity";
+
+        /**
+         * If {@link #FOR_EXPORT_ONLY} is explicitly set to "1", returned Cursor toward
+         * Data.CONTENT_URI contains only exportable data.
+         *
+         * This flag is useful (currently) only for vCard exporter in Contacts app, which
+         * needs to exclude "un-exportable" data from available data to export, while
+         * Contacts app itself has priviledge to access all data including "un-expotable"
+         * ones and providers return all of them regardless of the callers' intention.
+         * <P>Type: INTEGER</p>
+         *
+         * @hide Maybe available only in Eclair and not really ready for public use.
+         * TODO: remove, or implement this feature completely. As of now (Eclair),
+         * we only use this flag in queryEntities(), not query().
+         */
+        public static final String FOR_EXPORT_ONLY = "for_export_only";
+
+        /**
+         * The ID of the data column. The value will be null if this raw contact has no data rows.
+         * <P>Type: INTEGER</P>
+         */
+        public static final String DATA_ID = "data_id";
+    }
+
     private interface PhoneLookupColumns {
         /**
          * The phone number as the user entered it.
diff --git a/core/java/android/widget/AppSecurityPermissions.java b/core/java/android/widget/AppSecurityPermissions.java
index 6579660..a09f23c 100755
--- a/core/java/android/widget/AppSecurityPermissions.java
+++ b/core/java/android/widget/AppSecurityPermissions.java
@@ -26,13 +26,10 @@
 import android.content.pm.PermissionInfo;
 import android.content.pm.PackageManager.NameNotFoundException;
 import android.graphics.drawable.Drawable;
-import android.net.Uri;
-import android.util.DisplayMetrics;
 import android.util.Log;
 import android.view.LayoutInflater;
 import android.view.View;
 
-import java.io.File;
 import java.text.Collator;
 import java.util.ArrayList;
 import java.util.Collections;
@@ -149,15 +146,6 @@
         }
     }
     
-    public PackageParser.Package getPackageInfo(Uri packageURI) {
-        final String archiveFilePath = packageURI.getPath();
-        PackageParser packageParser = new PackageParser(archiveFilePath);
-        File sourceFile = new File(archiveFilePath);
-        DisplayMetrics metrics = new DisplayMetrics();
-        metrics.setToDefaults();
-        return packageParser.parsePackage(sourceFile, archiveFilePath, metrics, 0);
-    }
-    
     private void getAllUsedPermissions(int sharedUid, Set<PermissionInfo> permSet) {
         String sharedPkgList[] = mPm.getPackagesForUid(sharedUid);
         if(sharedPkgList == null || (sharedPkgList.length == 0)) {
diff --git a/core/java/com/android/internal/widget/RotarySelector.java b/core/java/com/android/internal/widget/RotarySelector.java
index 0998744..e103a5b 100644
--- a/core/java/com/android/internal/widget/RotarySelector.java
+++ b/core/java/com/android/internal/widget/RotarySelector.java
@@ -48,6 +48,7 @@
 
     private static final String LOG_TAG = "RotarySelector";
     private static final boolean DBG = false;
+    private static final boolean VISUAL_DEBUG = false;
 
     // Listener for onDialTrigger() callbacks.
     private OnDialTriggerListener mOnDialTriggerListener;
@@ -290,10 +291,12 @@
 
         final int width = getWidth();
 
-        // DEBUG: draw bounding box around widget
-//        mPaint.setColor(Color.RED);
-//        mPaint.setStyle(Paint.Style.STROKE);
-//        canvas.drawRect(0, 0, width, getHeight(), mPaint);
+        if (VISUAL_DEBUG) {
+            // draw bounding box around widget
+            mPaint.setColor(0xffff0000);
+            mPaint.setStyle(Paint.Style.STROKE);
+            canvas.drawRect(0, 0, width, getHeight(), mPaint);
+        }
 
         final int height = getHeight();
 
@@ -336,21 +339,18 @@
         final int bgTop = isHoriz() ?
                 height - bgHeight:
                 width - bgHeight;
-        // DEBUG: draw circle bounding arc drawable: good sanity check we're doing the math
-        // correctly
-//        float or = OUTER_ROTARY_RADIUS_DIP * mDensity;
-//        final int vOffset = mBackgroundWidth - height;
-//        final int midX = isHoriz() ?
-//                width / 2 :
-//                mBackgroundWidth / 2 - vOffset;
-//        if (isHoriz()) {
-//            canvas.drawCircle(midX, or + bgTop, or, mPaint);
-//        } else {
-//            canvas.drawCircle(or + bgTop, midX, or, mPaint);
-//        }
 
-        // dimple selection
-        Bitmap dimpleBitmap = mGrabbedState == NOTHING_GRABBED ? mDimple : mDimpleDim;
+        if (VISUAL_DEBUG) {
+            // draw circle bounding arc drawable: good sanity check we're doing the math correctly
+            float or = OUTER_ROTARY_RADIUS_DIP * mDensity;
+            final int vOffset = mBackgroundWidth - height;
+            final int midX = isHoriz() ? width / 2 : mBackgroundWidth / 2 - vOffset;
+            if (isHoriz()) {
+                canvas.drawCircle(midX, or + bgTop, or, mPaint);
+            } else {
+                canvas.drawCircle(or + bgTop, midX, or, mPaint);
+            }
+        }
 
         // left dimple / icon
         {
@@ -360,17 +360,13 @@
                     mInnerRadius,
                     mOuterRadius,
                     xOffset);
-            if (isHoriz()) {
-                drawCentered(dimpleBitmap, canvas, xOffset, drawableY + bgTop);
-                if (mGrabbedState != RIGHT_HANDLE_GRABBED) {
-                    drawCentered(mLeftHandleIcon, canvas, xOffset, drawableY + bgTop);
-                }
+            final int x = isHoriz() ? xOffset : drawableY + bgTop;
+            final int y = isHoriz() ? drawableY + bgTop : height - xOffset;
+            if (mGrabbedState != RIGHT_HANDLE_GRABBED) {
+                drawCentered(mDimple, canvas, x, y);
+                drawCentered(mLeftHandleIcon, canvas, x, y);
             } else {
-                // vertical
-                drawCentered(dimpleBitmap, canvas, drawableY + bgTop, height - xOffset);
-                if (mGrabbedState != RIGHT_HANDLE_GRABBED) {
-                    drawCentered(mLeftHandleIcon, canvas, drawableY + bgTop, height - xOffset);
-                }
+                drawCentered(mDimpleDim, canvas, x, y);
             }
         }
 
@@ -386,10 +382,10 @@
                     xOffset);
 
             if (isHoriz()) {
-                drawCentered(dimpleBitmap, canvas, xOffset, drawableY + bgTop);
+                drawCentered(mDimpleDim, canvas, xOffset, drawableY + bgTop);
             } else {
                 // vertical
-                drawCentered(dimpleBitmap, canvas, drawableY + bgTop, height - xOffset);
+                drawCentered(mDimpleDim, canvas, drawableY + bgTop, height - xOffset);
             }
         }
 
@@ -402,17 +398,13 @@
                     mOuterRadius,
                     xOffset);
 
-            if (isHoriz()) {
-                drawCentered(dimpleBitmap, canvas, xOffset, drawableY + bgTop);
-                if (mGrabbedState != LEFT_HANDLE_GRABBED) {
-                    drawCentered(mRightHandleIcon, canvas, xOffset, drawableY + bgTop);
-                }
+            final int x = isHoriz() ? xOffset : drawableY + bgTop;
+            final int y = isHoriz() ? drawableY + bgTop : height - xOffset;
+            if (mGrabbedState != LEFT_HANDLE_GRABBED) {
+                drawCentered(mDimple, canvas, x, y);
+                drawCentered(mRightHandleIcon, canvas, x, y);
             } else {
-                // vertical
-                drawCentered(dimpleBitmap, canvas, drawableY + bgTop, height - xOffset);
-                if (mGrabbedState != LEFT_HANDLE_GRABBED) {
-                    drawCentered(mRightHandleIcon, canvas, drawableY + bgTop, height - xOffset);
-                }
+                drawCentered(mDimpleDim, canvas, x, y);
             }
         }
 
@@ -427,9 +419,9 @@
                     dimpleLeft);
 
             if (isHoriz()) {
-                drawCentered(dimpleBitmap, canvas, dimpleLeft, drawableY + bgTop);
+                drawCentered(mDimpleDim, canvas, dimpleLeft, drawableY + bgTop);
             } else {
-                drawCentered(dimpleBitmap, canvas, drawableY + bgTop, height - dimpleLeft);
+                drawCentered(mDimpleDim, canvas, drawableY + bgTop, height - dimpleLeft);
             }
             dimpleLeft -= mDimpleSpacing;
         }
@@ -445,9 +437,9 @@
                     dimpleRight);
 
             if (isHoriz()) {
-                drawCentered(dimpleBitmap, canvas, dimpleRight, drawableY + bgTop);
+                drawCentered(mDimpleDim, canvas, dimpleRight, drawableY + bgTop);
             } else {
-                drawCentered(dimpleBitmap, canvas, drawableY + bgTop, height - dimpleRight);
+                drawCentered(mDimpleDim, canvas, drawableY + bgTop, height - dimpleRight);
             }
             dimpleRight += mDimpleSpacing;
         }
diff --git a/core/jni/android_hardware_Camera.cpp b/core/jni/android_hardware_Camera.cpp
index e944654..5b6bd35 100644
--- a/core/jni/android_hardware_Camera.cpp
+++ b/core/jni/android_hardware_Camera.cpp
@@ -413,6 +413,28 @@
     }
 }
 
+static void android_hardware_Camera_startSmoothZoom(JNIEnv *env, jobject thiz, jint value)
+{
+    LOGD("startSmoothZoom");
+    sp<Camera> camera = get_native_camera(env, thiz, NULL);
+    if (camera == 0) return;
+
+    if (camera->sendCommand(CAMERA_CMD_START_SMOOTH_ZOOM, value, 0) != NO_ERROR) {
+        jniThrowException(env, "java/lang/RuntimeException", "start smooth zoom failed");
+    }
+}
+
+static void android_hardware_Camera_stopSmoothZoom(JNIEnv *env, jobject thiz)
+{
+    LOGD("stopSmoothZoom");
+    sp<Camera> camera = get_native_camera(env, thiz, NULL);
+    if (camera == 0) return;
+
+    if (camera->sendCommand(CAMERA_CMD_STOP_SMOOTH_ZOOM, 0, 0) != NO_ERROR) {
+        jniThrowException(env, "java/lang/RuntimeException", "stop smooth zoom failed");
+    }
+}
+
 //-------------------------------------------------
 
 static JNINativeMethod camMethods[] = {
@@ -461,6 +483,12 @@
   { "unlock",
     "()V",
     (void*)android_hardware_Camera_unlock },
+  { "startSmoothZoom",
+    "(I)V",
+    (void *)android_hardware_Camera_startSmoothZoom },
+  { "stopSmoothZoom",
+    "()V",
+    (void *)android_hardware_Camera_stopSmoothZoom },
 };
 
 struct field {
diff --git a/graphics/java/android/renderscript/RenderScript.java b/graphics/java/android/renderscript/RenderScript.java
index 6b0b696..1f2ea38 100644
--- a/graphics/java/android/renderscript/RenderScript.java
+++ b/graphics/java/android/renderscript/RenderScript.java
@@ -75,6 +75,9 @@
     native void nContextAddDefineF(String name, float value);
     native void nContextPause();
     native void nContextResume();
+    native int nContextGetMessage(int[] data, boolean wait);
+    native void nContextInitToClient();
+    native void nContextDeinitToClient();
 
     native void nAssignName(int obj, byte[] name);
     native void nObjDestroy(int id);
@@ -190,6 +193,7 @@
     private int     mContext;
     @SuppressWarnings({"FieldCanBeLocal"})
     private Surface mSurface;
+    private MessageThread mMessageThread;
 
 
     Element mElement_USER_U8;
@@ -214,6 +218,52 @@
     ///////////////////////////////////////////////////////////////////////////////////
     //
 
+    public static class RSMessage implements Runnable {
+        protected int[] mData;
+        protected int mID;
+        public void run() {
+        }
+    }
+    public RSMessage mMessageCallback = null;
+
+    private static class MessageThread extends Thread {
+        RenderScript mRS;
+        boolean mRun = true;
+
+        MessageThread(RenderScript rs) {
+            super("RSMessageThread");
+            mRS = rs;
+
+        }
+
+        public void run() {
+            // This function is a temporary solution.  The final solution will
+            // used typed allocations where the message id is the type indicator.
+            int[] rbuf = new int[16];
+            mRS.nContextInitToClient();
+            while(mRun) {
+                int msg = mRS.nContextGetMessage(rbuf, true);
+                if (msg == 0) {
+                    // Should only happen during teardown.
+                    // But we want to avoid starving other threads during
+                    // teardown by yielding until the next line in the destructor
+                    // can execute to set mRun = false
+                    try {
+                        sleep(1, 0);
+                    } catch(InterruptedException e) {
+                    }
+                }
+                if(mRS.mMessageCallback != null) {
+                    mRS.mMessageCallback.mData = rbuf;
+                    mRS.mMessageCallback.mID = msg;
+                    mRS.mMessageCallback.run();
+                }
+                //Log.d("rs", "MessageThread msg " + msg + " v1 " + rbuf[0] + " v2 " + rbuf[1] + " v3 " +rbuf[2]);
+            }
+            Log.d("rs", "MessageThread exiting.");
+        }
+    }
+
     public RenderScript(Surface sur, boolean useDepth, boolean forceSW) {
         mSurface = sur;
         mDev = nDeviceCreate();
@@ -222,9 +272,14 @@
         }
         mContext = nContextCreate(mDev, mSurface, 0, useDepth);
         Element.initPredefined(this);
+        mMessageThread = new MessageThread(this);
+        mMessageThread.start();
     }
 
     public void destroy() {
+        nContextDeinitToClient();
+        mMessageThread.mRun = false;
+
         nContextDestroy(mContext);
         mContext = 0;
 
diff --git a/graphics/jni/android_renderscript_RenderScript.cpp b/graphics/jni/android_renderscript_RenderScript.cpp
index 9054b65..fa3baa20 100644
--- a/graphics/jni/android_renderscript_RenderScript.cpp
+++ b/graphics/jni/android_renderscript_RenderScript.cpp
@@ -194,6 +194,37 @@
     rsContextResume(con);
 }
 
+static jint
+nContextGetMessage(JNIEnv *_env, jobject _this, jintArray data, jboolean wait)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    jint len = _env->GetArrayLength(data);
+    LOG_API("nContextGetMessage, con(%p), len(%i)", con, len);
+    jint *ptr = _env->GetIntArrayElements(data, NULL);
+    size_t receiveLen;
+    int id = rsContextGetMessage(con, ptr, &receiveLen, len * 4, wait);
+    if (!id && receiveLen) {
+        LOGE("message receive buffer too small.  %i", receiveLen);
+    }
+    _env->ReleaseIntArrayElements(data, ptr, 0);
+    return id;
+}
+
+static void nContextInitToClient(JNIEnv *_env, jobject _this)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nContextInitToClient, con(%p)", con);
+    rsContextInitToClient(con);
+}
+
+static void nContextDeinitToClient(JNIEnv *_env, jobject _this)
+{
+    RsContext con = (RsContext)(_env->GetIntField(_this, gContextId));
+    LOG_API("nContextDeinitToClient, con(%p)", con);
+    rsContextDeinitToClient(con);
+}
+
+
 static void
 nElementBegin(JNIEnv *_env, jobject _this)
 {
@@ -1303,6 +1334,9 @@
 {"nAssignName",                    "(I[B)V",                               (void*)nAssignName },
 {"nObjDestroy",                    "(I)V",                                 (void*)nObjDestroy },
 {"nObjDestroyOOB",                 "(I)V",                                 (void*)nObjDestroyOOB },
+{"nContextGetMessage",             "([IZ)I",                               (void*)nContextGetMessage },
+{"nContextInitToClient",           "()V",                                  (void*)nContextInitToClient },
+{"nContextDeinitToClient",         "()V",                                  (void*)nContextDeinitToClient },
 
 {"nFileOpen",                      "([B)I",                                (void*)nFileOpen },
 
diff --git a/include/media/ToneGenerator.h b/include/media/ToneGenerator.h
index e8df08e..c884c2c 100644
--- a/include/media/ToneGenerator.h
+++ b/include/media/ToneGenerator.h
@@ -248,6 +248,7 @@
     // only if tone duration is less than about 27 Hours(@44100Hz sampling rate). If this time is exceeded,
     // no crash will occur but tone sequence will show a glitch.
     unsigned int mMaxSmp;  // Maximum number of audio samples played (maximun tone duration)
+    int mDurationMs;  // Maximum tone duration in ms
 
     unsigned short mCurSegment;  // Current segment index in ToneDescriptor segments[]
     unsigned short mCurCount;  // Current sequence repeat count
diff --git a/include/private/ui/SharedBufferStack.h b/include/private/ui/SharedBufferStack.h
index 59cf31c..f6824d9 100644
--- a/include/private/ui/SharedBufferStack.h
+++ b/include/private/ui/SharedBufferStack.h
@@ -139,7 +139,8 @@
 class SharedBufferBase
 {
 public:
-    SharedBufferBase(SharedClient* sharedClient, int surface, int num);
+    SharedBufferBase(SharedClient* sharedClient, int surface, int num,
+            int32_t identity);
     ~SharedBufferBase();
     uint32_t getIdentity();
     status_t getStatus() const;
@@ -150,6 +151,7 @@
     SharedClient* const mSharedClient;
     SharedBufferStack* const mSharedStack;
     const int mNumBuffers;
+    const int mIdentity;
 
     friend struct Update;
     friend struct QueueUpdate;
@@ -180,7 +182,10 @@
     SharedClient& client( *mSharedClient );
     const nsecs_t TIMEOUT = s2ns(1);
     Mutex::Autolock _l(client.lock);
-    while ((condition()==false) && (stack.status == NO_ERROR)) {
+    while ((condition()==false) &&
+            (stack.identity == mIdentity) &&
+            (stack.status == NO_ERROR))
+    {
         status_t err = client.cv.waitRelative(client.lock, TIMEOUT);
         
         // handle errors and timeouts
@@ -190,13 +195,13 @@
                     LOGE("waitForCondition(%s) timed out (identity=%d), "
                         "but condition is true! We recovered but it "
                         "shouldn't happen." , T::name(),
-                        mSharedStack->identity);
+                        stack.identity);
                     break;
                 } else {
                     LOGW("waitForCondition(%s) timed out "
                         "(identity=%d, status=%d). "
                         "CPU may be pegged. trying again.", T::name(),
-                        mSharedStack->identity, mSharedStack->status);
+                        stack.identity, stack.status);
                 }
             } else {
                 LOGE("waitForCondition(%s) error (%s) ",
@@ -205,7 +210,7 @@
             }
         }
     }
-    return stack.status;
+    return (stack.identity != mIdentity) ? status_t(BAD_INDEX) : stack.status;
 }
 
 
@@ -223,8 +228,9 @@
 class SharedBufferClient : public SharedBufferBase
 {
 public:
-    SharedBufferClient(SharedClient* sharedClient, int surface, int num);
-    
+    SharedBufferClient(SharedClient* sharedClient, int surface, int num,
+            int32_t identity);
+
     ssize_t dequeue();
     status_t undoDequeue(int buf);
     
diff --git a/include/private/ui/SurfaceBuffer.h b/include/private/ui/SurfaceBuffer.h
deleted file mode 100644
index 73e517b..0000000
--- a/include/private/ui/SurfaceBuffer.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_UI_PRIVATE_SURFACE_BUFFER_H
-#define ANDROID_UI_PRIVATE_SURFACE_BUFFER_H
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <utils/RefBase.h>
-
-#include <private/ui/android_natives_priv.h>
-
-namespace android {
-
-// ---------------------------------------------------------------------------
-
-class BufferMapper;
-class Parcel;
-class Rect;
-class Surface;
-class SurfaceBuffer;
-
-// ---------------------------------------------------------------------------
-
-class SurfaceBuffer 
-    : public EGLNativeBase<
-        android_native_buffer_t, 
-        SurfaceBuffer, 
-        LightRefBase<SurfaceBuffer> >
-{
-public:
-    status_t lock(uint32_t usage, void** vaddr);
-    status_t lock(uint32_t usage, const Rect& rect, void** vaddr);
-    status_t unlock();
-
-    void setIndex(int index);
-    int getIndex() const;
-    
-protected:
-            SurfaceBuffer();
-            SurfaceBuffer(const Parcel& reply);
-    virtual ~SurfaceBuffer();
-    bool mOwner;
-
-    inline const BufferMapper& getBufferMapper() const { return mBufferMapper; }
-    inline BufferMapper& getBufferMapper() { return mBufferMapper; }
-    
-private:
-    friend class Surface;
-    friend class BpSurface;
-    friend class BnSurface;
-    friend class LightRefBase<SurfaceBuffer>;    
-
-    SurfaceBuffer& operator = (const SurfaceBuffer& rhs);
-    const SurfaceBuffer& operator = (const SurfaceBuffer& rhs) const;
-
-    static status_t writeToParcel(Parcel* reply, 
-            android_native_buffer_t const* buffer);
-    
-    BufferMapper& mBufferMapper;
-    int mIndex;
-};
-
-}; // namespace android
-
-#endif // ANDROID_UI_PRIVATE_SURFACE_BUFFER_H
-
diff --git a/include/private/ui/android_natives_priv.h b/include/private/ui/android_natives_priv.h
index 9c92af8..6b9f524 100644
--- a/include/private/ui/android_natives_priv.h
+++ b/include/private/ui/android_natives_priv.h
@@ -14,49 +14,4 @@
  * limitations under the License.
  */
 
-#ifndef ANDROID_ANDROID_NATIVES_PRIV_H
-#define ANDROID_ANDROID_NATIVES_PRIV_H
-
-#include <ui/egl/android_natives.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*****************************************************************************/
-
-typedef struct android_native_buffer_t
-{
-#ifdef __cplusplus
-    android_native_buffer_t() { 
-        common.magic = ANDROID_NATIVE_BUFFER_MAGIC;
-        common.version = sizeof(android_native_buffer_t);
-        memset(common.reserved, 0, sizeof(common.reserved));
-    }
-#endif
-
-    struct android_native_base_t common;
-
-    int width;
-    int height;
-    int stride;
-    int format;
-    int usage;
-    
-    void* reserved[2];
-
-    buffer_handle_t handle;
-
-    void* reserved_proc[8];
-} android_native_buffer_t;
-
-
-/*****************************************************************************/
-
-#ifdef __cplusplus
-}
-#endif
-
-/*****************************************************************************/
-
-#endif /* ANDROID_ANDROID_NATIVES_PRIV_H */
+#include <ui/android_native_buffer.h>
diff --git a/include/private/ui/sw_gralloc_handle.h b/include/private/ui/sw_gralloc_handle.h
new file mode 100644
index 0000000..b3d333e
--- /dev/null
+++ b/include/private/ui/sw_gralloc_handle.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_UI_PRIVATE_SW_GRALLOC_HANDLE_H
+#define ANDROID_UI_PRIVATE_SW_GRALLOC_HANDLE_H
+
+#include <stdint.h>
+#include <limits.h>
+#include <sys/cdefs.h>
+#include <hardware/gralloc.h>
+#include <errno.h>
+
+#include <cutils/native_handle.h>
+
+namespace android {
+
+/*****************************************************************************/
+
+struct sw_gralloc_handle_t : public native_handle 
+{
+    // file-descriptors
+    int     fd;
+    // ints
+    int     magic;
+    int     size;
+    int     base;
+    int     prot;
+    int     pid;
+
+    static const int sNumInts = 5;
+    static const int sNumFds = 1;
+    static const int sMagic = '_sgh';
+
+    sw_gralloc_handle_t() :
+        fd(-1), magic(sMagic), size(0), base(0), prot(0), pid(getpid())
+    {
+        version = sizeof(native_handle);
+        numInts = sNumInts;
+        numFds = sNumFds;
+    }
+    ~sw_gralloc_handle_t() {
+        magic = 0;
+    }
+
+    static int validate(const native_handle* h) {
+        const sw_gralloc_handle_t* hnd = (const sw_gralloc_handle_t*)h;
+        if (!h || h->version != sizeof(native_handle) ||
+                h->numInts != sNumInts || h->numFds != sNumFds ||
+                hnd->magic != sMagic) 
+        {
+            return -EINVAL;
+        }
+        return 0;
+    }
+
+    static status_t alloc(uint32_t w, uint32_t h, int format,
+            int usage, buffer_handle_t* handle, int32_t* stride);
+    static status_t free(sw_gralloc_handle_t* hnd);
+    static status_t registerBuffer(sw_gralloc_handle_t* hnd);
+    static status_t unregisterBuffer(sw_gralloc_handle_t* hnd);
+    static status_t lock(sw_gralloc_handle_t* hnd, int usage,
+            int l, int t, int w, int h, void** vaddr);
+    static status_t unlock(sw_gralloc_handle_t* hnd);
+};
+
+/*****************************************************************************/
+
+}; // namespace android
+
+#endif /* ANDROID_UI_PRIVATE_SW_GRALLOC_HANDLE_H */
diff --git a/include/ui/Camera.h b/include/ui/Camera.h
index 9ceb8fd..5219772 100644
--- a/include/ui/Camera.h
+++ b/include/ui/Camera.h
@@ -78,6 +78,12 @@
     CAMERA_MSG_ALL_MSGS         = 0x1FF
 };
 
+// cmdType in sendCommand functions
+enum {
+    CAMERA_CMD_START_SMOOTH_ZOOM     = 1,
+    CAMERA_CMD_STOP_SMOOTH_ZOOM      = 2,
+};
+
 // camera fatal errors
 enum {
     CAMERA_ERROR_UKNOWN  = 1,
@@ -155,6 +161,9 @@
             // get preview/capture parameters - key/value pairs
             String8     getParameters() const;
 
+            // send command to camera driver
+            status_t    sendCommand(int32_t cmd, int32_t arg1, int32_t arg2);
+
             void        setListener(const sp<CameraListener>& listener);
             void        setPreviewCallbackFlags(int preview_callback_flag);
 
diff --git a/include/ui/CameraHardwareInterface.h b/include/ui/CameraHardwareInterface.h
index 5fbb7d8..af40f31 100644
--- a/include/ui/CameraHardwareInterface.h
+++ b/include/ui/CameraHardwareInterface.h
@@ -147,7 +147,7 @@
      * Returns true if recording is enabled.
      */
     virtual bool        recordingEnabled() = 0;
-    
+
     /**
      * Release a record frame previously returned by CAMERA_MSG_VIDEO_FRAME.
      */
@@ -186,11 +186,16 @@
     virtual CameraParameters  getParameters() const = 0;
 
     /**
+     * Send command to camera driver.
+     */
+    virtual status_t sendCommand(int32_t cmd, int32_t arg1, int32_t arg2) = 0;
+
+    /**
      * Release the hardware resources owned by this object.  Note that this is
      * *not* done in the destructor.
      */
     virtual void release() = 0;
-    
+
     /**
      * Dump state of the camera hardware
      */
diff --git a/include/ui/GraphicBuffer.h b/include/ui/GraphicBuffer.h
new file mode 100644
index 0000000..8897f03
--- /dev/null
+++ b/include/ui/GraphicBuffer.h
@@ -0,0 +1,124 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_GRAPHIC_BUFFER_H
+#define ANDROID_GRAPHIC_BUFFER_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <ui/android_native_buffer.h>
+#include <ui/PixelFormat.h>
+#include <ui/Rect.h>
+#include <pixelflinger/pixelflinger.h>
+
+struct android_native_buffer_t;
+
+namespace android {
+
+class GraphicBufferMapper;
+class Parcel;
+
+// ===========================================================================
+// GraphicBuffer
+// ===========================================================================
+
+class GraphicBuffer
+    : public EGLNativeBase<
+        android_native_buffer_t, 
+        GraphicBuffer, 
+        LightRefBase<GraphicBuffer> >
+{
+public:
+
+    enum {
+        USAGE_SW_READ_NEVER     = GRALLOC_USAGE_SW_READ_NEVER,
+        USAGE_SW_READ_RARELY    = GRALLOC_USAGE_SW_READ_RARELY,
+        USAGE_SW_READ_OFTEN     = GRALLOC_USAGE_SW_READ_OFTEN,
+        USAGE_SW_READ_MASK      = GRALLOC_USAGE_SW_READ_MASK,
+        
+        USAGE_SW_WRITE_NEVER    = GRALLOC_USAGE_SW_WRITE_NEVER,
+        USAGE_SW_WRITE_RARELY   = GRALLOC_USAGE_SW_WRITE_RARELY,
+        USAGE_SW_WRITE_OFTEN    = GRALLOC_USAGE_SW_WRITE_OFTEN,
+        USAGE_SW_WRITE_MASK     = GRALLOC_USAGE_SW_WRITE_MASK,
+        
+        USAGE_SOFTWARE_MASK     = USAGE_SW_READ_MASK|USAGE_SW_WRITE_MASK,
+        
+        USAGE_HW_TEXTURE        = GRALLOC_USAGE_HW_TEXTURE,
+        USAGE_HW_RENDER         = GRALLOC_USAGE_HW_RENDER,
+        USAGE_HW_2D             = GRALLOC_USAGE_HW_2D,
+        USAGE_HW_MASK           = GRALLOC_USAGE_HW_MASK
+    };
+
+    GraphicBuffer();
+
+    // creates w * h buffer
+    GraphicBuffer(uint32_t w, uint32_t h, PixelFormat format, uint32_t ssage);
+
+    // return status
+    status_t initCheck() const;
+
+    uint32_t getWidth() const           { return width; }
+    uint32_t getHeight() const          { return height; }
+    uint32_t getStride() const          { return stride; }
+    uint32_t getUsage() const           { return usage; }
+    PixelFormat getPixelFormat() const  { return format; }
+    Rect getBounds() const              { return Rect(width, height); }
+    
+    status_t reallocate(uint32_t w, uint32_t h, PixelFormat f, uint32_t usage);
+
+    status_t lock(uint32_t usage, void** vaddr);
+    status_t lock(uint32_t usage, const Rect& rect, void** vaddr);
+    status_t lock(GGLSurface* surface, uint32_t usage);
+    status_t unlock();
+    
+    android_native_buffer_t* getNativeBuffer() const;
+    
+    void setIndex(int index);
+    int getIndex() const;
+
+protected:
+    GraphicBuffer(const Parcel& reply);
+    virtual ~GraphicBuffer();
+
+    inline const GraphicBufferMapper& getBufferMapper() const { return mBufferMapper; }
+    inline GraphicBufferMapper& getBufferMapper() { return mBufferMapper; }
+    bool mOwner;
+
+private:
+    friend class Surface;
+    friend class BpSurface;
+    friend class BnSurface;
+    friend class LightRefBase<GraphicBuffer>;
+    GraphicBuffer(const GraphicBuffer& rhs);
+    GraphicBuffer& operator = (const GraphicBuffer& rhs);
+    const GraphicBuffer& operator = (const GraphicBuffer& rhs) const;
+
+    status_t initSize(uint32_t w, uint32_t h, PixelFormat format, 
+            uint32_t usage);
+
+    static status_t writeToParcel(Parcel* reply, 
+            android_native_buffer_t const* buffer);
+
+    GraphicBufferMapper& mBufferMapper;
+    ssize_t mInitCheck;
+    uint32_t mVStride;
+    int mIndex;
+};
+
+}; // namespace android
+
+#endif // ANDROID_GRAPHIC_BUFFER_H
diff --git a/libs/surfaceflinger/BufferAllocator.h b/include/ui/GraphicBufferAllocator.h
similarity index 90%
rename from libs/surfaceflinger/BufferAllocator.h
rename to include/ui/GraphicBufferAllocator.h
index a279ded..be9c79b 100644
--- a/libs/surfaceflinger/BufferAllocator.h
+++ b/include/ui/GraphicBufferAllocator.h
@@ -37,7 +37,7 @@
 
 class String8;
 
-class BufferAllocator : public Singleton<BufferAllocator>
+class GraphicBufferAllocator : public Singleton<GraphicBufferAllocator>
 {
 public:
     enum {
@@ -59,7 +59,7 @@
         USAGE_HW_MASK           = GRALLOC_USAGE_HW_MASK
     };
 
-    static inline BufferAllocator& get() { return getInstance(); }
+    static inline GraphicBufferAllocator& get() { return getInstance(); }
     
 
     status_t alloc(uint32_t w, uint32_t h, PixelFormat format, int usage,
@@ -82,9 +82,9 @@
     static Mutex sLock;
     static KeyedVector<buffer_handle_t, alloc_rec_t> sAllocList;
     
-    friend class Singleton<BufferAllocator>;
-    BufferAllocator();
-    ~BufferAllocator();
+    friend class Singleton<GraphicBufferAllocator>;
+    GraphicBufferAllocator();
+    ~GraphicBufferAllocator();
     
     mutable Mutex mLock;
     alloc_device_t  *mAllocDev;
diff --git a/include/ui/BufferMapper.h b/include/ui/GraphicBufferMapper.h
similarity index 87%
rename from include/ui/BufferMapper.h
rename to include/ui/GraphicBufferMapper.h
index 5f084be..697a02a 100644
--- a/include/ui/BufferMapper.h
+++ b/include/ui/GraphicBufferMapper.h
@@ -33,10 +33,10 @@
 
 class Rect;
 
-class BufferMapper : public Singleton<BufferMapper>
+class GraphicBufferMapper : public Singleton<GraphicBufferMapper>
 {
 public:
-    static inline BufferMapper& get() { return getInstance(); }
+    static inline GraphicBufferMapper& get() { return getInstance(); }
 
     status_t registerBuffer(buffer_handle_t handle);
 
@@ -51,8 +51,8 @@
     void dump(buffer_handle_t handle);
 
 private:
-    friend class Singleton<BufferMapper>;
-    BufferMapper();
+    friend class Singleton<GraphicBufferMapper>;
+    GraphicBufferMapper();
     gralloc_module_t const *mAllocMod;
 };
 
diff --git a/include/ui/ICamera.h b/include/ui/ICamera.h
index 7595e36..5642691 100644
--- a/include/ui/ICamera.h
+++ b/include/ui/ICamera.h
@@ -87,6 +87,9 @@
 
     // get preview/capture parameters - key/value pairs
     virtual String8         getParameters() const = 0;
+
+    // send command to camera driver
+    virtual status_t        sendCommand(int32_t cmd, int32_t arg1, int32_t arg2) = 0;
 };
 
 // ----------------------------------------------------------------------------
diff --git a/include/ui/ISurface.h b/include/ui/ISurface.h
index 1283033..2ca0026 100644
--- a/include/ui/ISurface.h
+++ b/include/ui/ISurface.h
@@ -34,7 +34,7 @@
 
 class IMemoryHeap;
 class OverlayRef;
-class SurfaceBuffer;
+class GraphicBuffer;
 
 class ISurface : public IInterface
 {
@@ -50,7 +50,7 @@
 public: 
     DECLARE_META_INTERFACE(Surface);
 
-    virtual sp<SurfaceBuffer> requestBuffer(int bufferIdx, int usage) = 0; 
+    virtual sp<GraphicBuffer> requestBuffer(int bufferIdx, int usage) = 0; 
     
     class BufferHeap {
     public:
diff --git a/include/ui/Surface.h b/include/ui/Surface.h
index 2cedeb6..70303cd 100644
--- a/include/ui/Surface.h
+++ b/include/ui/Surface.h
@@ -34,7 +34,7 @@
 
 // ---------------------------------------------------------------------------
 
-class BufferMapper;
+class GraphicBufferMapper;
 class IOMX;
 class Rect;
 class Surface;
@@ -192,8 +192,8 @@
    
            status_t validate(SharedClient const* cblk) const;
 
-    inline const BufferMapper& getBufferMapper() const { return mBufferMapper; }
-    inline BufferMapper& getBufferMapper() { return mBufferMapper; }
+    inline const GraphicBufferMapper& getBufferMapper() const { return mBufferMapper; }
+    inline GraphicBufferMapper& getBufferMapper() { return mBufferMapper; }
     
     static int setSwapInterval(android_native_window_t* window, int interval);
     static int dequeueBuffer(android_native_window_t* window, android_native_buffer_t** buffer);
@@ -208,7 +208,7 @@
     int query(int what, int* value);
     int perform(int operation, va_list args);
 
-    status_t dequeueBuffer(sp<SurfaceBuffer>* buffer);
+    status_t dequeueBuffer(sp<GraphicBuffer>* buffer);
 
     
     void setUsage(uint32_t reqUsage);
@@ -221,7 +221,7 @@
     uint32_t                    mIdentity;
     PixelFormat                 mFormat;
     uint32_t                    mFlags;
-    BufferMapper&               mBufferMapper;
+    GraphicBufferMapper&        mBufferMapper;
     SharedBufferClient*         mSharedBufferClient;
 
     // protected by mSurfaceLock
@@ -230,12 +230,12 @@
     
     // protected by mSurfaceLock. These are also used from lock/unlock
     // but in that case, they must be called form the same thread.
-    sp<SurfaceBuffer>           mBuffers[2];
+    sp<GraphicBuffer>           mBuffers[2];
     mutable Region              mDirtyRegion;
 
     // must be used from the lock/unlock thread
-    sp<SurfaceBuffer>           mLockedBuffer;
-    sp<SurfaceBuffer>           mPostedBuffer;
+    sp<GraphicBuffer>           mLockedBuffer;
+    sp<GraphicBuffer>           mPostedBuffer;
     mutable Region              mOldDirtyRegion;
     bool                        mNeedFullUpdate;
 
diff --git a/include/ui/android_native_buffer.h b/include/ui/android_native_buffer.h
new file mode 100644
index 0000000..9c92af8
--- /dev/null
+++ b/include/ui/android_native_buffer.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_ANDROID_NATIVES_PRIV_H
+#define ANDROID_ANDROID_NATIVES_PRIV_H
+
+#include <ui/egl/android_natives.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*****************************************************************************/
+
+typedef struct android_native_buffer_t
+{
+#ifdef __cplusplus
+    android_native_buffer_t() { 
+        common.magic = ANDROID_NATIVE_BUFFER_MAGIC;
+        common.version = sizeof(android_native_buffer_t);
+        memset(common.reserved, 0, sizeof(common.reserved));
+    }
+#endif
+
+    struct android_native_base_t common;
+
+    int width;
+    int height;
+    int stride;
+    int format;
+    int usage;
+    
+    void* reserved[2];
+
+    buffer_handle_t handle;
+
+    void* reserved_proc[8];
+} android_native_buffer_t;
+
+
+/*****************************************************************************/
+
+#ifdef __cplusplus
+}
+#endif
+
+/*****************************************************************************/
+
+#endif /* ANDROID_ANDROID_NATIVES_PRIV_H */
diff --git a/libs/audioflinger/AudioFlinger.cpp b/libs/audioflinger/AudioFlinger.cpp
index 8e967fb..ba8b322 100644
--- a/libs/audioflinger/AudioFlinger.cpp
+++ b/libs/audioflinger/AudioFlinger.cpp
@@ -62,8 +62,6 @@
 static const char* kHardwareLockedString = "Hardware lock is taken\n";
 
 //static const nsecs_t kStandbyTimeInNsecs = seconds(3);
-static const unsigned long kBufferRecoveryInUsecs = 2000;
-static const unsigned long kMaxBufferRecoveryInUsecs = 20000;
 static const float MAX_GAIN = 4096.0f;
 
 // retry counts for buffer fill timeout
@@ -1070,10 +1068,10 @@
     // in both cases "unstop" the track
     if (track->isPaused()) {
         track->mState = TrackBase::RESUMING;
-        LOGV("PAUSED => RESUMING (%d)", track->name());
+        LOGV("PAUSED => RESUMING (%d) on thread %p", track->name(), this);
     } else {
         track->mState = TrackBase::ACTIVE;
-        LOGV("? => ACTIVE (%d)", track->name());
+        LOGV("? => ACTIVE (%d) on thread %p", track->name(), this);
     }
     // set retry count for buffer fill
     track->mRetryCount = kMaxTrackStartupRetries;
@@ -1175,7 +1173,8 @@
 
 bool AudioFlinger::MixerThread::threadLoop()
 {
-    unsigned long sleepTime = 0;
+    uint32_t sleepTime = 0;
+    uint32_t maxBufferRecoveryInUsecs = getMaxBufferRecoveryInUsecs();
     int16_t* curBuf = mMixBuffer;
     Vector< sp<Track> > tracksToRemove;
     size_t enabledTracks = 0;
@@ -1200,6 +1199,7 @@
                 // FIXME: Relaxed timing because of a certain device that can't meet latency
                 // Should be reduced to 2x after the vendor fixes the driver issue
                 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
+                maxBufferRecoveryInUsecs = getMaxBufferRecoveryInUsecs();
             }
 
             const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
@@ -1235,7 +1235,6 @@
                     }
 
                     standbyTime = systemTime() + kStandbyTimeInNsecs;
-                    sleepTime = 0;
                     continue;
                 }
             }
@@ -1249,28 +1248,23 @@
             sleepTime = 0;
             standbyTime = systemTime() + kStandbyTimeInNsecs;
         } else {
-            sleepTime += kBufferRecoveryInUsecs;
-            if (sleepTime > kMaxBufferRecoveryInUsecs) {
-                sleepTime = kMaxBufferRecoveryInUsecs;
-            }
-            // There was nothing to mix this round, which means all
-            // active tracks were late. Sleep a little bit to give
-            // them another chance. If we're too late, write 0s to audio
-            // hardware to avoid underrun.
-            if (mBytesWritten != 0 && sleepTime >= kMaxBufferRecoveryInUsecs) {
+            // If no tracks are ready, sleep once for the duration of an output
+            // buffer size, then write 0s to the output
+            if (sleepTime == 0) {
+                sleepTime = maxBufferRecoveryInUsecs;
+            } else if (mBytesWritten != 0) {
                 memset (curBuf, 0, mixBufferSize);
                 sleepTime = 0;
             }
         }
 
         if (mSuspended) {
-            sleepTime = kMaxBufferRecoveryInUsecs;
+            sleepTime = maxBufferRecoveryInUsecs;
         }
         // sleepTime == 0 means we must write to audio hardware
         if (sleepTime == 0) {
             mLastWriteTime = systemTime();
             mInWrite = true;
-            LOGV("mOutput->write() thread %p frames %d", this, mFrameCount);
             int bytesWritten = (int)mOutput->write(curBuf, mixBufferSize);
             if (bytesWritten > 0) mBytesWritten += bytesWritten;
             mNumWrites++;
@@ -1393,7 +1387,7 @@
                 // No buffers for this track. Give it a few chances to
                 // fill a buffer, then remove it from active list.
                 if (--(track->mRetryCount) <= 0) {
-                    LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
+                    LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
                     tracksToRemove->add(track);
                 }
                 // For tracks using static shared memory buffer, make sure that we have
@@ -1583,6 +1577,16 @@
     return NO_ERROR;
 }
 
+uint32_t AudioFlinger::MixerThread::getMaxBufferRecoveryInUsecs()
+{
+    uint32_t time = ((mFrameCount * 1000) / mSampleRate) * 1000;
+    // Add some margin with regard to scheduling precision
+    if (time > 10000) {
+        time -= 10000;
+    }
+    return time;
+}
+
 // ----------------------------------------------------------------------------
 AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
     :   PlaybackThread(audioFlinger, output),
@@ -1598,7 +1602,8 @@
 
 bool AudioFlinger::DirectOutputThread::threadLoop()
 {
-    unsigned long sleepTime = 0;
+    uint32_t sleepTime = 0;
+    uint32_t maxBufferRecoveryInUsecs = getMaxBufferRecoveryInUsecs();
     sp<Track> trackToRemove;
     sp<Track> activeTrack;
     nsecs_t standbyTime = systemTime();
@@ -1615,6 +1620,7 @@
 
             if (checkForNewParameters_l()) {
                 mixBufferSize = mFrameCount*mFrameSize;
+                maxBufferRecoveryInUsecs = getMaxBufferRecoveryInUsecs();
             }
 
             // put audio hardware into standby after short delay
@@ -1648,7 +1654,6 @@
                     }
 
                     standbyTime = systemTime() + kStandbyTimeInNsecs;
-                    sleepTime = 0;
                     continue;
                 }
             }
@@ -1761,23 +1766,16 @@
             sleepTime = 0;
             standbyTime = systemTime() + kStandbyTimeInNsecs;
         } else {
-            sleepTime += kBufferRecoveryInUsecs;
-            if (sleepTime > kMaxBufferRecoveryInUsecs) {
-                sleepTime = kMaxBufferRecoveryInUsecs;
-            }
-            // There was nothing to mix this round, which means all
-            // active tracks were late. Sleep a little bit to give
-            // them another chance. If we're too late, write 0s to audio
-            // hardware to avoid underrun.
-            if (mBytesWritten != 0 && sleepTime >= kMaxBufferRecoveryInUsecs &&
-                AudioSystem::isLinearPCM(mFormat)) {
+            if (sleepTime == 0) {
+                sleepTime = maxBufferRecoveryInUsecs;
+            } else if (mBytesWritten != 0 && AudioSystem::isLinearPCM(mFormat)) {
                 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
                 sleepTime = 0;
             }
         }
 
         if (mSuspended) {
-            sleepTime = kMaxBufferRecoveryInUsecs;
+            sleepTime = maxBufferRecoveryInUsecs;
         }
         // sleepTime == 0 means we must write to audio hardware
         if (sleepTime == 0) {
@@ -1861,6 +1859,21 @@
     return reconfig;
 }
 
+uint32_t AudioFlinger::DirectOutputThread::getMaxBufferRecoveryInUsecs()
+{
+    uint32_t time;
+    if (AudioSystem::isLinearPCM(mFormat)) {
+        time = ((mFrameCount * 1000) / mSampleRate) * 1000;
+        // Add some margin with regard to scheduling precision
+        if (time > 10000) {
+            time -= 10000;
+        }
+    } else {
+        time = 10000;
+    }
+    return time;
+}
+
 // ----------------------------------------------------------------------------
 
 AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread)
@@ -1877,13 +1890,15 @@
 
 bool AudioFlinger::DuplicatingThread::threadLoop()
 {
-    unsigned long sleepTime = kBufferRecoveryInUsecs;
+    uint32_t sleepTime = 0;
+    uint32_t maxBufferRecoveryInUsecs = getMaxBufferRecoveryInUsecs();
     int16_t* curBuf = mMixBuffer;
     Vector< sp<Track> > tracksToRemove;
     size_t enabledTracks = 0;
     nsecs_t standbyTime = systemTime();
     size_t mixBufferSize = mFrameCount*mFrameSize;
     SortedVector< sp<OutputTrack> > outputTracks;
+    uint32_t writeFrames = 0;
 
     while (!exitPending())
     {
@@ -1896,6 +1911,7 @@
 
             if (checkForNewParameters_l()) {
                 mixBufferSize = mFrameCount*mFrameSize;
+                maxBufferRecoveryInUsecs = getMaxBufferRecoveryInUsecs();
             }
 
             const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
@@ -1935,7 +1951,6 @@
                     }
 
                     standbyTime = systemTime() + kStandbyTimeInNsecs;
-                    sleepTime = kBufferRecoveryInUsecs;
                     continue;
                 }
             }
@@ -1947,29 +1962,30 @@
             // mix buffers...
             mAudioMixer->process(curBuf);
             sleepTime = 0;
-            standbyTime = systemTime() + kStandbyTimeInNsecs;
+            writeFrames = mFrameCount;
         } else {
-            sleepTime += kBufferRecoveryInUsecs;
-            if (sleepTime > kMaxBufferRecoveryInUsecs) {
-                sleepTime = kMaxBufferRecoveryInUsecs;
-            }
-            // There was nothing to mix this round, which means all
-            // active tracks were late. Sleep a little bit to give
-            // them another chance. If we're too late, write 0s to audio
-            // hardware to avoid underrun.
-            if (mBytesWritten != 0 && sleepTime >= kMaxBufferRecoveryInUsecs) {
-                memset (curBuf, 0, mixBufferSize);
-                sleepTime = 0;
+            if (sleepTime == 0) {
+                sleepTime = maxBufferRecoveryInUsecs;
+            } else if (mBytesWritten != 0) {
+                // flush remaining overflow buffers in output tracks
+                for (size_t i = 0; i < outputTracks.size(); i++) {
+                    if (outputTracks[i]->isActive()) {
+                        sleepTime = 0;
+                        writeFrames = 0;
+                        break;
+                    }
+                }
             }
         }
 
         if (mSuspended) {
-            sleepTime = kMaxBufferRecoveryInUsecs;
+            sleepTime = maxBufferRecoveryInUsecs;
         }
         // sleepTime == 0 means we must write to audio hardware
         if (sleepTime == 0) {
+            standbyTime = systemTime() + kStandbyTimeInNsecs;
             for (size_t i = 0; i < outputTracks.size(); i++) {
-                outputTracks[i]->write(curBuf, mFrameCount);
+                outputTracks[i]->write(curBuf, writeFrames);
             }
             mStandby = false;
             mBytesWritten += mixBufferSize;
@@ -2026,7 +2042,6 @@
     LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
 }
 
-
 // ----------------------------------------------------------------------------
 
 // TrackBase constructor must be called with AudioFlinger::mLock held
@@ -2300,7 +2315,7 @@
 getNextBuffer_exit:
      buffer->raw = 0;
      buffer->frameCount = 0;
-     LOGV("getNextBuffer() no more data");
+     LOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
      return NOT_ENOUGH_DATA;
 }
 
@@ -2341,7 +2356,7 @@
             if (playbackThread->mActiveTracks.indexOf(this) < 0) {
                 reset();
             }
-            LOGV("(> STOPPED) => STOPPED (%d)", mName);
+            LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
         }
     }
 }
@@ -2354,7 +2369,7 @@
         Mutex::Autolock _l(thread->mLock);
         if (mState == ACTIVE || mState == RESUMING) {
             mState = PAUSING;
-            LOGV("ACTIVE/RESUMING => PAUSING (%d)", mName);
+            LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
         }
     }
 }
@@ -2566,7 +2581,7 @@
 
     uint32_t waitTimeLeftMs = mWaitTimeMs;
 
-    if (!mActive) {
+    if (!mActive && frames != 0) {
         start();
         sp<ThreadBase> thread = mThread.promote();
         if (thread != 0) {
@@ -2608,7 +2623,7 @@
                 break;
             }
             uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
-//            LOGV("OutputTrack::write() waitTimeMs %d waitTimeLeftMs %d", waitTimeMs, waitTimeLeftMs)
+            LOGV("OutputTrack::write() to thread %p waitTimeMs %d waitTimeLeftMs %d", mThread.unsafe_get(), waitTimeMs, waitTimeLeftMs);
             if (waitTimeLeftMs >= waitTimeMs) {
                 waitTimeLeftMs -= waitTimeMs;
             } else {
@@ -2663,7 +2678,7 @@
             pInBuffer->i16 = pInBuffer->mBuffer;
             memset(pInBuffer->raw, 0, frames * channels * sizeof(int16_t));
             mBufferQueue.add(pInBuffer);
-        } else {
+        } else if (mActive) {
             stop();
         }
     }
diff --git a/libs/audioflinger/AudioFlinger.h b/libs/audioflinger/AudioFlinger.h
index 3699019..4bf73ce 100644
--- a/libs/audioflinger/AudioFlinger.h
+++ b/libs/audioflinger/AudioFlinger.h
@@ -524,6 +524,10 @@
         bool                            mMasterMute;
         SortedVector< wp<Track> >       mActiveTracks;
 
+        virtual int             getTrackName_l() = 0;
+        virtual void            deleteTrackName_l(int name) = 0;
+        virtual uint32_t        getMaxBufferRecoveryInUsecs() = 0;
+
     private:
 
         friend class AudioFlinger;
@@ -539,8 +543,7 @@
 
         status_t    addTrack_l(const sp<Track>& track);
         void        destroyTrack_l(const sp<Track>& track);
-        virtual int         getTrackName_l() = 0;
-        virtual void        deleteTrackName_l(int name) = 0;
+
         void        readOutputParameters();
 
         virtual status_t    dumpInternals(int fd, const Vector<String16>& args);
@@ -571,13 +574,14 @@
                                       int streamType);
                     void        putTracks(SortedVector < sp<Track> >& tracks,
                                       SortedVector < wp<Track> >& activeTracks);
-        virtual     int         getTrackName_l();
-        virtual     void        deleteTrackName_l(int name);
         virtual     bool        checkForNewParameters_l();
         virtual     status_t    dumpInternals(int fd, const Vector<String16>& args);
 
     protected:
         size_t prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove);
+        virtual     int         getTrackName_l();
+        virtual     void        deleteTrackName_l(int name);
+        virtual     uint32_t    getMaxBufferRecoveryInUsecs();
 
         AudioMixer*                     mAudioMixer;
     };
@@ -591,9 +595,12 @@
         // Thread virtuals
         virtual     bool        threadLoop();
 
+        virtual     bool        checkForNewParameters_l();
+
+    protected:
         virtual     int         getTrackName_l();
         virtual     void        deleteTrackName_l(int name);
-        virtual     bool        checkForNewParameters_l();
+        virtual     uint32_t    getMaxBufferRecoveryInUsecs();
 
     private:
         float mLeftVolume;
diff --git a/libs/rs/RenderScript.h b/libs/rs/RenderScript.h
index 87a2f4a..9b04393 100644
--- a/libs/rs/RenderScript.h
+++ b/libs/rs/RenderScript.h
@@ -59,6 +59,10 @@
 void rsContextDestroy(RsContext);
 void rsObjDestroyOOB(RsContext, void *);
 
+uint32_t rsContextGetMessage(RsContext, void *data, size_t *receiveLen, size_t bufferLen, bool wait);
+void rsContextInitToClient(RsContext);
+void rsContextDeinitToClient(RsContext);
+
 #define RS_MAX_TEXTURE 2
 
 enum RsDataType {
diff --git a/libs/rs/rsContext.cpp b/libs/rs/rsContext.cpp
index 169d5d4..195ea6f 100644
--- a/libs/rs/rsContext.cpp
+++ b/libs/rs/rsContext.cpp
@@ -142,6 +142,7 @@
     if (this->props.mLogTimes) {
         timerSet(RS_TIMER_SCRIPT);
     }
+    mStateFragmentStore.mLast.clear();
     bool ret = runScript(mRootScript.get(), 0);
     return ret;
 }
@@ -303,10 +304,15 @@
     int status;
     pthread_attr_t threadAttr;
 
-    status = pthread_key_create(&gThreadTLSKey, NULL);
-    if (status) {
-        LOGE("Failed to init thread tls key.");
-        return;
+    if (!gThreadTLSKey) {
+        status = pthread_key_create(&gThreadTLSKey, NULL);
+        if (status) {
+            LOGE("Failed to init thread tls key.");
+            return;
+        }
+    } else {
+        // HACK: workaround gl hang on start
+        exit(-1);
     }
 
     status = pthread_attr_init(&threadAttr);
@@ -529,6 +535,64 @@
     }
 }
 
+uint32_t Context::getMessageToClient(void *data, size_t *receiveLen, size_t bufferLen, bool wait)
+{
+    //LOGE("getMessageToClient %i %i", bufferLen, wait);
+    if (!wait) {
+        if (mIO.mToClient.isEmpty()) {
+            // No message to get and not going to wait for one.
+            receiveLen = 0;
+            return 0;
+        }
+    }
+
+    //LOGE("getMessageToClient 2 con=%p", this);
+    uint32_t bytesData = 0;
+    uint32_t commandID = 0;
+    const void *d = mIO.mToClient.get(&commandID, &bytesData);
+    //LOGE("getMessageToClient 3    %i  %i", commandID, bytesData);
+
+    *receiveLen = bytesData;
+    if (bufferLen >= bytesData) {
+        memcpy(data, d, bytesData);
+        mIO.mToClient.next();
+        return commandID;
+    }
+    return 0;
+}
+
+bool Context::sendMessageToClient(void *data, uint32_t cmdID, size_t len, bool waitForSpace)
+{
+    //LOGE("sendMessageToClient %i %i %i", cmdID, len, waitForSpace);
+    if (cmdID == 0) {
+        LOGE("Attempting to send invalid command 0 to client.");
+        return false;
+    }
+    if (!waitForSpace) {
+        if (mIO.mToClient.getFreeSpace() < len) {
+            // Not enough room, and not waiting.
+            return false;
+        }
+    }
+    //LOGE("sendMessageToClient 2");
+    void *p = mIO.mToClient.reserve(len);
+    memcpy(p, data, len);
+    mIO.mToClient.commit(cmdID, len);
+    //LOGE("sendMessageToClient 3");
+    return true;
+}
+
+void Context::initToClient()
+{
+    while(!mRunning) {
+        usleep(100);
+    }
+}
+
+void Context::deinitToClient()
+{
+    mIO.mToClient.shutdown();
+}
 
 
 ///////////////////////////////////////////////////////////////////////////////////////////
@@ -636,3 +700,21 @@
     rsc->objDestroyAdd(static_cast<ObjectBase *>(obj));
 }
 
+uint32_t rsContextGetMessage(RsContext vrsc, void *data, size_t *receiveLen, size_t bufferLen, bool wait)
+{
+    Context * rsc = static_cast<Context *>(vrsc);
+    return rsc->getMessageToClient(data, receiveLen, bufferLen, wait);
+}
+
+void rsContextInitToClient(RsContext vrsc)
+{
+    Context * rsc = static_cast<Context *>(vrsc);
+    rsc->initToClient();
+}
+
+void rsContextDeinitToClient(RsContext vrsc)
+{
+    Context * rsc = static_cast<Context *>(vrsc);
+    rsc->deinitToClient();
+}
+
diff --git a/libs/rs/rsContext.h b/libs/rs/rsContext.h
index cef421d..b56e7d7 100644
--- a/libs/rs/rsContext.h
+++ b/libs/rs/rsContext.h
@@ -97,6 +97,12 @@
     void appendNameDefines(String8 *str) const;
     void appendVarDefines(String8 *str) const;
 
+    uint32_t getMessageToClient(void *data, size_t *receiveLen, size_t bufferLen, bool wait);
+    bool sendMessageToClient(void *data, uint32_t cmdID, size_t len, bool waitForSpace);
+
+    void initToClient();
+    void deinitToClient();
+
     ProgramFragment * getDefaultProgramFragment() const {
         return mStateFragment.mDefault.get();
     }
diff --git a/libs/rs/rsLocklessFifo.cpp b/libs/rs/rsLocklessFifo.cpp
index b0540a6..085a81e 100644
--- a/libs/rs/rsLocklessFifo.cpp
+++ b/libs/rs/rsLocklessFifo.cpp
@@ -99,6 +99,9 @@
 
 void LocklessCommandFifo::commit(uint32_t command, uint32_t sizeInBytes)
 {
+    if (mInShutdown) {
+        return;
+    }
     //dumpState("commit 1");
     reinterpret_cast<uint16_t *>(mPut)[0] = command;
     reinterpret_cast<uint16_t *>(mPut)[1] = sizeInBytes;
@@ -109,6 +112,9 @@
 
 void LocklessCommandFifo::commitSync(uint32_t command, uint32_t sizeInBytes)
 {
+    if (mInShutdown) {
+        return;
+    }
     commit(command, sizeInBytes);
     flush();
 }
diff --git a/libs/rs/rsScriptC.cpp b/libs/rs/rsScriptC.cpp
index 20088da..9da7766 100644
--- a/libs/rs/rsScriptC.cpp
+++ b/libs/rs/rsScriptC.cpp
@@ -62,6 +62,7 @@
 {
     Context::ScriptTLSStruct * tls =
     (Context::ScriptTLSStruct *)pthread_getspecific(Context::gThreadTLSKey);
+    rsAssert(tls);
 
     if (mEnviroment.mFragmentStore.get()) {
         rsc->setFragmentStore(mEnviroment.mFragmentStore.get());
diff --git a/libs/rs/rsScriptC_Lib.cpp b/libs/rs/rsScriptC_Lib.cpp
index 17d14f5..9a96290 100644
--- a/libs/rs/rsScriptC_Lib.cpp
+++ b/libs/rs/rsScriptC_Lib.cpp
@@ -1002,6 +1002,12 @@
     return rs888to565(ir, ig, ib);
 }
 
+static uint32_t SC_toClient(void *data, int cmdID, int len, int waitForSpace)
+{
+    GET_TLS();
+    return rsc->sendMessageToClient(data, cmdID, len, waitForSpace != 0);
+}
+
 //////////////////////////////////////////////////////////////////////////////
 // Class implementation
 //////////////////////////////////////////////////////////////////////////////
@@ -1270,6 +1276,8 @@
     { "getHeight", (void *)&SC_getHeight,
         "int", "()" },
 
+    { "sendToClient", (void *)&SC_toClient,
+        "int", "(void *data, int cmdID, int len, int waitForSpace)" },
 
 
     { "debugF", (void *)&SC_debugF,
diff --git a/libs/rs/rsThreadIO.cpp b/libs/rs/rsThreadIO.cpp
index 4d3d73a..527b3d7 100644
--- a/libs/rs/rsThreadIO.cpp
+++ b/libs/rs/rsThreadIO.cpp
@@ -24,6 +24,7 @@
 ThreadIO::ThreadIO()
 {
     mToCore.init(16 * 1024);
+    mToClient.init(1024);
 }
 
 ThreadIO::~ThreadIO()
diff --git a/libs/rs/rsThreadIO.h b/libs/rs/rsThreadIO.h
index 1f6a0c2..95270f5 100644
--- a/libs/rs/rsThreadIO.h
+++ b/libs/rs/rsThreadIO.h
@@ -39,7 +39,7 @@
 
 
     LocklessCommandFifo mToCore;
-    //LocklessCommandFifo mToClient;
+    LocklessCommandFifo mToClient;
 
     intptr_t mToCoreRet;
 
diff --git a/libs/surfaceflinger/Android.mk b/libs/surfaceflinger/Android.mk
index 49da111..eb51c22 100644
--- a/libs/surfaceflinger/Android.mk
+++ b/libs/surfaceflinger/Android.mk
@@ -6,8 +6,6 @@
     DisplayHardware/DisplayHardware.cpp \
     DisplayHardware/DisplayHardwareBase.cpp \
     BlurFilter.cpp.arm \
-    Buffer.cpp \
-    BufferAllocator.cpp \
     Layer.cpp \
     LayerBase.cpp \
     LayerBuffer.cpp \
diff --git a/libs/surfaceflinger/Buffer.cpp b/libs/surfaceflinger/Buffer.cpp
deleted file mode 100644
index 6190cd8..0000000
--- a/libs/surfaceflinger/Buffer.cpp
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdlib.h>
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <utils/Errors.h>
-#include <utils/Log.h>
-
-#include <ui/PixelFormat.h>
-#include <pixelflinger/pixelflinger.h>
-
-#include "Buffer.h"
-#include "BufferAllocator.h"
-
-namespace android {
-
-// ===========================================================================
-// Buffer and implementation of android_native_buffer_t
-// ===========================================================================
-
-Buffer::Buffer()
-    : SurfaceBuffer(), mInitCheck(NO_ERROR),  mVStride(0)
-{
-}
-
-Buffer::Buffer(uint32_t w, uint32_t h, PixelFormat format,
-        uint32_t reqUsage, uint32_t flags)
-    : SurfaceBuffer(), mInitCheck(NO_INIT), mVStride(0)
-{
-    mInitCheck = initSize(w, h, format, reqUsage, flags);
-}
-
-Buffer::~Buffer()
-{
-    if (handle) {
-        BufferAllocator& allocator(BufferAllocator::get());
-        allocator.free(handle);
-    }
-}
-
-status_t Buffer::initCheck() const {
-    return mInitCheck;
-}
-
-android_native_buffer_t* Buffer::getNativeBuffer() const
-{
-    return static_cast<android_native_buffer_t*>(const_cast<Buffer*>(this));
-}
-
-status_t Buffer::reallocate(uint32_t w, uint32_t h, PixelFormat f,
-        uint32_t reqUsage, uint32_t flags)
-{
-    if (handle) {
-        BufferAllocator& allocator(BufferAllocator::get());
-        allocator.free(handle);
-        handle = 0;
-    }
-    return initSize(w, h, f, reqUsage, flags);
-}
-
-status_t Buffer::initSize(uint32_t w, uint32_t h, PixelFormat format,
-        uint32_t reqUsage, uint32_t flags)
-{
-    status_t err = NO_ERROR;
-
-    BufferAllocator& allocator = BufferAllocator::get();
-        
-    /*
-     *  buffers used for software rendering, but h/w composition
-     *  are allocated with SW_READ_OFTEN | SW_WRITE_OFTEN | HW_TEXTURE
-     *  
-     *  buffers used for h/w rendering and h/w composition
-     *  are allocated with  HW_RENDER | HW_TEXTURE
-     *  
-     *  buffers used with h/w rendering and either NPOT or no egl_image_ext
-     *  are allocated with SW_READ_RARELY | HW_RENDER 
-     *  
-     */
-    
-    if (flags & Buffer::SECURE) {
-        // secure buffer, don't store it into the GPU
-        usage = BufferAllocator::USAGE_SW_READ_OFTEN | 
-                BufferAllocator::USAGE_SW_WRITE_OFTEN;
-    } else {
-        // it's allowed to modify the usage flags here, but generally
-        // the requested flags should be honored.
-        usage = reqUsage | BufferAllocator::USAGE_HW_TEXTURE;
-    }
-    
-    if (format == PIXEL_FORMAT_RGBX_8888)
-        format = PIXEL_FORMAT_RGBA_8888;
-
-    err = allocator.alloc(w, h, format, usage, &handle, &stride);
-    if (err == NO_ERROR) {
-        this->width  = w;
-        this->height = h;
-        this->format = format;
-        mVStride = 0;
-    }
-
-    return err;
-}
-
-status_t Buffer::lock(GGLSurface* sur, uint32_t usage) 
-{
-    void* vaddr;
-    status_t res = SurfaceBuffer::lock(usage, &vaddr);
-    if (res == NO_ERROR && sur) {
-        sur->version = sizeof(GGLSurface);
-        sur->width = width;
-        sur->height = height;
-        sur->stride = stride;
-        sur->format = format;
-        sur->vstride = mVStride;
-        sur->data = static_cast<GGLubyte*>(vaddr);
-    }
-    return res;
-}
-
-// ---------------------------------------------------------------------------
-
-}; // namespace android
diff --git a/libs/surfaceflinger/Buffer.h b/libs/surfaceflinger/Buffer.h
deleted file mode 100644
index 203da3b..0000000
--- a/libs/surfaceflinger/Buffer.h
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_LAYER_BITMAP_H
-#define ANDROID_LAYER_BITMAP_H
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <ui/PixelFormat.h>
-#include <ui/Rect.h>
-#include <pixelflinger/pixelflinger.h>
-#include <private/ui/SurfaceBuffer.h>
-
-struct android_native_buffer_t;
-
-namespace android {
-
-// ===========================================================================
-// Buffer
-// ===========================================================================
-
-class Buffer : public SurfaceBuffer
-{
-public:
-    enum {
-        DONT_CLEAR  = 0x00000001,
-        SECURE      = 0x00000004
-    };
-
-    Buffer();
-
-    // creates w * h buffer
-    Buffer(uint32_t w, uint32_t h, PixelFormat format,
-            uint32_t reqUsage, uint32_t flags = 0);
-
-    // return status
-    status_t initCheck() const;
-
-    uint32_t getWidth() const           { return width; }
-    uint32_t getHeight() const          { return height; }
-    uint32_t getStride() const          { return stride; }
-    uint32_t getUsage() const           { return usage; }
-    PixelFormat getPixelFormat() const  { return format; }
-    Rect getBounds() const              { return Rect(width, height); }
-    
-    status_t lock(GGLSurface* surface, uint32_t usage);
-    
-    android_native_buffer_t* getNativeBuffer() const;
-    
-    status_t reallocate(uint32_t w, uint32_t h, PixelFormat f,
-            uint32_t reqUsage, uint32_t flags);
-
-private:
-    friend class LightRefBase<Buffer>;
-    Buffer(const Buffer& rhs);
-    virtual ~Buffer();
-    Buffer& operator = (const Buffer& rhs);
-    const Buffer& operator = (const Buffer& rhs) const;
-
-    status_t initSize(uint32_t w, uint32_t h, PixelFormat format,
-            uint32_t reqUsage, uint32_t flags);
-
-    ssize_t     mInitCheck;
-    uint32_t    mVStride;
-};
-
-}; // namespace android
-
-#endif // ANDROID_LAYER_BITMAP_H
diff --git a/libs/surfaceflinger/DisplayHardware/DisplayHardware.cpp b/libs/surfaceflinger/DisplayHardware/DisplayHardware.cpp
index 8a7abec..f84933e 100644
--- a/libs/surfaceflinger/DisplayHardware/DisplayHardware.cpp
+++ b/libs/surfaceflinger/DisplayHardware/DisplayHardware.cpp
@@ -123,7 +123,7 @@
     EGLint numConfigs=0;
     EGLSurface surface;
     EGLContext context;
-    mFlags = 0;
+    mFlags = CACHED_BUFFERS;
 
     // TODO: all the extensions below should be queried through
     // eglGetProcAddress().
@@ -239,12 +239,17 @@
 
     eglMakeCurrent(display, surface, surface, context);
     const char* const  gl_extensions = (const char*)glGetString(GL_EXTENSIONS);
+    const char* const  gl_renderer = (const char*)glGetString(GL_RENDERER);
     LOGI("OpenGL informations:");
     LOGI("vendor    : %s", glGetString(GL_VENDOR));
-    LOGI("renderer  : %s", glGetString(GL_RENDERER));
+    LOGI("renderer  : %s", gl_renderer);
     LOGI("version   : %s", glGetString(GL_VERSION));
     LOGI("extensions: %s", gl_extensions);
 
+    if (strstr(gl_renderer, "PowerVR SGX 530")) {
+        LOGD("Assuming uncached graphics buffers.");
+        mFlags &= ~CACHED_BUFFERS;
+    }
     if (strstr(gl_extensions, "GL_ARB_texture_non_power_of_two")) {
         mFlags |= NPOT_EXTENSION;
     }
diff --git a/libs/surfaceflinger/DisplayHardware/DisplayHardware.h b/libs/surfaceflinger/DisplayHardware/DisplayHardware.h
index cb688b7..6914d0c 100644
--- a/libs/surfaceflinger/DisplayHardware/DisplayHardware.h
+++ b/libs/surfaceflinger/DisplayHardware/DisplayHardware.h
@@ -51,6 +51,7 @@
         PARTIAL_UPDATES         = 0x00020000,   // video driver feature
         SLOW_CONFIG             = 0x00040000,   // software
         SWAP_RECTANGLE          = 0x00080000,
+        CACHED_BUFFERS          = 0x00100000
     };
 
     DisplayHardware(
diff --git a/libs/surfaceflinger/Layer.cpp b/libs/surfaceflinger/Layer.cpp
index 13201db..0258cee 100644
--- a/libs/surfaceflinger/Layer.cpp
+++ b/libs/surfaceflinger/Layer.cpp
@@ -25,10 +25,10 @@
 #include <utils/Log.h>
 #include <utils/StopWatch.h>
 
+#include <ui/GraphicBuffer.h>
 #include <ui/PixelFormat.h>
 #include <ui/Surface.h>
 
-#include "Buffer.h"
 #include "clz.h"
 #include "Layer.h"
 #include "SurfaceFlinger.h"
@@ -51,6 +51,7 @@
         const sp<Client>& c, int32_t i)
     :   LayerBaseClient(flinger, display, c, i),
         mSecure(false),
+        mNoEGLImageForSwBuffers(false),
         mNeedsBlending(true),
         mNeedsDithering(false)
 {
@@ -108,25 +109,22 @@
     const DisplayHardware& hw(graphicPlane(0).displayHardware());
     PixelFormatInfo displayInfo;
     getPixelFormatInfo(hw.getFormat(), &displayInfo);
-
-    uint32_t bufferFlags = 0;
-    if (flags & ISurfaceComposer::eSecure)
-        bufferFlags |= Buffer::SECURE;
-
+    const uint32_t hwFlags = hw.getFlags();
+    
     mFormat = format;
     mWidth = w;
     mHeight = h;
-    mSecure = (bufferFlags & Buffer::SECURE) ? true : false;
+    mSecure = (flags & ISurfaceComposer::eSecure) ? true : false;
     mNeedsBlending = (info.h_alpha - info.l_alpha) > 0;
-
+    mNoEGLImageForSwBuffers = !(hwFlags & DisplayHardware::CACHED_BUFFERS);
+    
     // we use the red index
     int displayRedSize = displayInfo.getSize(PixelFormatInfo::INDEX_RED);
     int layerRedsize = info.getSize(PixelFormatInfo::INDEX_RED);
     mNeedsDithering = layerRedsize > displayRedSize;
 
-    mBufferFlags = bufferFlags;
     for (size_t i=0 ; i<NUM_BUFFERS ; i++) {
-        mBuffers[i] = new Buffer();
+        mBuffers[i] = new GraphicBuffer();
     }
     mSurface = new SurfaceLayer(mFlinger, clientIndex(), this);
     return NO_ERROR;
@@ -135,8 +133,9 @@
 void Layer::reloadTexture(const Region& dirty)
 {
     Mutex::Autolock _l(mLock);
-    sp<Buffer> buffer(getFrontBuffer());
-    if (LIKELY(mFlags & DisplayHardware::DIRECT_TEXTURE)) {
+    sp<GraphicBuffer> buffer(getFrontBufferLocked());
+    if (LIKELY((mFlags & DisplayHardware::DIRECT_TEXTURE) &&
+            (buffer->usage & GRALLOC_USAGE_HW_TEXTURE))) {
         int index = mFrontBufferIndex;
         if (LIKELY(!mTextures[index].dirty)) {
             glBindTexture(GL_TEXTURE_2D, mTextures[index].name);
@@ -187,6 +186,7 @@
                     mFlags &= ~DisplayHardware::DIRECT_TEXTURE;
                 } else {
                     // Everything went okay!
+                    mTextures[index].NPOTAdjust = false;
                     mTextures[index].dirty  = false;
                     mTextures[index].width  = clientBuf->width;
                     mTextures[index].height = clientBuf->height;
@@ -194,15 +194,21 @@
             }                
         }
     } else {
+        for (size_t i=0 ; i<NUM_BUFFERS ; i++)
+            mTextures[i].image = EGL_NO_IMAGE_KHR;
+
         GGLSurface t;
-        status_t res = buffer->lock(&t, GRALLOC_USAGE_SW_READ_RARELY);
+        status_t res = buffer->lock(&t, GRALLOC_USAGE_SW_READ_OFTEN);
         LOGE_IF(res, "error %d (%s) locking buffer %p",
                 res, strerror(res), buffer.get());
+        
         if (res == NO_ERROR) {
             if (UNLIKELY(mTextures[0].name == -1U)) {
                 mTextures[0].name = createTexture();
+                mTextures[0].width = 0;
+                mTextures[0].height = 0;
             }
-            loadTexture(&mTextures[0], mTextures[0].name, dirty, t);
+            loadTexture(&mTextures[0], dirty, t);
             buffer->unlock();
         }
     }
@@ -211,8 +217,9 @@
 
 void Layer::onDraw(const Region& clip) const
 {
-    const int index = (mFlags & DisplayHardware::DIRECT_TEXTURE) ? 
-            mFrontBufferIndex : 0;
+    int index = mFrontBufferIndex;
+    if (mTextures[index].image == EGL_NO_IMAGE_KHR)
+        index = 0;
     GLuint textureName = mTextures[index].name;
     if (UNLIKELY(textureName == -1LU)) {
         // the texture has not been created yet, this Layer has
@@ -224,9 +231,9 @@
     drawWithOpenGL(clip, mTextures[index]);
 }
 
-sp<SurfaceBuffer> Layer::requestBuffer(int index, int usage)
+sp<GraphicBuffer> Layer::requestBuffer(int index, int usage)
 {
-    sp<Buffer> buffer;
+    sp<GraphicBuffer> buffer;
 
     // this ensures our client doesn't go away while we're accessing
     // the shared area.
@@ -269,14 +276,15 @@
         mBuffers[index].clear();
     }
 
+    const uint32_t effectiveUsage = getEffectiveUsage(usage);
     if (buffer!=0 && buffer->getStrongCount() == 1) {
-        err = buffer->reallocate(w, h, mFormat, usage, mBufferFlags);
+        err = buffer->reallocate(w, h, mFormat, effectiveUsage);
     } else {
         // here we have to reallocate a new buffer because we could have a
         // client in our process with a reference to it (eg: status bar),
         // and we can't release the handle under its feet.
         buffer.clear();
-        buffer = new Buffer(w, h, mFormat, usage, mBufferFlags);
+        buffer = new GraphicBuffer(w, h, mFormat, effectiveUsage);
         err = buffer->initCheck();
     }
 
@@ -305,6 +313,40 @@
     return buffer;
 }
 
+uint32_t Layer::getEffectiveUsage(uint32_t usage) const
+{
+    /*
+     *  buffers used for software rendering, but h/w composition
+     *  are allocated with SW_READ_OFTEN | SW_WRITE_OFTEN | HW_TEXTURE
+     *
+     *  buffers used for h/w rendering and h/w composition
+     *  are allocated with  HW_RENDER | HW_TEXTURE
+     *
+     *  buffers used with h/w rendering and either NPOT or no egl_image_ext
+     *  are allocated with SW_READ_RARELY | HW_RENDER
+     *
+     */
+
+    if (mSecure) {
+        // secure buffer, don't store it into the GPU
+        usage = GraphicBuffer::USAGE_SW_READ_OFTEN |
+                GraphicBuffer::USAGE_SW_WRITE_OFTEN;
+    } else {
+        // it's allowed to modify the usage flags here, but generally
+        // the requested flags should be honored.
+        if (mNoEGLImageForSwBuffers) {
+            if (usage & GraphicBuffer::USAGE_HW_MASK) {
+                // request EGLImage for h/w buffers only
+                usage |= GraphicBuffer::USAGE_HW_TEXTURE;
+            }
+        } else {
+            // request EGLImage for all buffers
+            usage |= GraphicBuffer::USAGE_HW_TEXTURE;
+        }
+    }
+    return usage;
+}
+
 uint32_t Layer::doTransaction(uint32_t flags)
 {
     const Layer::State& front(drawingState());
@@ -383,7 +425,7 @@
     mFrontBufferIndex = buf;
 
     // get the dirty region
-    sp<Buffer> newFrontBuffer(getBuffer(buf));
+    sp<GraphicBuffer> newFrontBuffer(getBuffer(buf));
     const Region dirty(lcblk->getDirtyRegion(buf));
     mPostedDirtyRegion = dirty.intersect( newFrontBuffer->getBounds() );
 
@@ -421,7 +463,9 @@
     // FIXME: signal an event if we have more buffers waiting
     // mFlinger->signalEvent();
 
-    reloadTexture( mPostedDirtyRegion );
+    if (!mPostedDirtyRegion.isEmpty()) {
+        reloadTexture( mPostedDirtyRegion );
+    }
 }
 
 void Layer::unlockPageFlip(
@@ -465,9 +509,9 @@
 {
 }
 
-sp<SurfaceBuffer> Layer::SurfaceLayer::requestBuffer(int index, int usage)
+sp<GraphicBuffer> Layer::SurfaceLayer::requestBuffer(int index, int usage)
 {
-    sp<SurfaceBuffer> buffer;
+    sp<GraphicBuffer> buffer;
     sp<Layer> owner(getOwner());
     if (owner != 0) {
         LOGE_IF(uint32_t(index)>=NUM_BUFFERS,
diff --git a/libs/surfaceflinger/Layer.h b/libs/surfaceflinger/Layer.h
index f111840..702c51a 100644
--- a/libs/surfaceflinger/Layer.h
+++ b/libs/surfaceflinger/Layer.h
@@ -20,6 +20,7 @@
 #include <stdint.h>
 #include <sys/types.h>
 
+#include <ui/GraphicBuffer.h>
 #include <ui/PixelFormat.h>
 #include <pixelflinger/pixelflinger.h>
 
@@ -28,7 +29,6 @@
 #include <GLES/gl.h>
 #include <GLES/glext.h>
 
-#include "Buffer.h"
 #include "LayerBase.h"
 #include "Transform.h"
 
@@ -38,7 +38,6 @@
 
 class Client;
 class FreezeLock;
-class Buffer;
 
 // ---------------------------------------------------------------------------
 
@@ -74,20 +73,22 @@
     virtual status_t ditch();
     
     // only for debugging
-    inline sp<Buffer> getBuffer(int i) { return mBuffers[i]; }
+    inline sp<GraphicBuffer> getBuffer(int i) { return mBuffers[i]; }
     // only for debugging
     inline const sp<FreezeLock>&  getFreezeLock() const { return mFreezeLock; }
     // only for debugging
     inline PixelFormat pixelFormat() const { return mFormat; }
 
 private:
-    inline sp<Buffer> getFrontBuffer() {
+    inline sp<GraphicBuffer> getFrontBufferLocked() {
         return mBuffers[mFrontBufferIndex];
     }
  
     void reloadTexture(const Region& dirty);
 
-    sp<SurfaceBuffer> requestBuffer(int index, int usage);
+    uint32_t getEffectiveUsage(uint32_t usage) const;
+
+    sp<GraphicBuffer> requestBuffer(int index, int usage);
     void destroy();
 
     class SurfaceLayer : public LayerBaseClient::Surface {
@@ -96,7 +97,7 @@
                 SurfaceID id, const sp<Layer>& owner);
         ~SurfaceLayer();
     private:
-        virtual sp<SurfaceBuffer> requestBuffer(int index, int usage);
+        virtual sp<GraphicBuffer> requestBuffer(int index, int usage);
         sp<Layer> getOwner() const {
             return static_cast<Layer*>(Surface::getOwner().get());
         }
@@ -106,16 +107,16 @@
     sp<Surface>             mSurface;
 
             bool            mSecure;
+            bool            mNoEGLImageForSwBuffers;
             int32_t         mFrontBufferIndex;
             bool            mNeedsBlending;
             bool            mNeedsDithering;
             Region          mPostedDirtyRegion;
             sp<FreezeLock>  mFreezeLock;
             PixelFormat     mFormat;
-            uint32_t        mBufferFlags;
             
             // protected by mLock
-            sp<Buffer>      mBuffers[NUM_BUFFERS];
+            sp<GraphicBuffer> mBuffers[NUM_BUFFERS];
             Texture         mTextures[NUM_BUFFERS];
             uint32_t        mWidth;
             uint32_t        mHeight;
diff --git a/libs/surfaceflinger/LayerBase.cpp b/libs/surfaceflinger/LayerBase.cpp
index 83814cc..b376e72 100644
--- a/libs/surfaceflinger/LayerBase.cpp
+++ b/libs/surfaceflinger/LayerBase.cpp
@@ -449,17 +449,9 @@
             glTranslatef(0, 1, 0);
             glRotatef(-90, 0, 0, 1);
         }
-
-        if (!(mFlags & (DisplayHardware::NPOT_EXTENSION |
-                DisplayHardware::DIRECT_TEXTURE))) {
-            // find the smallest power-of-two that will accommodate our surface
-            GLuint tw = 1 << (31 - clz(width));
-            GLuint th = 1 << (31 - clz(height));
-            if (tw < width)  tw <<= 1;
-            if (th < height) th <<= 1;
-            GLfloat ws = GLfloat(width) /tw;
-            GLfloat hs = GLfloat(height)/th;
-            glScalef(ws, hs, 1.0f);
+        
+        if (texture.NPOTAdjust) {
+            glScalef(texture.wScale, texture.hScale, 1.0f);
         }
 
         glEnableClientState(GL_TEXTURE_COORD_ARRAY);
@@ -508,21 +500,15 @@
     }
 }
 
-void LayerBase::loadTexture(Texture* texture, GLint textureName, 
+void LayerBase::loadTexture(Texture* texture, 
         const Region& dirty, const GGLSurface& t) const
 {
-    // TODO: defer the actual texture reload until LayerBase::validateTexture
-    // is called.
-
-    texture->name = textureName;
-    GLuint& textureWidth(texture->width);
-    GLuint& textureHeight(texture->height);
+    if (texture->name == -1U) {
+        // uh?
+        return;
+    }
     
-    uint32_t flags = mFlags;
-    glBindTexture(GL_TEXTURE_2D, textureName);
-
-    GLuint tw = t.width;
-    GLuint th = t.height;
+    glBindTexture(GL_TEXTURE_2D, texture->name);
 
     /*
      * In OpenGL ES we can't specify a stride with glTexImage2D (however,
@@ -547,64 +533,63 @@
     /*
      * round to POT if needed 
      */
-    
-    GLuint texture_w = tw;
-    GLuint texture_h = th;
-    if (!(flags & DisplayHardware::NPOT_EXTENSION)) {
-        // find the smallest power-of-two that will accommodate our surface
-        texture_w = 1 << (31 - clz(t.width));
-        texture_h = 1 << (31 - clz(t.height));
-        if (texture_w < t.width)  texture_w <<= 1;
-        if (texture_h < t.height) texture_h <<= 1;
+    if (!(mFlags & DisplayHardware::NPOT_EXTENSION)) {
+        texture->NPOTAdjust = true;
     }
     
-regular:
+    if (texture->NPOTAdjust) {
+        // find the smallest power-of-two that will accommodate our surface
+        texture->potWidth  = 1 << (31 - clz(t.width));
+        texture->potHeight = 1 << (31 - clz(t.height));
+        if (texture->potWidth  < t.width)  texture->potWidth  <<= 1;
+        if (texture->potHeight < t.height) texture->potHeight <<= 1;
+        texture->wScale = float(t.width)  / texture->potWidth;
+        texture->hScale = float(t.height) / texture->potHeight;
+    } else {
+        texture->potWidth  = t.width;
+        texture->potHeight = t.height;
+    }
+
     Rect bounds(dirty.bounds());
     GLvoid* data = 0;
-    if (texture_w!=textureWidth || texture_h!=textureHeight) {
-        // texture size changed, we need to create a new one
+    if (texture->width != t.width || texture->height != t.height) {
+        texture->width  = t.width;
+        texture->height = t.height;
 
-        if (!textureWidth || !textureHeight) {
-            // this is the first time, load the whole texture
-            if (texture_w==tw && texture_h==th) {
-                // we can do it one pass
-                data = t.data;
-            } else {
-                // we have to create the texture first because it
-                // doesn't match the size of the buffer
-                bounds.set(Rect(tw, th));
-            }
+        // texture size changed, we need to create a new one
+        bounds.set(Rect(t.width, t.height));
+        if (t.width  == texture->potWidth &&
+            t.height == texture->potHeight) {
+            // we can do it one pass
+            data = t.data;
         }
-        
+
         if (t.format == GGL_PIXEL_FORMAT_RGB_565) {
             glTexImage2D(GL_TEXTURE_2D, 0,
-                    GL_RGB, texture_w, texture_h, 0,
+                    GL_RGB, texture->potWidth, texture->potHeight, 0,
                     GL_RGB, GL_UNSIGNED_SHORT_5_6_5, data);
         } else if (t.format == GGL_PIXEL_FORMAT_RGBA_4444) {
             glTexImage2D(GL_TEXTURE_2D, 0,
-                    GL_RGBA, texture_w, texture_h, 0,
+                    GL_RGBA, texture->potWidth, texture->potHeight, 0,
                     GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, data);
         } else if (t.format == GGL_PIXEL_FORMAT_RGBA_8888 || 
                    t.format == GGL_PIXEL_FORMAT_RGBX_8888) {
             glTexImage2D(GL_TEXTURE_2D, 0,
-                    GL_RGBA, texture_w, texture_h, 0,
+                    GL_RGBA, texture->potWidth, texture->potHeight, 0,
                     GL_RGBA, GL_UNSIGNED_BYTE, data);
         } else if ( t.format == GGL_PIXEL_FORMAT_YCbCr_422_SP ||
                     t.format == GGL_PIXEL_FORMAT_YCbCr_420_SP) {
             // just show the Y plane of YUV buffers
             glTexImage2D(GL_TEXTURE_2D, 0,
-                    GL_LUMINANCE, texture_w, texture_h, 0,
+                    GL_LUMINANCE, texture->potWidth, texture->potHeight, 0,
                     GL_LUMINANCE, GL_UNSIGNED_BYTE, data);
         } else {
             // oops, we don't handle this format!
             LOGE("layer %p, texture=%d, using format %d, which is not "
-                 "supported by the GL", this, textureName, t.format);
-            textureName = -1;
+                 "supported by the GL", this, texture->name, t.format);
         }
-        textureWidth = texture_w;
-        textureHeight = texture_h;
     }
-    if (!data && textureName>=0) {
+    if (!data) {
         if (t.format == GGL_PIXEL_FORMAT_RGB_565) {
             glTexSubImage2D(GL_TEXTURE_2D, 0,
                     0, bounds.top, t.width, bounds.height(),
@@ -747,7 +732,7 @@
     return BnSurface::onTransact(code, data, reply, flags);
 }
 
-sp<SurfaceBuffer> LayerBaseClient::Surface::requestBuffer(int index, int usage) 
+sp<GraphicBuffer> LayerBaseClient::Surface::requestBuffer(int index, int usage) 
 {
     return NULL; 
 }
diff --git a/libs/surfaceflinger/LayerBase.h b/libs/surfaceflinger/LayerBase.h
index 0dfa4fe..efa4f8c 100644
--- a/libs/surfaceflinger/LayerBase.h
+++ b/libs/surfaceflinger/LayerBase.h
@@ -39,12 +39,11 @@
 
 // ---------------------------------------------------------------------------
 
-class SurfaceFlinger;
 class DisplayHardware;
-class GraphicPlane;
 class Client;
-class SurfaceBuffer;
-class Buffer;
+class GraphicBuffer;
+class GraphicPlane;
+class SurfaceFlinger;
 
 // ---------------------------------------------------------------------------
 
@@ -241,12 +240,18 @@
     
           struct Texture {
               Texture() : name(-1U), width(0), height(0),
-                  image(EGL_NO_IMAGE_KHR), transform(0), dirty(true) { }
+                  image(EGL_NO_IMAGE_KHR), transform(0), 
+                  NPOTAdjust(false), dirty(true) { }
               GLuint        name;
               GLuint        width;
               GLuint        height;
+              GLuint        potWidth;
+              GLuint        potHeight;
+              GLfloat       wScale;
+              GLfloat       hScale;
               EGLImageKHR   image;
               uint32_t      transform;
+              bool          NPOTAdjust;
               bool          dirty;
           };
 
@@ -254,7 +259,7 @@
                                GLclampx b, GLclampx alpha) const;
           void clearWithOpenGL(const Region& clip) const;
           void drawWithOpenGL(const Region& clip, const Texture& texture) const;
-          void loadTexture(Texture* texture, GLint textureName, 
+          void loadTexture(Texture* texture, 
                   const Region& dirty, const GGLSurface& t) const;
 
           
@@ -339,7 +344,7 @@
         sp<LayerBaseClient> getOwner() const;
 
     private:
-        virtual sp<SurfaceBuffer> requestBuffer(int index, int usage);
+        virtual sp<GraphicBuffer> requestBuffer(int index, int usage);
         virtual status_t registerBuffers(const ISurface::BufferHeap& buffers); 
         virtual void postBuffer(ssize_t offset);
         virtual void unregisterBuffers();
diff --git a/libs/surfaceflinger/LayerBlur.cpp b/libs/surfaceflinger/LayerBlur.cpp
index 0ef663f..744f2e9 100644
--- a/libs/surfaceflinger/LayerBlur.cpp
+++ b/libs/surfaceflinger/LayerBlur.cpp
@@ -189,8 +189,8 @@
             } else {
                 GLuint tw = 1 << (31 - clz(w));
                 GLuint th = 1 << (31 - clz(h));
-                if (tw < w) tw <<= 1;
-                if (th < h) th <<= 1;
+                if (tw < GLuint(w)) tw <<= 1;
+                if (th < GLuint(h)) th <<= 1;
                 glTexImage2D(GL_TEXTURE_2D, 0, mReadFormat, tw, th, 0,
                         mReadFormat, mReadType, NULL);
                 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, 
diff --git a/libs/surfaceflinger/LayerBuffer.cpp b/libs/surfaceflinger/LayerBuffer.cpp
index 667571b..7e27a02 100644
--- a/libs/surfaceflinger/LayerBuffer.cpp
+++ b/libs/surfaceflinger/LayerBuffer.cpp
@@ -23,13 +23,12 @@
 #include <utils/Log.h>
 #include <utils/StopWatch.h>
 
+#include <ui/GraphicBuffer.h>
 #include <ui/PixelFormat.h>
 #include <ui/FramebufferNativeWindow.h>
 
 #include <hardware/copybit.h>
 
-#include "Buffer.h"
-#include "BufferAllocator.h"
 #include "LayerBuffer.h"
 #include "SurfaceFlinger.h"
 #include "DisplayHardware/DisplayHardware.h"
@@ -474,9 +473,9 @@
                         mTempBitmap->getWidth() < size_t(tmp_w) || 
                         mTempBitmap->getHeight() < size_t(tmp_h)) {
                     mTempBitmap.clear();
-                    mTempBitmap = new android::Buffer(
-                            tmp_w, tmp_h, src.img.format,
-                            BufferAllocator::USAGE_HW_2D);
+                    mTempBitmap = new GraphicBuffer(
+                            tmp_w, tmp_h, src.img.format, 
+                            GraphicBuffer::USAGE_HW_2D);
                     err = mTempBitmap->initCheck();
                 }
 
@@ -549,7 +548,7 @@
         t.format = src.img.format;
         t.data = (GGLubyte*)src.img.base;
         const Region dirty(Rect(t.width, t.height));
-        mLayer.loadTexture(&mTexture, mTexture.name, dirty, t);
+        mLayer.loadTexture(&mTexture, dirty, t);
         mTexture.transform = mBufferHeap.transform;
         mLayer.drawWithOpenGL(clip, mTexture);
     }
diff --git a/libs/surfaceflinger/LayerBuffer.h b/libs/surfaceflinger/LayerBuffer.h
index 0452818..5eb472c 100644
--- a/libs/surfaceflinger/LayerBuffer.h
+++ b/libs/surfaceflinger/LayerBuffer.h
@@ -20,9 +20,6 @@
 #include <stdint.h>
 #include <sys/types.h>
 
-#include <binder/IMemory.h>
-#include <private/ui/LayerState.h>
-
 #include "LayerBase.h"
 
 struct copybit_device_t;
@@ -133,7 +130,7 @@
         status_t                        mStatus;
         ISurface::BufferHeap            mBufferHeap;
         size_t                          mBufferSize;
-        mutable sp<android::Buffer>     mTempBitmap;
+        mutable sp<GraphicBuffer>       mTempBitmap;
         mutable LayerBase::Texture      mTexture;
         copybit_device_t*               mBlitEngine;
     };
diff --git a/libs/surfaceflinger/LayerDim.cpp b/libs/surfaceflinger/LayerDim.cpp
index 8ba0a9d..538dc77 100644
--- a/libs/surfaceflinger/LayerDim.cpp
+++ b/libs/surfaceflinger/LayerDim.cpp
@@ -21,8 +21,8 @@
 #include <utils/Errors.h>
 #include <utils/Log.h>
 
-#include "Buffer.h"
-#include "BufferAllocator.h"
+#include <ui/GraphicBuffer.h>
+
 #include "LayerDim.h"
 #include "SurfaceFlinger.h"
 #include "DisplayHardware/DisplayHardware.h"
@@ -70,9 +70,9 @@
 
     if (LIKELY(flags & DisplayHardware::DIRECT_TEXTURE)) {
         // TODO: api to pass the usage flags
-        sp<Buffer> buffer = new Buffer(w, h, PIXEL_FORMAT_RGB_565,
-                 BufferAllocator::USAGE_SW_WRITE_OFTEN |
-                 BufferAllocator::USAGE_HW_TEXTURE);
+        sp<GraphicBuffer> buffer = new GraphicBuffer(w, h, PIXEL_FORMAT_RGB_565,
+                 GraphicBuffer::USAGE_SW_WRITE_OFTEN |
+                 GraphicBuffer::USAGE_HW_TEXTURE);
         
         android_native_buffer_t* clientBuf = buffer->getNativeBuffer();
 
diff --git a/libs/surfaceflinger/SurfaceFlinger.cpp b/libs/surfaceflinger/SurfaceFlinger.cpp
index f2b918f..9694cf1 100644
--- a/libs/surfaceflinger/SurfaceFlinger.cpp
+++ b/libs/surfaceflinger/SurfaceFlinger.cpp
@@ -37,6 +37,7 @@
 #include <utils/String16.h>
 #include <utils/StopWatch.h>
 
+#include <ui/GraphicBufferAllocator.h>
 #include <ui/PixelFormat.h>
 #include <ui/DisplayInfo.h>
 
@@ -44,8 +45,6 @@
 #include <GLES/gl.h>
 
 #include "clz.h"
-#include "Buffer.h"
-#include "BufferAllocator.h"
 #include "Layer.h"
 #include "LayerBlur.h"
 #include "LayerBuffer.h"
@@ -190,6 +189,7 @@
         mLastSwapBufferTime(0),
         mDebugInTransaction(0),
         mLastTransactionTime(0),
+        mBootFinished(false),
         mConsoleSignals(0),
         mSecureFrameBuffer(0)
 {
@@ -294,6 +294,7 @@
     const nsecs_t now = systemTime();
     const nsecs_t duration = now - mBootTime;
     LOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );  
+    mBootFinished = true;
     property_set("ctl.stop", "bootanim");
 }
 
@@ -1521,8 +1522,8 @@
             if (l != 0) {
                 SharedBufferStack::Statistics stats = l->lcblk->getStats();
                 result.append( l->lcblk->dump("      ") );
-                sp<const Buffer> buf0(l->getBuffer(0));
-                sp<const Buffer> buf1(l->getBuffer(1));
+                sp<const GraphicBuffer> buf0(l->getBuffer(0));
+                sp<const GraphicBuffer> buf1(l->getBuffer(1));
                 uint32_t w0=0, h0=0, s0=0;
                 uint32_t w1=0, h1=0, s1=0;
                 if (buf0 != 0) {
@@ -1573,7 +1574,7 @@
         }
         snprintf(buffer, SIZE, "  client count: %d\n", mClientsMap.size());
         result.append(buffer);
-        const BufferAllocator& alloc(BufferAllocator::get());
+        const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
         alloc.dump(result);
 
         if (locked) {
diff --git a/libs/surfaceflinger/SurfaceFlinger.h b/libs/surfaceflinger/SurfaceFlinger.h
index e446070..6698e00 100644
--- a/libs/surfaceflinger/SurfaceFlinger.h
+++ b/libs/surfaceflinger/SurfaceFlinger.h
@@ -293,7 +293,7 @@
             inline void decFreezeCount() { if (mFreezeCount > 0) mFreezeCount--; }
             inline bool hasFreezeRequest() const { return mFreezeDisplay; }
             inline bool isFrozen() const { 
-                return mFreezeDisplay || mFreezeCount>0;
+                return (mFreezeDisplay || mFreezeCount>0) && mBootFinished;
             }
 
             
@@ -351,6 +351,7 @@
                 nsecs_t                     mLastSwapBufferTime;
                 volatile nsecs_t            mDebugInTransaction;
                 nsecs_t                     mLastTransactionTime;
+                bool                        mBootFinished;
 
                 // these are thread safe
     mutable     Barrier                     mReadyToRunBarrier;
diff --git a/libs/ui/Android.mk b/libs/ui/Android.mk
index 9577044..73d86ea 100644
--- a/libs/ui/Android.mk
+++ b/libs/ui/Android.mk
@@ -2,13 +2,15 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES:= \
-	BufferMapper.cpp \
 	Camera.cpp \
 	CameraParameters.cpp \
 	EGLUtils.cpp \
 	EventHub.cpp \
 	EventRecurrence.cpp \
 	FramebufferNativeWindow.cpp \
+	GraphicBuffer.cpp \
+	GraphicBufferAllocator.cpp \
+	GraphicBufferMapper.cpp \
 	KeyLayoutMap.cpp \
 	KeyCharacterMap.cpp \
 	ICamera.cpp \
@@ -25,7 +27,6 @@
 	Region.cpp \
 	SharedBufferStack.cpp \
 	Surface.cpp \
-	SurfaceBuffer.cpp \
 	SurfaceComposerClient.cpp \
 	SurfaceFlingerSynchro.cpp 
 
diff --git a/libs/ui/BufferMapper.cpp b/libs/ui/BufferMapper.cpp
deleted file mode 100644
index 4add8f9..0000000
--- a/libs/ui/BufferMapper.cpp
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "BufferMapper"
-
-#include <stdint.h>
-#include <errno.h>
-
-#include <utils/Errors.h>
-#include <utils/Log.h>
-
-#include <ui/BufferMapper.h>
-#include <ui/Rect.h>
-
-#include <hardware/gralloc.h>
-
-
-namespace android {
-// ---------------------------------------------------------------------------
-
-ANDROID_SINGLETON_STATIC_INSTANCE( BufferMapper )
-
-BufferMapper::BufferMapper()
-    : mAllocMod(0)
-{
-    hw_module_t const* module;
-    int err = hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &module);
-    LOGE_IF(err, "FATAL: can't find the %s module", GRALLOC_HARDWARE_MODULE_ID);
-    if (err == 0) {
-        mAllocMod = (gralloc_module_t const *)module;
-    }
-}
-
-status_t BufferMapper::registerBuffer(buffer_handle_t handle)
-{
-    status_t err = mAllocMod->registerBuffer(mAllocMod, handle);
-    LOGW_IF(err, "registerBuffer(%p) failed %d (%s)",
-            handle, err, strerror(-err));
-    return err;
-}
-
-status_t BufferMapper::unregisterBuffer(buffer_handle_t handle)
-{
-    status_t err = mAllocMod->unregisterBuffer(mAllocMod, handle);
-    LOGW_IF(err, "unregisterBuffer(%p) failed %d (%s)",
-            handle, err, strerror(-err));
-    return err;
-}
-
-status_t BufferMapper::lock(buffer_handle_t handle, 
-        int usage, const Rect& bounds, void** vaddr)
-{
-    status_t err = mAllocMod->lock(mAllocMod, handle, usage,
-            bounds.left, bounds.top, bounds.width(), bounds.height(), vaddr);
-    LOGW_IF(err, "lock(...) failed %d (%s)", err, strerror(-err));
-    return err;
-}
-
-status_t BufferMapper::unlock(buffer_handle_t handle)
-{
-    status_t err = mAllocMod->unlock(mAllocMod, handle);
-    LOGW_IF(err, "unlock(...) failed %d (%s)", err, strerror(-err));
-    return err;
-}
-
-// ---------------------------------------------------------------------------
-}; // namespace android
diff --git a/libs/ui/Camera.cpp b/libs/ui/Camera.cpp
index 0c6d340..09a36f1 100644
--- a/libs/ui/Camera.cpp
+++ b/libs/ui/Camera.cpp
@@ -278,6 +278,15 @@
     return params;
 }
 
+// send command to camera driver
+status_t Camera::sendCommand(int32_t cmd, int32_t arg1, int32_t arg2)
+{
+    LOGD("sendCommand");
+    sp <ICamera> c = mCamera;
+    if (c == 0) return NO_INIT;
+    return c->sendCommand(cmd, arg1, arg2);
+}
+
 void Camera::setListener(const sp<CameraListener>& listener)
 {
     Mutex::Autolock _l(mLock);
diff --git a/libs/ui/GraphicBuffer.cpp b/libs/ui/GraphicBuffer.cpp
new file mode 100644
index 0000000..1cf20d7
--- /dev/null
+++ b/libs/ui/GraphicBuffer.cpp
@@ -0,0 +1,213 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdlib.h>
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <binder/Parcel.h>
+
+#include <utils/Errors.h>
+#include <utils/Log.h>
+
+#include <ui/GraphicBuffer.h>
+#include <ui/GraphicBufferAllocator.h>
+#include <ui/GraphicBufferMapper.h>
+#include <ui/PixelFormat.h>
+
+#include <pixelflinger/pixelflinger.h>
+
+namespace android {
+
+// ===========================================================================
+// Buffer and implementation of android_native_buffer_t
+// ===========================================================================
+
+GraphicBuffer::GraphicBuffer()
+    : BASE(), mOwner(false), mBufferMapper(GraphicBufferMapper::get()),
+      mInitCheck(NO_ERROR),  mVStride(0), mIndex(-1)
+{
+    width  = 
+    height = 
+    stride = 
+    format = 
+    usage  = 0;
+    handle = NULL;
+}
+
+GraphicBuffer::GraphicBuffer(uint32_t w, uint32_t h, 
+        PixelFormat reqFormat, uint32_t reqUsage)
+    : BASE(), mOwner(false), mBufferMapper(GraphicBufferMapper::get()),
+      mInitCheck(NO_ERROR),  mVStride(0), mIndex(-1)
+{
+    width  = 
+    height = 
+    stride = 
+    format = 
+    usage  = 0;
+    handle = NULL;
+    mInitCheck = initSize(w, h, reqFormat, reqUsage);
+}
+
+GraphicBuffer::GraphicBuffer(const Parcel& data) 
+    : BASE(), mOwner(true), mBufferMapper(GraphicBufferMapper::get()),
+      mInitCheck(NO_ERROR),  mVStride(0), mIndex(-1)
+{
+    // we own the handle in this case
+    width  = data.readInt32();
+    if (width < 0) {
+        width = height = stride = format = usage = 0;
+        handle = 0;
+    } else {
+        height = data.readInt32();
+        stride = data.readInt32();
+        format = data.readInt32();
+        usage  = data.readInt32();
+        handle = data.readNativeHandle();
+    }
+}
+
+GraphicBuffer::~GraphicBuffer()
+{
+    if (handle) {
+        if (mOwner) {
+            native_handle_close(handle);
+            native_handle_delete(const_cast<native_handle*>(handle));
+        } else {
+            GraphicBufferAllocator& allocator(GraphicBufferAllocator::get());
+            allocator.free(handle);
+        }
+    }
+}
+
+status_t GraphicBuffer::initCheck() const {
+    return mInitCheck;
+}
+
+android_native_buffer_t* GraphicBuffer::getNativeBuffer() const
+{
+    return static_cast<android_native_buffer_t*>(
+            const_cast<GraphicBuffer*>(this));
+}
+
+status_t GraphicBuffer::reallocate(uint32_t w, uint32_t h, PixelFormat f,
+        uint32_t reqUsage)
+{
+    if (handle) {
+        GraphicBufferAllocator& allocator(GraphicBufferAllocator::get());
+        allocator.free(handle);
+        handle = 0;
+    }
+    return initSize(w, h, f, reqUsage);
+}
+
+status_t GraphicBuffer::initSize(uint32_t w, uint32_t h, PixelFormat format,
+        uint32_t reqUsage)
+{
+    if (format == PIXEL_FORMAT_RGBX_8888)
+        format = PIXEL_FORMAT_RGBA_8888;
+
+    GraphicBufferAllocator& allocator = GraphicBufferAllocator::get();
+    status_t err = allocator.alloc(w, h, format, reqUsage, &handle, &stride);
+    if (err == NO_ERROR) {
+        this->width  = w;
+        this->height = h;
+        this->format = format;
+        this->usage  = reqUsage;
+        mVStride = 0;
+    }
+    return err;
+}
+
+status_t GraphicBuffer::lock(uint32_t usage, void** vaddr)
+{
+    const Rect lockBounds(width, height);
+    status_t res = lock(usage, lockBounds, vaddr);
+    return res;
+}
+
+status_t GraphicBuffer::lock(uint32_t usage, const Rect& rect, void** vaddr)
+{
+    if (rect.left < 0 || rect.right  > this->width || 
+        rect.top  < 0 || rect.bottom > this->height) {
+        LOGE("locking pixels (%d,%d,%d,%d) outside of buffer (w=%d, h=%d)",
+                rect.left, rect.top, rect.right, rect.bottom, 
+                this->width, this->height);
+        return BAD_VALUE;
+    }
+    status_t res = getBufferMapper().lock(handle, usage, rect, vaddr);
+    return res;
+}
+
+status_t GraphicBuffer::unlock()
+{
+    status_t res = getBufferMapper().unlock(handle);
+    return res;
+}
+
+status_t GraphicBuffer::lock(GGLSurface* sur, uint32_t usage) 
+{
+    void* vaddr;
+    status_t res = GraphicBuffer::lock(usage, &vaddr);
+    if (res == NO_ERROR && sur) {
+        sur->version = sizeof(GGLSurface);
+        sur->width = width;
+        sur->height = height;
+        sur->stride = stride;
+        sur->format = format;
+        sur->vstride = mVStride;
+        sur->data = static_cast<GGLubyte*>(vaddr);
+    }
+    return res;
+}
+
+
+status_t GraphicBuffer::writeToParcel(Parcel* reply, 
+        android_native_buffer_t const* buffer)
+{
+    if (buffer == NULL)
+        return BAD_VALUE;
+
+    if (buffer->width < 0 || buffer->height < 0)
+        return BAD_VALUE;
+
+    status_t err = NO_ERROR;
+    if (buffer->handle == NULL) {
+        // this buffer doesn't have a handle
+        reply->writeInt32(NO_MEMORY);
+    } else {
+        reply->writeInt32(buffer->width);
+        reply->writeInt32(buffer->height);
+        reply->writeInt32(buffer->stride);
+        reply->writeInt32(buffer->format);
+        reply->writeInt32(buffer->usage);
+        err = reply->writeNativeHandle(buffer->handle);
+    }
+    return err;
+}
+
+
+void GraphicBuffer::setIndex(int index) {
+    mIndex = index;
+}
+
+int GraphicBuffer::getIndex() const {
+    return mIndex;
+}
+
+// ---------------------------------------------------------------------------
+
+}; // namespace android
diff --git a/libs/surfaceflinger/BufferAllocator.cpp b/libs/ui/GraphicBufferAllocator.cpp
similarity index 74%
rename from libs/surfaceflinger/BufferAllocator.cpp
rename to libs/ui/GraphicBufferAllocator.cpp
index 3e37bc3..57d5fc3 100644
--- a/libs/surfaceflinger/BufferAllocator.cpp
+++ b/libs/ui/GraphicBufferAllocator.cpp
@@ -20,18 +20,20 @@
 #include <utils/Singleton.h>
 #include <utils/String8.h>
 
-#include "BufferAllocator.h"
+#include <ui/GraphicBufferAllocator.h>
 
+#include <private/ui/sw_gralloc_handle.h>
 
 namespace android {
 // ---------------------------------------------------------------------------
 
-ANDROID_SINGLETON_STATIC_INSTANCE( BufferAllocator )
+ANDROID_SINGLETON_STATIC_INSTANCE( GraphicBufferAllocator )
 
-Mutex BufferAllocator::sLock;
-KeyedVector<buffer_handle_t, BufferAllocator::alloc_rec_t> BufferAllocator::sAllocList;
+Mutex GraphicBufferAllocator::sLock;
+KeyedVector<buffer_handle_t,
+    GraphicBufferAllocator::alloc_rec_t> GraphicBufferAllocator::sAllocList;
 
-BufferAllocator::BufferAllocator()
+GraphicBufferAllocator::GraphicBufferAllocator()
     : mAllocDev(0)
 {
     hw_module_t const* module;
@@ -42,12 +44,12 @@
     }
 }
 
-BufferAllocator::~BufferAllocator()
+GraphicBufferAllocator::~GraphicBufferAllocator()
 {
     gralloc_close(mAllocDev);
 }
 
-void BufferAllocator::dump(String8& result) const
+void GraphicBufferAllocator::dump(String8& result) const
 {
     Mutex::Autolock _l(sLock);
     KeyedVector<buffer_handle_t, alloc_rec_t>& list(sAllocList);
@@ -73,7 +75,7 @@
     return c>0 ? c : 1;
 }
 
-status_t BufferAllocator::alloc(uint32_t w, uint32_t h, PixelFormat format,
+status_t GraphicBufferAllocator::alloc(uint32_t w, uint32_t h, PixelFormat format,
         int usage, buffer_handle_t* handle, int32_t* stride)
 {
     Mutex::Autolock _l(mLock);
@@ -83,8 +85,13 @@
     h = clamp(h);
 
     // we have a h/w allocator and h/w buffer is requested
-    status_t err = mAllocDev->alloc(mAllocDev,
-            w, h, format, usage, handle, stride);
+    status_t err; 
+    
+    if (usage & GRALLOC_USAGE_HW_MASK) {
+        err = mAllocDev->alloc(mAllocDev, w, h, format, usage, handle, stride);
+    } else {
+        err = sw_gralloc_handle_t::alloc(w, h, format, usage, handle, stride);
+    }
 
     LOGW_IF(err, "alloc(%u, %u, %d, %08x, ...) failed %d (%s)",
             w, h, format, usage, err, strerror(-err));
@@ -109,13 +116,18 @@
     return err;
 }
 
-status_t BufferAllocator::free(buffer_handle_t handle)
+status_t GraphicBufferAllocator::free(buffer_handle_t handle)
 {
     Mutex::Autolock _l(mLock);
 
-    status_t err = mAllocDev->free(mAllocDev, handle);
+    status_t err;
+    if (sw_gralloc_handle_t::validate(handle) < 0) {
+        err = mAllocDev->free(mAllocDev, handle);
+    } else {
+        err = sw_gralloc_handle_t::free((sw_gralloc_handle_t*)handle);
+    }
+
     LOGW_IF(err, "free(...) failed %d (%s)", err, strerror(-err));
-    
     if (err == NO_ERROR) {
         Mutex::Autolock _l(sLock);
         KeyedVector<buffer_handle_t, alloc_rec_t>& list(sAllocList);
diff --git a/libs/ui/GraphicBufferMapper.cpp b/libs/ui/GraphicBufferMapper.cpp
new file mode 100644
index 0000000..ce2acd0
--- /dev/null
+++ b/libs/ui/GraphicBufferMapper.cpp
@@ -0,0 +1,228 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "GraphicBufferMapper"
+
+#include <stdint.h>
+#ifdef HAVE_ANDROID_OS      // just want PAGE_SIZE define
+# include <asm/page.h>
+#else
+# include <sys/user.h>
+#endif
+#include <errno.h>
+#include <sys/mman.h>
+
+#include <cutils/ashmem.h>
+
+#include <utils/Errors.h>
+#include <utils/Log.h>
+
+#include <ui/GraphicBufferMapper.h>
+#include <ui/Rect.h>
+
+#include <hardware/gralloc.h>
+
+#include <private/ui/sw_gralloc_handle.h>
+
+
+namespace android {
+// ---------------------------------------------------------------------------
+
+ANDROID_SINGLETON_STATIC_INSTANCE( GraphicBufferMapper )
+
+GraphicBufferMapper::GraphicBufferMapper()
+    : mAllocMod(0)
+{
+    hw_module_t const* module;
+    int err = hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &module);
+    LOGE_IF(err, "FATAL: can't find the %s module", GRALLOC_HARDWARE_MODULE_ID);
+    if (err == 0) {
+        mAllocMod = (gralloc_module_t const *)module;
+    }
+}
+
+status_t GraphicBufferMapper::registerBuffer(buffer_handle_t handle)
+{
+    status_t err;
+    if (sw_gralloc_handle_t::validate(handle) < 0) {
+        err = mAllocMod->registerBuffer(mAllocMod, handle);
+    } else {
+        err = sw_gralloc_handle_t::registerBuffer((sw_gralloc_handle_t*)handle);
+    }
+    LOGW_IF(err, "registerBuffer(%p) failed %d (%s)",
+            handle, err, strerror(-err));
+    return err;
+}
+
+status_t GraphicBufferMapper::unregisterBuffer(buffer_handle_t handle)
+{
+    status_t err;
+    if (sw_gralloc_handle_t::validate(handle) < 0) {
+        err = mAllocMod->unregisterBuffer(mAllocMod, handle);
+    } else {
+        err = sw_gralloc_handle_t::unregisterBuffer((sw_gralloc_handle_t*)handle);
+    }
+    LOGW_IF(err, "unregisterBuffer(%p) failed %d (%s)",
+            handle, err, strerror(-err));
+    return err;
+}
+
+status_t GraphicBufferMapper::lock(buffer_handle_t handle, 
+        int usage, const Rect& bounds, void** vaddr)
+{
+    status_t err;
+    if (sw_gralloc_handle_t::validate(handle) < 0) {
+        err = mAllocMod->lock(mAllocMod, handle, usage,
+                bounds.left, bounds.top, bounds.width(), bounds.height(),
+                vaddr);
+    } else {
+        err = sw_gralloc_handle_t::lock((sw_gralloc_handle_t*)handle, usage,
+                bounds.left, bounds.top, bounds.width(), bounds.height(),
+                vaddr);
+    }
+    LOGW_IF(err, "lock(...) failed %d (%s)", err, strerror(-err));
+    return err;
+}
+
+status_t GraphicBufferMapper::unlock(buffer_handle_t handle)
+{
+    status_t err;
+    if (sw_gralloc_handle_t::validate(handle) < 0) {
+        err = mAllocMod->unlock(mAllocMod, handle);
+    } else {
+        err = sw_gralloc_handle_t::unlock((sw_gralloc_handle_t*)handle);
+    }
+    LOGW_IF(err, "unlock(...) failed %d (%s)", err, strerror(-err));
+    return err;
+}
+
+// ---------------------------------------------------------------------------
+
+status_t sw_gralloc_handle_t::alloc(uint32_t w, uint32_t h, int format,
+        int usage, buffer_handle_t* pHandle, int32_t* pStride)
+{
+    int align = 4;
+    int bpp = 0;
+    switch (format) {
+        case HAL_PIXEL_FORMAT_RGBA_8888:
+        case HAL_PIXEL_FORMAT_RGBX_8888:
+        case HAL_PIXEL_FORMAT_BGRA_8888:
+            bpp = 4;
+            break;
+        case HAL_PIXEL_FORMAT_RGB_888:
+            bpp = 3;
+            break;
+        case HAL_PIXEL_FORMAT_RGB_565:
+        case HAL_PIXEL_FORMAT_RGBA_5551:
+        case HAL_PIXEL_FORMAT_RGBA_4444:
+            bpp = 2;
+            break;
+        default:
+            return -EINVAL;
+    }
+    size_t bpr = (w*bpp + (align-1)) & ~(align-1);
+    size_t size = bpr * h;
+    size_t stride = bpr / bpp;
+    size = (size + (PAGE_SIZE-1)) & ~(PAGE_SIZE-1);
+    
+    int fd = ashmem_create_region("sw-gralloc-buffer", size);
+    if (fd < 0) {
+        LOGE("ashmem_create_region(size=%d) failed (%s)",
+                size, strerror(-errno));
+        return -errno;
+    }
+    
+    int prot = PROT_READ;
+    if (usage & GRALLOC_USAGE_SW_WRITE_MASK)
+        prot |= PROT_WRITE;
+    
+    if (ashmem_set_prot_region(fd, prot) < 0) {
+        LOGE("ashmem_set_prot_region(fd=%d, prot=%x) failed (%s)",
+                fd, prot, strerror(-errno));
+        close(fd);
+        return -errno;
+    }
+
+    void* base = mmap(0, size, prot, MAP_SHARED, fd, 0);
+    if (base == MAP_FAILED) {
+        LOGE("alloc mmap(fd=%d, size=%d, prot=%x) failed (%s)",
+                fd, size, prot, strerror(-errno));
+        close(fd);
+        return -errno;
+    }
+
+    sw_gralloc_handle_t* hnd = new sw_gralloc_handle_t();
+    hnd->fd = fd;
+    hnd->size = size;
+    hnd->base = intptr_t(base);
+    hnd->prot = prot;
+    *pStride = stride;
+    *pHandle = hnd; 
+    
+    return NO_ERROR;
+}
+
+status_t sw_gralloc_handle_t::free(sw_gralloc_handle_t* hnd)
+{
+    if (hnd->base) {
+        munmap((void*)hnd->base, hnd->size);
+    }
+    if (hnd->fd >= 0) {
+        close(hnd->fd);
+    }
+    delete hnd;    
+    return NO_ERROR;
+}
+
+status_t sw_gralloc_handle_t::registerBuffer(sw_gralloc_handle_t* hnd)
+{
+    if (hnd->pid != getpid()) {
+        void* base = mmap(0, hnd->size, hnd->prot, MAP_SHARED, hnd->fd, 0);
+        if (base == MAP_FAILED) {
+            LOGE("registerBuffer mmap(fd=%d, size=%d, prot=%x) failed (%s)",
+                    hnd->fd, hnd->size, hnd->prot, strerror(-errno));
+            return -errno;
+        }
+        hnd->base = intptr_t(base);
+    }
+    return NO_ERROR;
+}
+
+status_t sw_gralloc_handle_t::unregisterBuffer(sw_gralloc_handle_t* hnd)
+{
+    if (hnd->pid != getpid()) {
+        if (hnd->base) {
+            munmap((void*)hnd->base, hnd->size);
+        }
+        hnd->base = 0;
+    }
+    return NO_ERROR;
+}
+
+status_t sw_gralloc_handle_t::lock(sw_gralloc_handle_t* hnd, int usage,
+        int l, int t, int w, int h, void** vaddr)
+{
+    *vaddr = (void*)hnd->base;
+    return NO_ERROR;
+}
+
+status_t sw_gralloc_handle_t::unlock(sw_gralloc_handle_t* hnd)
+{
+    return NO_ERROR;
+}
+
+// ---------------------------------------------------------------------------
+}; // namespace android
diff --git a/libs/ui/ICamera.cpp b/libs/ui/ICamera.cpp
index fd7e084..e1b3ec7 100644
--- a/libs/ui/ICamera.cpp
+++ b/libs/ui/ICamera.cpp
@@ -36,6 +36,7 @@
     TAKE_PICTURE,
     SET_PARAMETERS,
     GET_PARAMETERS,
+    SEND_COMMAND,
     CONNECT,
     LOCK,
     UNLOCK,
@@ -205,6 +206,17 @@
         remote()->transact(GET_PARAMETERS, data, &reply);
         return reply.readString8();
     }
+    virtual status_t sendCommand(int32_t cmd, int32_t arg1, int32_t arg2)
+    {
+        LOGD("sendCommand");
+        Parcel data, reply;
+        data.writeInterfaceToken(ICamera::getInterfaceDescriptor());
+        data.writeInt32(cmd);
+        data.writeInt32(arg1);
+        data.writeInt32(arg2);
+        remote()->transact(SEND_COMMAND, data, &reply);
+        return reply.readInt32();
+    }
     virtual status_t connect(const sp<ICameraClient>& cameraClient)
     {
         Parcel data, reply;
@@ -331,6 +343,15 @@
              reply->writeString8(getParameters());
             return NO_ERROR;
          } break;
+        case SEND_COMMAND: {
+            LOGD("SEND_COMMAND");
+            CHECK_INTERFACE(ICamera, data, reply);
+            int command = data.readInt32();
+            int arg1 = data.readInt32();
+            int arg2 = data.readInt32();
+            reply->writeInt32(sendCommand(command, arg1, arg2));
+            return NO_ERROR;
+         } break;
         case CONNECT: {
             CHECK_INTERFACE(ICamera, data, reply);
             sp<ICameraClient> cameraClient = interface_cast<ICameraClient>(data.readStrongBinder());
diff --git a/libs/ui/ISurface.cpp b/libs/ui/ISurface.cpp
index a2dbe7f..4fb38ed 100644
--- a/libs/ui/ISurface.cpp
+++ b/libs/ui/ISurface.cpp
@@ -27,7 +27,7 @@
 #include <ui/Overlay.h>
 #include <ui/Surface.h>
 
-#include <private/ui/SurfaceBuffer.h>
+#include <ui/GraphicBuffer.h>
 
 namespace android {
 
@@ -71,14 +71,14 @@
     {
     }
 
-    virtual sp<SurfaceBuffer> requestBuffer(int bufferIdx, int usage)
+    virtual sp<GraphicBuffer> requestBuffer(int bufferIdx, int usage)
     {
         Parcel data, reply;
         data.writeInterfaceToken(ISurface::getInterfaceDescriptor());
         data.writeInt32(bufferIdx);
         data.writeInt32(usage);
         remote()->transact(REQUEST_BUFFER, data, &reply);
-        sp<SurfaceBuffer> buffer = new SurfaceBuffer(reply);
+        sp<GraphicBuffer> buffer = new GraphicBuffer(reply);
         return buffer;
     }
 
@@ -139,8 +139,8 @@
             CHECK_INTERFACE(ISurface, data, reply);
             int bufferIdx = data.readInt32();
             int usage = data.readInt32();
-            sp<SurfaceBuffer> buffer(requestBuffer(bufferIdx, usage));
-            return SurfaceBuffer::writeToParcel(reply, buffer.get());
+            sp<GraphicBuffer> buffer(requestBuffer(bufferIdx, usage));
+            return GraphicBuffer::writeToParcel(reply, buffer.get());
         }
         case REGISTER_BUFFERS: {
             CHECK_INTERFACE(ISurface, data, reply);
diff --git a/libs/ui/SharedBufferStack.cpp b/libs/ui/SharedBufferStack.cpp
index 47c596c..b460757 100644
--- a/libs/ui/SharedBufferStack.cpp
+++ b/libs/ui/SharedBufferStack.cpp
@@ -97,10 +97,10 @@
 // ----------------------------------------------------------------------------
 
 SharedBufferBase::SharedBufferBase(SharedClient* sharedClient,
-        int surface, int num)
+        int surface, int num, int32_t identity)
     : mSharedClient(sharedClient), 
       mSharedStack(sharedClient->surfaces + surface),
-      mNumBuffers(num)
+      mNumBuffers(num), mIdentity(identity)
 {
 }
 
@@ -248,8 +248,8 @@
 // ============================================================================
 
 SharedBufferClient::SharedBufferClient(SharedClient* sharedClient,
-        int surface, int num)
-    : SharedBufferBase(sharedClient, surface, num), tail(0)
+        int surface, int num, int32_t identity)
+    : SharedBufferBase(sharedClient, surface, num, identity), tail(0)
 {
     tail = computeTail();
 }
@@ -353,7 +353,7 @@
 
 SharedBufferServer::SharedBufferServer(SharedClient* sharedClient,
         int surface, int num, int32_t identity)
-    : SharedBufferBase(sharedClient, surface, num)
+    : SharedBufferBase(sharedClient, surface, num, identity)
 {
     mSharedStack->init(identity);
     mSharedStack->head = num-1;
diff --git a/libs/ui/Surface.cpp b/libs/ui/Surface.cpp
index 285edb4..2d83a8c 100644
--- a/libs/ui/Surface.cpp
+++ b/libs/ui/Surface.cpp
@@ -31,7 +31,8 @@
 #include <utils/Log.h>
 
 #include <ui/DisplayInfo.h>
-#include <ui/BufferMapper.h>
+#include <ui/GraphicBuffer.h>
+#include <ui/GraphicBufferMapper.h>
 #include <ui/ISurface.h>
 #include <ui/Surface.h>
 #include <ui/SurfaceComposerClient.h>
@@ -41,15 +42,14 @@
 
 #include <private/ui/SharedBufferStack.h>
 #include <private/ui/LayerState.h>
-#include <private/ui/SurfaceBuffer.h>
 
 namespace android {
 
 // ----------------------------------------------------------------------
 
 static status_t copyBlt(
-        const sp<SurfaceBuffer>& dst, 
-        const sp<SurfaceBuffer>& src, 
+        const sp<GraphicBuffer>& dst, 
+        const sp<GraphicBuffer>& src, 
         const Region& reg)
 {
     status_t err;
@@ -310,17 +310,17 @@
     : mClient(surface->mClient), mSurface(surface->mSurface),
       mToken(surface->mToken), mIdentity(surface->mIdentity),
       mFormat(surface->mFormat), mFlags(surface->mFlags),
-      mBufferMapper(BufferMapper::get()), mSharedBufferClient(NULL),
+      mBufferMapper(GraphicBufferMapper::get()), mSharedBufferClient(NULL),
       mWidth(surface->mWidth), mHeight(surface->mHeight)
 {
     mSharedBufferClient = new SharedBufferClient(
-            mClient->mControl, mToken, 2);
+            mClient->mControl, mToken, 2, mIdentity);
 
     init();
 }
 
 Surface::Surface(const Parcel& parcel)
-    :  mBufferMapper(BufferMapper::get()), mSharedBufferClient(NULL)
+    :  mBufferMapper(GraphicBufferMapper::get()), mSharedBufferClient(NULL)
 {
     sp<IBinder> clientBinder = parcel.readStrongBinder();
     mSurface    = interface_cast<ISurface>(parcel.readStrongBinder());
@@ -336,7 +336,7 @@
         mClient = SurfaceComposerClient::clientForConnection(clientBinder);
 
         mSharedBufferClient = new SharedBufferClient(
-                mClient->mControl, mToken, 2);
+                mClient->mControl, mToken, 2, mIdentity);
     }
 
     init();
@@ -473,11 +473,11 @@
 
 // ----------------------------------------------------------------------------
 
-status_t Surface::dequeueBuffer(sp<SurfaceBuffer>* buffer) {
+status_t Surface::dequeueBuffer(sp<GraphicBuffer>* buffer) {
     android_native_buffer_t* out;
     status_t err = dequeueBuffer(&out);
     if (err == NO_ERROR) {
-        *buffer = SurfaceBuffer::getSelf(out);
+        *buffer = GraphicBuffer::getSelf(out);
     }
     return err;
 }
@@ -500,7 +500,7 @@
 
     // below we make sure we AT LEAST have the usage flags we want
     const uint32_t usage(getUsage());
-    const sp<SurfaceBuffer>& backBuffer(mBuffers[bufIdx]);
+    const sp<GraphicBuffer>& backBuffer(mBuffers[bufIdx]);
     if (backBuffer == 0 || 
         ((uint32_t(backBuffer->usage) & usage) != usage) ||
         mSharedBufferClient->needNewBuffer(bufIdx)) 
@@ -537,7 +537,7 @@
     if (err != NO_ERROR)
         return err;
 
-    int32_t bufIdx = SurfaceBuffer::getSelf(buffer)->getIndex();
+    int32_t bufIdx = GraphicBuffer::getSelf(buffer)->getIndex();
     err = mSharedBufferClient->lock(bufIdx);
     LOGE_IF(err, "error locking buffer %d (%s)", bufIdx, strerror(-err));
     return err;
@@ -554,7 +554,7 @@
         mDirtyRegion.set(mSwapRectangle);
     }
     
-    int32_t bufIdx = SurfaceBuffer::getSelf(buffer)->getIndex();
+    int32_t bufIdx = GraphicBuffer::getSelf(buffer)->getIndex();
     mSharedBufferClient->setDirtyRegion(bufIdx, mDirtyRegion);
     err = mSharedBufferClient->queue(bufIdx);
     LOGE_IF(err, "error queuing buffer %d (%s)", bufIdx, strerror(-err));
@@ -627,7 +627,7 @@
     // we're intending to do software rendering from this point
     setUsage(GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
 
-    sp<SurfaceBuffer> backBuffer;
+    sp<GraphicBuffer> backBuffer;
     status_t err = dequeueBuffer(&backBuffer);
     LOGE_IF(err, "dequeueBuffer failed (%s)", strerror(-err));
     if (err == NO_ERROR) {
@@ -652,7 +652,7 @@
                 newDirtyRegion.andSelf(bounds);
             }
 
-            const sp<SurfaceBuffer>& frontBuffer(mPostedBuffer);
+            const sp<GraphicBuffer>& frontBuffer(mPostedBuffer);
             if (frontBuffer !=0 &&
                 backBuffer->width  == frontBuffer->width && 
                 backBuffer->height == frontBuffer->height &&
@@ -721,13 +721,13 @@
     status_t err = NO_MEMORY;
 
     // free the current buffer
-    sp<SurfaceBuffer>& currentBuffer(mBuffers[index]);
+    sp<GraphicBuffer>& currentBuffer(mBuffers[index]);
     if (currentBuffer != 0) {
         getBufferMapper().unregisterBuffer(currentBuffer->handle);
         currentBuffer.clear();
     }
 
-    sp<SurfaceBuffer> buffer = s->requestBuffer(index, usage);
+    sp<GraphicBuffer> buffer = s->requestBuffer(index, usage);
     LOGE_IF(buffer==0,
             "ISurface::getBuffer(%d, %08x) returned NULL",
             index, usage);
diff --git a/libs/ui/SurfaceBuffer.cpp b/libs/ui/SurfaceBuffer.cpp
deleted file mode 100644
index 0510bc1..0000000
--- a/libs/ui/SurfaceBuffer.cpp
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "SurfaceBuffer"
-
-#include <stdint.h>
-#include <errno.h>
-#include <sys/types.h>
-
-#include <utils/Errors.h>
-#include <utils/Log.h>
-#include <binder/Parcel.h>
-
-#include <ui/BufferMapper.h>
-#include <ui/Rect.h>
-#include <private/ui/SurfaceBuffer.h>
-
-namespace android {
-
-// ============================================================================
-//  SurfaceBuffer
-// ============================================================================
-
-SurfaceBuffer::SurfaceBuffer() 
-    : BASE(), mOwner(false), mBufferMapper(BufferMapper::get()), mIndex(-1)
-{
-    width  = 
-    height = 
-    stride = 
-    format = 
-    usage  = 0;
-    handle = NULL;
-}
-
-SurfaceBuffer::SurfaceBuffer(const Parcel& data) 
-    : BASE(), mOwner(true), mBufferMapper(BufferMapper::get())
-{
-    // we own the handle in this case
-    width  = data.readInt32();
-    if (width < 0) {
-        width = height = stride = format = usage = 0;
-        handle = 0;
-    } else {
-        height = data.readInt32();
-        stride = data.readInt32();
-        format = data.readInt32();
-        usage  = data.readInt32();
-        handle = data.readNativeHandle();
-    }
-}
-
-SurfaceBuffer::~SurfaceBuffer()
-{
-    if (handle && mOwner) {
-        native_handle_close(handle);
-        native_handle_delete(const_cast<native_handle*>(handle));
-    }
-}
-
-status_t SurfaceBuffer::lock(uint32_t usage, void** vaddr)
-{
-    const Rect lockBounds(width, height);
-    status_t res = lock(usage, lockBounds, vaddr);
-    return res;
-}
-
-status_t SurfaceBuffer::lock(uint32_t usage, const Rect& rect, void** vaddr)
-{
-    if (rect.left < 0 || rect.right  > this->width || 
-        rect.top  < 0 || rect.bottom > this->height) {
-        LOGE("locking pixels (%d,%d,%d,%d) outside of buffer (w=%d, h=%d)",
-                rect.left, rect.top, rect.right, rect.bottom, 
-                this->width, this->height);
-        return BAD_VALUE;
-    }
-    status_t res = getBufferMapper().lock(handle, usage, rect, vaddr);
-    return res;
-}
-
-status_t SurfaceBuffer::unlock()
-{
-    status_t res = getBufferMapper().unlock(handle);
-    return res;
-}
-
-status_t SurfaceBuffer::writeToParcel(Parcel* reply, 
-        android_native_buffer_t const* buffer)
-{
-    if (buffer == NULL)
-        return BAD_VALUE;
-
-    if (buffer->width < 0 || buffer->height < 0)
-        return BAD_VALUE;
-
-    status_t err = NO_ERROR;
-    if (buffer->handle == NULL) {
-        // this buffer doesn't have a handle
-        reply->writeInt32(NO_MEMORY);
-    } else {
-        reply->writeInt32(buffer->width);
-        reply->writeInt32(buffer->height);
-        reply->writeInt32(buffer->stride);
-        reply->writeInt32(buffer->format);
-        reply->writeInt32(buffer->usage);
-        err = reply->writeNativeHandle(buffer->handle);
-    }
-    return err;
-}
-
-
-void SurfaceBuffer::setIndex(int index) {
-    mIndex = index;
-}
-
-int SurfaceBuffer::getIndex() const {
-    return mIndex;
-}
-
-
-}; // namespace android
-
diff --git a/media/java/android/media/MediaPlayer.java b/media/java/android/media/MediaPlayer.java
index 472542d..a676782 100644
--- a/media/java/android/media/MediaPlayer.java
+++ b/media/java/android/media/MediaPlayer.java
@@ -522,6 +522,7 @@
      *
      * @return A parcel suitable to hold a request for the native
      * player.
+     * {@hide}
      */
     public Parcel newRequest() {
         Parcel parcel = Parcel.obtain();
@@ -543,6 +544,7 @@
      * native player.
      *
      * @return The status code see utils/Errors.h
+     * {@hide}
      */
     public int invoke(Parcel request, Parcel reply) {
         int retcode = native_invoke(request, reply);
diff --git a/media/java/android/media/ToneGenerator.java b/media/java/android/media/ToneGenerator.java
index d4ae80f..d232265 100644
--- a/media/java/android/media/ToneGenerator.java
+++ b/media/java/android/media/ToneGenerator.java
@@ -852,10 +852,10 @@
 
     /**
      * This method starts the playback of a tone of the specified type for the specified duration.
-     * @param toneType   The type of tone generated @see #startTone(int).
+     * @param toneType   The type of tone generated @see {@link #startTone(int)}.
      * @param durationMs  The tone duration in milliseconds. If the tone is limited in time by definition,
      * the actual duration will be the minimum of durationMs and the defined tone duration. Setting durationMs to -1,
-     * is equivalent to calling #startTone(int).
+     * is equivalent to calling {@link #startTone(int)}.
     */
     public native boolean startTone(int toneType, int durationMs);
 
diff --git a/media/libmedia/ToneGenerator.cpp b/media/libmedia/ToneGenerator.cpp
index d36bec9..3729eb3 100644
--- a/media/libmedia/ToneGenerator.cpp
+++ b/media/libmedia/ToneGenerator.cpp
@@ -879,6 +879,7 @@
 ////////////////////////////////////////////////////////////////////////////////
 bool ToneGenerator::startTone(int toneType, int durationMs) {
     bool lResult = false;
+    status_t lStatus;
 
     if ((toneType < 0) || (toneType >= NUM_TONES))
         return lResult;
@@ -898,15 +899,16 @@
     toneType = getToneForRegion(toneType);
     mpNewToneDesc = &sToneDescriptors[toneType];
 
-    if (durationMs == -1) {
-        mMaxSmp = TONEGEN_INF;
-    } else {
-        if (durationMs > (int)(TONEGEN_INF / mSamplingRate)) {
-            mMaxSmp = (durationMs / 1000) * mSamplingRate;
-        } else {
-            mMaxSmp = (durationMs * mSamplingRate) / 1000;
+    mDurationMs = durationMs;
+
+    if (mState == TONE_STOPPED) {
+        LOGV("Start waiting for previous tone to stop");
+        lStatus = mWaitCbkCond.waitRelative(mLock, seconds(1));
+        if (lStatus != NO_ERROR) {
+            LOGE("--- start wait for stop timed out, status %d", lStatus);
+            mState = TONE_IDLE;
+            return lResult;
         }
-        LOGV("startTone, duration limited to %d ms", durationMs);
     }
 
     if (mState == TONE_INIT) {
@@ -919,7 +921,7 @@
             mLock.lock();
             if (mState == TONE_STARTING) {
                 LOGV("Wait for start callback");
-                status_t lStatus = mWaitCbkCond.waitRelative(mLock, seconds(1));
+                lStatus = mWaitCbkCond.waitRelative(mLock, seconds(1));
                 if (lStatus != NO_ERROR) {
                     LOGE("--- Immediate start timed out, status %d", lStatus);
                     mState = TONE_IDLE;
@@ -931,9 +933,8 @@
         }
     } else {
         LOGV("Delayed start\n");
-
         mState = TONE_RESTARTING;
-        status_t lStatus = mWaitCbkCond.waitRelative(mLock, seconds(1));
+        lStatus = mWaitCbkCond.waitRelative(mLock, seconds(1));
         if (lStatus == NO_ERROR) {
             if (mState != TONE_IDLE) {
                 lResult = true;
@@ -1316,6 +1317,17 @@
 
     mpToneDesc = mpNewToneDesc;
 
+    if (mDurationMs == -1) {
+        mMaxSmp = TONEGEN_INF;
+    } else {
+        if (mDurationMs > (int)(TONEGEN_INF / mSamplingRate)) {
+            mMaxSmp = (mDurationMs / 1000) * mSamplingRate;
+        } else {
+            mMaxSmp = (mDurationMs * mSamplingRate) / 1000;
+        }
+        LOGV("prepareWave, duration limited to %d ms", mDurationMs);
+    }
+
     while (mpToneDesc->segments[segmentIdx].duration) {
         // Get total number of sine waves: needed to adapt sine wave gain.
         unsigned int lNumWaves = numWaves(segmentIdx);
diff --git a/opengl/tests/copybits/Android.mk b/opengl/tests/copybits/Android.mk
deleted file mode 100644
index d5ded42..0000000
--- a/opengl/tests/copybits/Android.mk
+++ /dev/null
@@ -1,18 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES:= \
-	copybits.cpp
-
-LOCAL_SHARED_LIBRARIES := \
-	libcutils \
-    libEGL \
-    libGLESv1_CM \
-    libui
-
-LOCAL_MODULE:= test-opengl-copybits
-
-LOCAL_MODULE_TAGS := tests
-
-include $(BUILD_EXECUTABLE)
-
diff --git a/opengl/tests/copybits/copybits.cpp b/opengl/tests/copybits/copybits.cpp
deleted file mode 100644
index 11dfb6e..0000000
--- a/opengl/tests/copybits/copybits.cpp
+++ /dev/null
@@ -1,726 +0,0 @@
-// Test software OpenGL hardware accelleration using copybits.
-
-#define LOG_TAG "copybits_test"
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <math.h>
-#include <sys/types.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/time.h>
-
-#include <ui/PixelFormat.h>
-
-#include <cutils/log.h>
-#include <cutils/native_handle.h>
-
-#include <utils/Atomic.h>
-
-#include <private/ui/SurfaceBuffer.h>
-#include <pixelflinger/pixelflinger.h>
-
-#include <hardware/gralloc.h>
-#include <hardware/hardware.h>
-
-#include <ui/FramebufferNativeWindow.h>
-#include <ui/EGLUtils.h>
-
-#define EGL_EGLEXT_PROTOTYPES
-#define GL_GLEXT_PROTOTYPES
-
-#include <EGL/egl.h>
-#include <EGL/eglext.h>
-
-#include <GLES/gl.h>
-#include <GLES/glext.h>
-
-using namespace android;
-
-EGLDisplay eglDisplay;
-EGLSurface eglSurface;
-EGLContext eglContext;
-GLuint texture;
-
-hw_module_t const* gralloc_module;
-alloc_device_t  *sAllocDev;
-
-#define FIXED_ONE 0x10000 /* 1.0 in 16.16 fixed point. */
-
-int init_gl_surface();
-void free_gl_surface();
-void init_scene();
-
-int create_physical_texture();
-int readTimer();
-
-// ===========================================================================
-// Buffer an implementation of android_native_buffer_t
-// ===========================================================================
-
-class NativeBuffer;
-
-class Buffer : public android::SurfaceBuffer
-{
-public:
-    // creates w * h buffer
-    Buffer(uint32_t w, uint32_t h, PixelFormat format, uint32_t usage);
-
-    // return status
-    status_t initCheck() const;
-
-    uint32_t getWidth() const           { return width; }
-    uint32_t getHeight() const          { return height; }
-    uint32_t getStride() const          { return stride; }
-    uint32_t getUsage() const           { return usage; }
-    PixelFormat getPixelFormat() const  { return format; }
-    
-    
-    android_native_buffer_t* getNativeBuffer() const;
-
-    void setPixel(int x, int y, int r, int g, int b, int a);
-
-    status_t lock(GGLSurface* surface, uint32_t usage);
-    void lock() {
-        GGLSurface s;
-        lock(&s, GRALLOC_USAGE_SW_WRITE_OFTEN);
-        mData = (void*)s.data;
-    }
-
-private:
-    friend class LightRefBase<Buffer>;
-    Buffer(const Buffer& rhs);
-    virtual ~Buffer();
-    Buffer& operator = (const Buffer& rhs);
-    const Buffer& operator = (const Buffer& rhs) const;
-
-    status_t initSize(uint32_t w, uint32_t h);
-
-    ssize_t                 mInitCheck;
-    void*                   mData;
-};
-
-Buffer::Buffer(uint32_t w, uint32_t h, PixelFormat format, uint32_t usage)
-    : SurfaceBuffer(), mInitCheck(NO_INIT)
-{
-    this->usage = usage;
-    this->format = format;
-    if (w>0 && h>0) {
-        mInitCheck = initSize(w, h);
-    }
-}
-
-Buffer::~Buffer()
-{
-    if (handle) {
-        sAllocDev->free(sAllocDev, handle);
-    }
-}
-
-status_t Buffer::initCheck() const {
-    return mInitCheck;
-}
-
-android_native_buffer_t* Buffer::getNativeBuffer() const
-{
-    return static_cast<android_native_buffer_t*>(const_cast<Buffer*>(this));
-}
-
-status_t Buffer::initSize(uint32_t w, uint32_t h)
-{
-    status_t err = NO_ERROR;
-
-    err = sAllocDev->alloc(sAllocDev, w, h, format, usage, &handle, &stride);
-    
-    if (err == NO_ERROR) {
-        if (err == NO_ERROR) {
-            width  = w;
-            height = h;
-        }
-    }
-
-    return err;
-}
-
-status_t Buffer::lock(GGLSurface* sur, uint32_t usage) 
-{
-    void* vaddr;
-    status_t res = SurfaceBuffer::lock(usage, &vaddr);
-    if (res == NO_ERROR && sur) {
-        sur->version = sizeof(GGLSurface);
-        sur->width = width;
-        sur->height = height;
-        sur->stride = stride;
-        sur->format = format;
-        sur->data = static_cast<GGLubyte*>(vaddr);
-    }
-    return res;
-}
-
-
-void Buffer::setPixel(int x, int y, int r, int g, int b, int a) {
-    if (x < 0 || (unsigned int) x >= width
-            || y < 0 || (unsigned int) y >= height) {
-        // clipped
-        return;
-    }
-    int index = stride * y + x;
-    switch (format) {
-    case HAL_PIXEL_FORMAT_RGB_565: {
-            unsigned short val = (unsigned short) (
-                    ((0x1f & (r >> 3)) << 11)
-                    | ((0x3f & (g >> 2)) << 5)
-                    | (0x1f & (b >> 3)));
-            ((unsigned short*) mData)[index]= val;
-        }
-        break;
-    case HAL_PIXEL_FORMAT_RGBA_8888: { // ABGR
-        unsigned int val = (unsigned int)
-            (((a & 0xff) << 24)
-                    | ((b & 0xff) << 16)
-                    | ((g & 0xff) << 8)
-                    | (r & 0xff));
-            ((unsigned int*) mData)[index] = val;
-        }
-        break;
-    default:
-        // Unsupported pixel format
-        break;
-    }
-}
-
-
-static void gluLookAt(float eyeX, float eyeY, float eyeZ,
-        float centerX, float centerY, float centerZ, float upX, float upY,
-        float upZ)
-{
-    // See the OpenGL GLUT documentation for gluLookAt for a description
-    // of the algorithm. We implement it in a straightforward way:
-
-    float fx = centerX - eyeX;
-    float fy = centerY - eyeY;
-    float fz = centerZ - eyeZ;
-
-    // Normalize f
-    float rlf = 1.0f / sqrtf(fx*fx + fy*fy + fz*fz);
-    fx *= rlf;
-    fy *= rlf;
-    fz *= rlf;
-
-    // Normalize up
-    float rlup = 1.0f / sqrtf(upX*upX + upY*upY + upZ*upZ);
-    upX *= rlup;
-    upY *= rlup;
-    upZ *= rlup;
-
-    // compute s = f x up (x means "cross product")
-
-    float sx = fy * upZ - fz * upY;
-    float sy = fz * upX - fx * upZ;
-    float sz = fx * upY - fy * upX;
-
-    // compute u = s x f
-    float ux = sy * fz - sz * fy;
-    float uy = sz * fx - sx * fz;
-    float uz = sx * fy - sy * fx;
-
-    float m[16] ;
-    m[0] = sx;
-    m[1] = ux;
-    m[2] = -fx;
-    m[3] = 0.0f;
-
-    m[4] = sy;
-    m[5] = uy;
-    m[6] = -fy;
-    m[7] = 0.0f;
-
-    m[8] = sz;
-    m[9] = uz;
-    m[10] = -fz;
-    m[11] = 0.0f;
-
-    m[12] = 0.0f;
-    m[13] = 0.0f;
-    m[14] = 0.0f;
-    m[15] = 1.0f;
-
-    glMultMatrixf(m);
-    glTranslatef(-eyeX, -eyeY, -eyeZ);
-}
-
-int init_gralloc() {
-    int err = hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &gralloc_module);
-    LOGE_IF(err, "FATAL: can't find the %s module", GRALLOC_HARDWARE_MODULE_ID);
-
-    if (err == 0) {
-        gralloc_open(gralloc_module, &sAllocDev);
-    }
-    return err;
-}
-
-int init_gl_surface(void)
-{
-    EGLint numConfigs = 1;
-    EGLConfig myConfig = {0};
-    EGLint attrib[] =
-    {
-            EGL_DEPTH_SIZE,     16,
-            EGL_NONE
-    };
-
-    EGLNativeWindowType window = android_createDisplaySurface();
-
-    printf("init_gl_surface\n");
-    if ( (eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY)) == EGL_NO_DISPLAY )
-    {
-        printf("eglGetDisplay failed\n");
-        return 0;
-    }
-
-    if ( eglInitialize(eglDisplay, NULL, NULL) != EGL_TRUE )
-    {
-        printf("eglInitialize failed\n");
-        return 0;
-    }
-
-    if ( EGLUtils::selectConfigForNativeWindow(eglDisplay, attrib, window, &myConfig) != 0)
-    {
-        printf("EGLUtils::selectConfigForNativeWindow failed\n");
-        return 0;
-    }
-        
-
-    if ( (eglSurface = eglCreateWindowSurface(eglDisplay, myConfig,
-            window, 0)) == EGL_NO_SURFACE )
-    {
-        printf("eglCreateWindowSurface failed\n");
-        return 0;
-    }
-
-    if ( (eglContext = eglCreateContext(eglDisplay, myConfig, 0, 0)) == EGL_NO_CONTEXT )
-    {
-        printf("eglCreateContext failed\n");
-        return 0;
-    }
-
-    if ( eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext) != EGL_TRUE )
-    {
-        printf("eglMakeCurrent failed\n");
-        return 0;
-    }
-
-#if EGL_ANDROID_swap_rectangle
-    eglSetSwapRectangleANDROID(eglDisplay, eglSurface, 0, 0, 320, 480);
-#endif
-    
-    return 1;
-}
-
-void free_gl_surface(void)
-{
-    if (eglDisplay != EGL_NO_DISPLAY)
-    {
-        eglMakeCurrent( eglDisplay, EGL_NO_SURFACE,
-                EGL_NO_SURFACE, EGL_NO_CONTEXT );
-        eglDestroyContext( eglDisplay, eglContext );
-        eglDestroySurface( eglDisplay, eglSurface );
-        eglTerminate( eglDisplay );
-        eglDisplay = EGL_NO_DISPLAY;
-    }
-}
-
-void init_scene(void)
-{
-    glDisable(GL_DITHER);
-    glEnable(GL_CULL_FACE);
-    float ratio = 320.0f /  480.0f;
-    glViewport(0, 0, 320, 480);
-
-    glMatrixMode(GL_PROJECTION);
-    glLoadIdentity();
-    glFrustumf(-ratio, ratio, -1, 1, 1, 10);
-
-    glMatrixMode(GL_MODELVIEW);
-
-    glLoadIdentity();
-    gluLookAt(
-            0, 0, 3,  // eye
-            0, 0, 0,  // center
-            0, 1, 0); // up
-
-    glEnable(GL_TEXTURE_2D);
-}
-
-// #define USE_ALPHA_COLOR
-
-#define USE_GL_REPLACE
-//#define USE_GL_MODULATE
-
-// #define USE_BLEND
-
-#define USE_565
-// #define USE_8888
-
-// #define USE_NEAREST
-#define USE_LINEAR
-
-#define USE_SCALE
-
-void setSmoothGradient(Buffer* bufferObject) {
-    int pixels = bufferObject->getHeight() * bufferObject->getWidth();
-    int step = 0;
-    for (unsigned int y = 0; y < bufferObject->getHeight(); y++) {
-        for(unsigned int x = 0; x < bufferObject->getWidth() ; x++) {
-            int grey = step * 255 / pixels;
-            bufferObject->setPixel(x, y, grey, grey, grey, 255);
-            ++step;
-        }
-    }
-}
-
-void setSmoothAlphaGradient(Buffer* bufferObject) {
-    int pixels = bufferObject->getHeight() * bufferObject->getWidth();
-    int step = 0;
-    for (unsigned int y = 0; y < bufferObject->getHeight(); y++) {
-        for(unsigned int x = 0; x < bufferObject->getWidth() ; x++) {
-            int grey = step * 255 / pixels;
-            bufferObject->setPixel(x, y, 255, 255, 255, grey);
-            ++step;
-        }
-    }
-}
-
-void setOrientedCheckerboard(Buffer* bufferObject) {
-    bufferObject->setPixel(0, 0, 0, 0, 0, 255);
-    for(unsigned int x = 1; x < bufferObject->getWidth() ; x++) {
-        bufferObject->setPixel(x, 0, 0, 255, 0, 255);
-    }
-    for (unsigned int y = 1; y < bufferObject->getHeight(); y++) {
-        for(unsigned int x = 0; x < bufferObject->getWidth() ; x++) {
-            if ((x ^ y ) & 1) {
-                bufferObject->setPixel(x, y, 255, 255, 255, 255);
-            } else {
-                bufferObject->setPixel(x, y, 255, 0, 0, 255);
-            }
-        }
-    }
-}
-
-int create_physical_texture(unsigned int w, unsigned int h)
-{
-
-#ifdef USE_565
-    PixelFormat format = HAL_PIXEL_FORMAT_RGB_565;
-#else
-    PixelFormat format = HAL_PIXEL_FORMAT_RGBA_8888;
-#endif
-    int usage = GRALLOC_USAGE_SW_READ_OFTEN |
-        GRALLOC_USAGE_SW_WRITE_OFTEN |
-        GRALLOC_USAGE_HW_TEXTURE |
-        GRALLOC_USAGE_HW_2D; /* This is the key to allocating the texture in pmem. */
-    int32_t stride;
-    buffer_handle_t handle;
-
-    // Allocate the hardware buffer
-    Buffer* bufferObject = new Buffer(w, h, format, usage);
-
-    android_native_buffer_t* buffer = bufferObject->getNativeBuffer();
-
-    buffer->common.incRef(&buffer->common);
-
-    // create the new EGLImageKHR
-    EGLint attrs[] = { EGL_IMAGE_PRESERVED_KHR, EGL_NONE };
-    EGLDisplay dpy = eglGetCurrentDisplay();
-    EGLImageKHR image = eglCreateImageKHR(dpy, EGL_NO_CONTEXT, EGL_NATIVE_BUFFER_ANDROID,
-            (EGLClientBuffer)buffer, attrs);
-    if (image == EGL_NO_IMAGE_KHR) {
-        printf("Could not create an image %d\n", eglGetError());
-        return -1;
-    }
-
-    bufferObject->lock();
-    setOrientedCheckerboard(bufferObject);
-    // setSmoothGradient(bufferObject);
-    // setSmoothAlphaGradient(bufferObject);
-    bufferObject->unlock();
-
-    glGenTextures(1, &texture);
-    glBindTexture(GL_TEXTURE_2D, texture);
-    glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, image);
-#ifdef USE_LINEAR
-    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
-    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-#elif defined(USE_NEAREST)
-    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
-    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-#endif
-
-#ifdef USE_GL_REPLACE
-    glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
-#elif defined(USE_GL_MODULATE)
-    glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
-#endif
-
-#ifdef USE_ALPHA_COLOR
-    glColor4f(1.0f, 1.0f, 1.0f, 0.4f);
-#else
-    glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
-#endif
-
-#ifdef USE_BLEND
-    glEnable(GL_BLEND);
-    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
-#endif
-    return 0;
-}
-
-static const int SCALE_COUNT = 12;
-
-int scale(int base, int factor) {
-    static const float kTable[SCALE_COUNT] = {
-            0.24f, 0.25f, 0.5f, 0.75f, 1.0f,
-            1.5f, 2.0f, 2.5f, 3.0f, 3.5f, 4.0f, 5.0f
-    };
-    return base * kTable[factor];
-}
-
-class Timer {
-    struct timeval  first;
-    double elapsedSeconds;
-
-public:
-    Timer() {}
-    void start() {
-        gettimeofday(&first, NULL);
-    }
-
-    void stop() {
-        struct timeval  second,
-                        elapsed;
-        gettimeofday(&second, NULL);
-
-        if (first.tv_usec > second.tv_usec) {
-           second.tv_usec += 1000000;
-           second.tv_sec--;
-        }
-
-        elapsedSeconds = (second.tv_sec  - first.tv_sec) +
-            (second.tv_usec - first.tv_usec) / 1000000.0;
-    }
-
-    double getElapsedSeconds() {
-        return elapsedSeconds;
-    }
-
-    double getElapsedMs() {
-        return elapsedSeconds* 1000.0f;
-    }
-};
-
-int testTime()
-{
-    static const int WIDTH = 320;
-    static const int HEIGHT = 480;
-    static const int SCALE = 8;
-
-    if (create_physical_texture(WIDTH, HEIGHT) != 0) {
-        return -1;
-    }
-    // Need to do a dummy eglSwapBuffers first. Don't know why.
-    glClearColor(0.4, 1.0, 0.4, 0.4);
-    glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
-    eglSwapBuffers(eglDisplay, eglSurface);
-
-    glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
-
-#if defined(USE_SCALE)
-    static const int scaleOffset = 0;
-#else
-    static const int scaleOffset = 1;
-#endif
-    printf("ms\n");
-    for(int j = 0; j < SCALE; j++) {
-        int w = WIDTH >> (j + scaleOffset);
-        int h = HEIGHT >> j;
-        int cropRect[4] = {0,h,w,-h}; // Left bottom width height. Width and Height can be neg to flip.
-        glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, cropRect);
-        Timer timer;
-        timer.start();
-
-        int copyCount = 1000;
-        for (int i = 0; i < copyCount; i++) {
-            glDrawTexiOES(0, 0, 0, w, h);
-        }
-
-        timer.stop();
-        printf("%g\n", timer.getElapsedMs() / copyCount);
-    }
-
-    eglSwapBuffers(eglDisplay, eglSurface);
-    return 0;
-}
-
-int testStretch()
-{
-    static const int WIDTH = 8;
-    static const int HEIGHT = 8;
-
-    if (create_physical_texture(WIDTH, HEIGHT) != 0) {
-        return -1;
-    }
-    // Need to do a dummy eglSwapBuffers first. Don't know why.
-    glClearColor(0.4, 1.0, 0.4, 1.0);
-    glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
-    eglSwapBuffers(eglDisplay, eglSurface);
-    
-    int cropRect[4] = {0,HEIGHT,WIDTH,-HEIGHT}; // Left bottom width height. Width and Height can be neg to flip.
-    glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, cropRect);
-
-    for(int frame = 0; frame < 2; frame++) {
-        glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
-        int baseX = 10;
-        for (int x = 0; x < SCALE_COUNT; x++) {
-            int baseY = 10;
-            int width = scale(WIDTH, x);
-            for (int y = 0; y < SCALE_COUNT; y++) {
-                int height = scale(HEIGHT, y);
-                glDrawTexxOES(baseX << 16, baseY << 16, 0, width << 16, height << 16);
-                baseY += height + 10;
-            }
-            baseX += width + 10;
-        }
-
-        eglSwapBuffers(eglDisplay, eglSurface);
-        LOGD("wait 1s");
-        usleep(1000000);
-    }
-    return 0;
-}
-
-int testRot90()
-{
-    static const int WIDTH = 8;
-    static const int HEIGHT = 8;
-
-    if (create_physical_texture(WIDTH, HEIGHT) != 0) {
-        return -1;
-    }
-
-    glMatrixMode(GL_PROJECTION);
-    glLoadIdentity();
-    glOrthof(0, 320, 480, 0, 0, 1);
-
-    glMatrixMode(GL_MODELVIEW);
-
-    glLoadIdentity();
-
-    // Need to do a dummy eglSwapBuffers first. Don't know why.
-    glClearColor(0.4, 0.4, 0.4, 0.4);
-    glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
-    eglSwapBuffers(eglDisplay, eglSurface);
-
-    glEnable(GL_TEXTURE_2D);
-    glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
-    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
-    glColor4x(0x10000, 0x10000, 0x10000, 0x10000);
-    glDisable(GL_BLEND);
-    glShadeModel(GL_FLAT);
-    glDisable(GL_DITHER);
-    glDisable(GL_CULL_FACE);
-
-    for(int frame = 0; frame < 2; frame++) {
-        LOGD("frame = %d", frame);
-        glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
-        int baseX = 10;
-        for (int x = 0; x < SCALE_COUNT; x++) {
-            int baseY = 10;
-            int width = scale(WIDTH, x);
-            for (int y = 0; y < SCALE_COUNT; y++) {
-                int height = scale(HEIGHT, y);
-
-                // Code copied from SurfaceFlinger LayerBase.cpp
-
-                const GLfixed texCoords[4][2] = {
-                        { 0,        0 },
-                        { 0,        0x10000 },
-                        { 0x10000,  0x10000 },
-                        { 0x10000,  0 }
-                };
-
-                GLfixed fx = baseX << 16;
-                GLfixed fy = baseY << 16;
-                GLfixed fw = width << 16;
-                GLfixed fh = height << 16;
-
-                /*
-                 * Vertex pattern:
-                 *    (2)--(3)
-                 *     |\   |
-                 *     | \  |
-                 *     |  \ |
-                 *     |   \|
-                 *    (1)--(0)
-                 *
-                 */
-
-                const GLfixed vertices[4][2] = {
-                        {fx + fw, fy},
-                        {fx,      fy},
-                        {fx,      fy + fh},
-                        {fx + fw, fy + fh}
-                };
-
-                static const bool rotate90 = true;
-
-                glMatrixMode(GL_TEXTURE);
-                glLoadIdentity();
-
-                glEnableClientState(GL_VERTEX_ARRAY);
-                glEnableClientState(GL_TEXTURE_COORD_ARRAY);
-                glVertexPointer(2, GL_FIXED, 0, vertices);
-                glTexCoordPointer(2, GL_FIXED, 0, texCoords);
-
-                LOGD("testRot90 %d, %d %d, %d", baseX, baseY, width, height);
-                glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
-
-                baseY += height + 10;
-            }
-            baseX += width + 10;
-        }
-
-        eglSwapBuffers(eglDisplay, eglSurface);
-    }
-    return 0;
-}
-
-int main(int argc, char **argv)
-{
-
-    int q;
-    int start, end;
-
-    if (init_gralloc()) {
-        printf("gralloc initialization failed - exiting\n");
-        return 0;
-    }
-
-    printf("Initializing EGL...\n");
-
-    if(!init_gl_surface())
-    {
-        printf("GL initialisation failed - exiting\n");
-        return 0;
-    }
-
-    init_scene();
-
-    printf("Start test...\n");
-    // testTime();
-     testStretch();
-    //testRot90();
-    free_gl_surface();
-
-    return 0;
-}
diff --git a/opengl/tests/gralloc/Android.mk b/opengl/tests/gralloc/Android.mk
index a86c8ec..d43c39a 100644
--- a/opengl/tests/gralloc/Android.mk
+++ b/opengl/tests/gralloc/Android.mk
@@ -2,9 +2,7 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES:= \
-    gralloc.cpp \
-    Buffer.cpp \
-    BufferAllocator.cpp
+    gralloc.cpp
 
 LOCAL_SHARED_LIBRARIES := \
     libcutils \
diff --git a/opengl/tests/gralloc/Buffer.cpp b/opengl/tests/gralloc/Buffer.cpp
deleted file mode 100644
index 3920ff0..0000000
--- a/opengl/tests/gralloc/Buffer.cpp
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdlib.h>
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <utils/Errors.h>
-#include <utils/Log.h>
-
-#include <ui/PixelFormat.h>
-#include <pixelflinger/pixelflinger.h>
-
-#include "Buffer.h"
-#include "BufferAllocator.h"
-
-
-namespace android {
-
-// ===========================================================================
-// Buffer and implementation of android_native_buffer_t
-// ===========================================================================
-
-Buffer::Buffer()
-    : SurfaceBuffer(), mInitCheck(NO_ERROR),  mVStride(0)
-{
-}
-
-Buffer::Buffer(uint32_t w, uint32_t h, PixelFormat format,
-        uint32_t reqUsage, uint32_t flags)
-    : SurfaceBuffer(), mInitCheck(NO_INIT), mVStride(0)
-{
-    mInitCheck = initSize(w, h, format, reqUsage, flags);
-}
-
-Buffer::~Buffer()
-{
-    if (handle) {
-        BufferAllocator& allocator(BufferAllocator::get());
-        allocator.free(handle);
-    }
-}
-
-status_t Buffer::initCheck() const {
-    return mInitCheck;
-}
-
-android_native_buffer_t* Buffer::getNativeBuffer() const
-{
-    return static_cast<android_native_buffer_t*>(const_cast<Buffer*>(this));
-}
-
-status_t Buffer::reallocate(uint32_t w, uint32_t h, PixelFormat f,
-        uint32_t reqUsage, uint32_t flags)
-{
-    if (handle) {
-        BufferAllocator& allocator(BufferAllocator::get());
-        allocator.free(handle);
-        handle = 0;
-    }
-    return initSize(w, h, f, reqUsage, flags);
-}
-
-status_t Buffer::initSize(uint32_t w, uint32_t h, PixelFormat format,
-        uint32_t reqUsage, uint32_t flags)
-{
-    status_t err = NO_ERROR;
-    BufferAllocator& allocator = BufferAllocator::get();
-    err = allocator.alloc(w, h, format, reqUsage, &handle, &stride);
-    if (err == NO_ERROR) {
-        this->width  = w;
-        this->height = h;
-        this->format = format;
-        mVStride = 0;
-    }
-
-    return err;
-}
-
-status_t Buffer::lock(GGLSurface* sur, uint32_t usage)
-{
-    void* vaddr;
-    status_t res = SurfaceBuffer::lock(usage, &vaddr);
-    if (res == NO_ERROR && sur) {
-        sur->version = sizeof(GGLSurface);
-        sur->width = width;
-        sur->height = height;
-        sur->stride = stride;
-        sur->format = format;
-        sur->vstride = mVStride;
-        sur->data = static_cast<GGLubyte*>(vaddr);
-    }
-    return res;
-}
-
-// ---------------------------------------------------------------------------
-
-}; // namespace android
diff --git a/opengl/tests/gralloc/Buffer.h b/opengl/tests/gralloc/Buffer.h
deleted file mode 100644
index 8a32153..0000000
--- a/opengl/tests/gralloc/Buffer.h
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_LAYER_BITMAP_H
-#define ANDROID_LAYER_BITMAP_H
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <hardware/gralloc.h>
-
-#include <utils/Atomic.h>
-
-#include <private/ui/SurfaceBuffer.h>
-#include <ui/PixelFormat.h>
-#include <ui/Rect.h>
-
-#include <pixelflinger/pixelflinger.h>
-
-struct android_native_buffer_t;
-
-namespace android {
-
-// ===========================================================================
-// Buffer
-// ===========================================================================
-
-class NativeBuffer;
-
-class Buffer : public SurfaceBuffer
-{
-public:
-    enum {
-        DONT_CLEAR  = 0x00000001,
-        SECURE      = 0x00000004
-    };
-
-    Buffer();
-
-    // creates w * h buffer
-    Buffer(uint32_t w, uint32_t h, PixelFormat format,
-            uint32_t reqUsage, uint32_t flags = 0);
-
-    // return status
-    status_t initCheck() const;
-
-    uint32_t getWidth() const           { return width; }
-    uint32_t getHeight() const          { return height; }
-    uint32_t getStride() const          { return stride; }
-    uint32_t getUsage() const           { return usage; }
-    PixelFormat getPixelFormat() const  { return format; }
-    Rect getBounds() const              { return Rect(width, height); }
-
-    status_t lock(GGLSurface* surface, uint32_t usage);
-
-    android_native_buffer_t* getNativeBuffer() const;
-
-    status_t reallocate(uint32_t w, uint32_t h, PixelFormat f,
-            uint32_t reqUsage, uint32_t flags);
-
-private:
-    friend class LightRefBase<Buffer>;
-    Buffer(const Buffer& rhs);
-    virtual ~Buffer();
-    Buffer& operator = (const Buffer& rhs);
-    const Buffer& operator = (const Buffer& rhs) const;
-
-    status_t initSize(uint32_t w, uint32_t h, PixelFormat format,
-            uint32_t reqUsage, uint32_t flags);
-
-    ssize_t     mInitCheck;
-    uint32_t    mVStride;
-};
-
-}; // namespace android
-
-#endif // ANDROID_LAYER_BITMAP_H
diff --git a/opengl/tests/gralloc/BufferAllocator.cpp b/opengl/tests/gralloc/BufferAllocator.cpp
deleted file mode 100644
index caf9bec..0000000
--- a/opengl/tests/gralloc/BufferAllocator.cpp
+++ /dev/null
@@ -1,131 +0,0 @@
-/* 
-**
-** Copyright 2009, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License"); 
-** you may not use this file except in compliance with the License. 
-** You may obtain a copy of the License at 
-**
-**     http://www.apache.org/licenses/LICENSE-2.0 
-**
-** Unless required by applicable law or agreed to in writing, software 
-** distributed under the License is distributed on an "AS IS" BASIS, 
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
-** See the License for the specific language governing permissions and 
-** limitations under the License.
-*/
-
-#include <sys/mman.h>
-#include <cutils/ashmem.h>
-#include <cutils/log.h>
-
-#include <utils/Singleton.h>
-#include <utils/String8.h>
-
-#include "BufferAllocator.h"
-
-
-namespace android {
-// ---------------------------------------------------------------------------
-
-ANDROID_SINGLETON_STATIC_INSTANCE( BufferAllocator )
-
-Mutex BufferAllocator::sLock;
-KeyedVector<buffer_handle_t, BufferAllocator::alloc_rec_t> BufferAllocator::sAllocList;
-
-BufferAllocator::BufferAllocator()
-    : mAllocDev(0)
-{
-    hw_module_t const* module;
-    int err = hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &module);
-    LOGE_IF(err, "FATAL: can't find the %s module", GRALLOC_HARDWARE_MODULE_ID);
-    if (err == 0) {
-        gralloc_open(module, &mAllocDev);
-    }
-}
-
-BufferAllocator::~BufferAllocator()
-{
-    gralloc_close(mAllocDev);
-}
-
-void BufferAllocator::dump(String8& result) const
-{
-    Mutex::Autolock _l(sLock);
-    KeyedVector<buffer_handle_t, alloc_rec_t>& list(sAllocList);
-    size_t total = 0;
-    const size_t SIZE = 512;
-    char buffer[SIZE];
-    snprintf(buffer, SIZE, "Allocated buffers:\n");
-    result.append(buffer);
-    const size_t c = list.size();
-    for (size_t i=0 ; i<c ; i++) {
-        const alloc_rec_t& rec(list.valueAt(i));
-        snprintf(buffer, SIZE, "%10p: %7.2f KiB | %4u x %4u | %2d | 0x%08x\n",
-            list.keyAt(i), rec.size/1024.0f, 
-            rec.w, rec.h, rec.format, rec.usage);
-        result.append(buffer);
-        total += rec.size;
-    }
-    snprintf(buffer, SIZE, "Total allocated: %.2f KB\n", total/1024.0f);
-    result.append(buffer);
-}
-
-static inline uint32_t clamp(uint32_t c) {
-    return c>0 ? c : 1;
-}
-
-status_t BufferAllocator::alloc(uint32_t w, uint32_t h, PixelFormat format,
-        int usage, buffer_handle_t* handle, int32_t* stride)
-{
-    Mutex::Autolock _l(mLock);
-
-    // make sure to not allocate a 0 x 0 buffer
-    w = clamp(w);
-    h = clamp(h);
-
-    // we have a h/w allocator and h/w buffer is requested
-    status_t err = mAllocDev->alloc(mAllocDev,
-            w, h, format, usage, handle, stride);
-
-    LOGW_IF(err, "alloc(%u, %u, %d, %08x, ...) failed %d (%s)",
-            w, h, format, usage, err, strerror(-err));
-    
-    if (err == NO_ERROR) {
-        Mutex::Autolock _l(sLock);
-        KeyedVector<buffer_handle_t, alloc_rec_t>& list(sAllocList);
-        alloc_rec_t rec;
-        rec.w = w;
-        rec.h = h;
-        rec.format = format;
-        rec.usage = usage;
-        rec.vaddr = 0;
-        rec.size = h * stride[0] * bytesPerPixel(format);
-        list.add(*handle, rec);
-    } else {
-        String8 s;
-        dump(s);
-        LOGD("%s", s.string());
-    }
-
-    return err;
-}
-
-status_t BufferAllocator::free(buffer_handle_t handle)
-{
-    Mutex::Autolock _l(mLock);
-
-    status_t err = mAllocDev->free(mAllocDev, handle);
-    LOGW_IF(err, "free(...) failed %d (%s)", err, strerror(-err));
-    
-    if (err == NO_ERROR) {
-        Mutex::Autolock _l(sLock);
-        KeyedVector<buffer_handle_t, alloc_rec_t>& list(sAllocList);
-        list.removeItem(handle);
-    }
-
-    return err;
-}
-
-// ---------------------------------------------------------------------------
-}; // namespace android
diff --git a/opengl/tests/gralloc/BufferAllocator.h b/opengl/tests/gralloc/BufferAllocator.h
deleted file mode 100644
index a279ded..0000000
--- a/opengl/tests/gralloc/BufferAllocator.h
+++ /dev/null
@@ -1,96 +0,0 @@
-/* 
-**
-** Copyright 2009, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License"); 
-** you may not use this file except in compliance with the License. 
-** You may obtain a copy of the License at 
-**
-**     http://www.apache.org/licenses/LICENSE-2.0 
-**
-** Unless required by applicable law or agreed to in writing, software 
-** distributed under the License is distributed on an "AS IS" BASIS, 
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
-** See the License for the specific language governing permissions and 
-** limitations under the License.
-*/
-
-#ifndef ANDROID_BUFFER_ALLOCATOR_H
-#define ANDROID_BUFFER_ALLOCATOR_H
-
-#include <stdint.h>
-
-#include <cutils/native_handle.h>
-
-#include <utils/Errors.h>
-#include <utils/KeyedVector.h>
-#include <utils/threads.h>
-#include <utils/Singleton.h>
-
-#include <ui/PixelFormat.h>
-
-#include <hardware/gralloc.h>
-
-
-namespace android {
-// ---------------------------------------------------------------------------
-
-class String8;
-
-class BufferAllocator : public Singleton<BufferAllocator>
-{
-public:
-    enum {
-        USAGE_SW_READ_NEVER     = GRALLOC_USAGE_SW_READ_NEVER,
-        USAGE_SW_READ_RARELY    = GRALLOC_USAGE_SW_READ_RARELY,
-        USAGE_SW_READ_OFTEN     = GRALLOC_USAGE_SW_READ_OFTEN,
-        USAGE_SW_READ_MASK      = GRALLOC_USAGE_SW_READ_MASK,
-        
-        USAGE_SW_WRITE_NEVER    = GRALLOC_USAGE_SW_WRITE_NEVER,
-        USAGE_SW_WRITE_RARELY   = GRALLOC_USAGE_SW_WRITE_RARELY,
-        USAGE_SW_WRITE_OFTEN    = GRALLOC_USAGE_SW_WRITE_OFTEN,
-        USAGE_SW_WRITE_MASK     = GRALLOC_USAGE_SW_WRITE_MASK,
-        
-        USAGE_SOFTWARE_MASK     = USAGE_SW_READ_MASK|USAGE_SW_WRITE_MASK,
-        
-        USAGE_HW_TEXTURE        = GRALLOC_USAGE_HW_TEXTURE,
-        USAGE_HW_RENDER         = GRALLOC_USAGE_HW_RENDER,
-        USAGE_HW_2D             = GRALLOC_USAGE_HW_2D,
-        USAGE_HW_MASK           = GRALLOC_USAGE_HW_MASK
-    };
-
-    static inline BufferAllocator& get() { return getInstance(); }
-    
-
-    status_t alloc(uint32_t w, uint32_t h, PixelFormat format, int usage,
-            buffer_handle_t* handle, int32_t* stride);
-
-    status_t free(buffer_handle_t handle);
-
-    void dump(String8& res) const;
-
-private:
-    struct alloc_rec_t {
-        uint32_t w;
-        uint32_t h;
-        PixelFormat format;
-        uint32_t usage;
-        void* vaddr;
-        size_t size;
-    };
-    
-    static Mutex sLock;
-    static KeyedVector<buffer_handle_t, alloc_rec_t> sAllocList;
-    
-    friend class Singleton<BufferAllocator>;
-    BufferAllocator();
-    ~BufferAllocator();
-    
-    mutable Mutex mLock;
-    alloc_device_t  *mAllocDev;
-};
-
-// ---------------------------------------------------------------------------
-}; // namespace android
-
-#endif // ANDROID_BUFFER_ALLOCATOR_H
diff --git a/opengl/tests/gralloc/gralloc.cpp b/opengl/tests/gralloc/gralloc.cpp
index d989bb2..8987040 100644
--- a/opengl/tests/gralloc/gralloc.cpp
+++ b/opengl/tests/gralloc/gralloc.cpp
@@ -22,8 +22,8 @@
 #include <utils/StopWatch.h>
 #include <utils/Log.h>
 
-#include "Buffer.h"
-#include <ui/BufferMapper.h>
+#include <ui/GraphicBuffer.h>
+#include <ui/GraphicBufferMapper.h>
 
 using namespace android;
 
@@ -46,7 +46,7 @@
     memset(temp2, 0, size);
 
 
-    sp<Buffer> buffer = new Buffer(128, 256, HAL_PIXEL_FORMAT_RGBA_8888,
+    sp<GraphicBuffer> buffer = new GraphicBuffer(128, 256, HAL_PIXEL_FORMAT_RGBA_8888,
             GRALLOC_USAGE_SW_READ_OFTEN |
             GRALLOC_USAGE_SW_WRITE_OFTEN);
 
@@ -57,7 +57,7 @@
     }
 
     void* vaddr;
-    buffer->SurfaceBuffer::lock(
+    buffer->lock(
             GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN,
             &vaddr);
 
diff --git a/services/java/com/android/server/ConnectivityService.java b/services/java/com/android/server/ConnectivityService.java
index 6a8d692..78215b0 100644
--- a/services/java/com/android/server/ConnectivityService.java
+++ b/services/java/com/android/server/ConnectivityService.java
@@ -53,7 +53,7 @@
  */
 public class ConnectivityService extends IConnectivityManager.Stub {
 
-    private static final boolean DBG = false;
+    private static final boolean DBG = true;
     private static final String TAG = "ConnectivityService";
 
     // Event log tags (must be in sync with event-log-tags)
@@ -740,7 +740,6 @@
                 ++numConnectedNets;
             }
         }
-        if (DBG) Log.d(TAG, "numConnectedNets returning "+numConnectedNets);
         return numConnectedNets;
     }
 
@@ -766,10 +765,6 @@
     private void handleDisconnect(NetworkInfo info) {
 
         int prevNetType = info.getType();
-        if (DBG) {
-            Log.v(TAG, "Handle DISCONNECT for " + info.getTypeName() +
-                    (mNetAttributes[prevNetType].isDefault() ? ", a default network" : ""));
-        }
 
         mNetTrackers[prevNetType].setTeardownRequested(false);
         /*
@@ -878,11 +873,6 @@
         // do this before we broadcast the change
         handleConnectivityChange();
 
-        if (DBG) Log.v(TAG, "Sending DISCONNECT bcast for " +
-                info.getTypeName() +
-                (newNet == null || !newNet.isAvailable() ? "" : " other=" +
-                newNet.getNetworkInfo().getTypeName()));
-
         sendStickyBroadcast(intent);
         /*
          * If the failover network is already connected, then immediately send
@@ -975,8 +965,6 @@
     }
 
     private void handleConnect(NetworkInfo info) {
-        if (DBG) Log.d(TAG, "Handle CONNECT for " + info.getTypeName());
-
         int type = info.getType();
 
         // snapshot isFailover, because sendConnectedBroadcast() resets it
@@ -986,7 +974,6 @@
         // if this is a default net and other default is running
         // kill the one not preferred
         if (mNetAttributes[type].isDefault()) {
-            if (DBG) Log.d(TAG, "connecting to a default network");
             if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
                 if ((type != mNetworkPreference &&
                         mNetAttributes[mActiveDefaultNetwork].mPriority >
@@ -1016,7 +1003,6 @@
             mActiveDefaultNetwork = type;
         }
         thisNet.setTeardownRequested(false);
-        if (DBG) Log.d(TAG, "Sending CONNECT bcast for " + info.getTypeName());
         thisNet.updateNetworkSettings();
         handleConnectivityChange();
         sendConnectedBroadcast(info);
diff --git a/services/java/com/android/server/PackageManagerService.java b/services/java/com/android/server/PackageManagerService.java
index 5eb78c3..6289d4f 100644
--- a/services/java/com/android/server/PackageManagerService.java
+++ b/services/java/com/android/server/PackageManagerService.java
@@ -1997,7 +1997,6 @@
         parseFlags |= mDefParseFlags;
         PackageParser pp = new PackageParser(scanFile.getPath());
         pp.setSeparateProcesses(mSeparateProcesses);
-        pp.setSdkVersion(mSdkVersion, mSdkCodename);
         final PackageParser.Package pkg = pp.parsePackage(scanFile,
                 destCodeFile.getAbsolutePath(), mMetrics, parseFlags);
         if (pkg == null) {
@@ -4168,7 +4167,6 @@
             parseFlags |= mDefParseFlags;
             PackageParser pp = new PackageParser(tmpPackageFile.getPath());
             pp.setSeparateProcesses(mSeparateProcesses);
-            pp.setSdkVersion(mSdkVersion, mSdkCodename);
             final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
                     destPackageFile.getAbsolutePath(), mMetrics, parseFlags);
             if (pkg == null) {
diff --git a/test-runner/android/test/mock/MockContentProvider.java b/test-runner/android/test/mock/MockContentProvider.java
index 74f86d8..c3fe9c0 100644
--- a/test-runner/android/test/mock/MockContentProvider.java
+++ b/test-runner/android/test/mock/MockContentProvider.java
@@ -53,10 +53,6 @@
         return 0;
     }
 
-    public Uri insertEntity(Uri uri, Entity entities) throws RemoteException {
-        throw new UnsupportedOperationException("unimplemented mock method");
-    }
-
     @SuppressWarnings("unused")
     public IBulkCursor bulkQuery(Uri url, String[] projection, String selection,
             String[] selectionArgs, String sortOrder, IContentObserver observer, 
@@ -103,6 +99,9 @@
         throw new UnsupportedOperationException("unimplemented mock method");
     }
 
+    /**
+     * @hide
+     */
     public EntityIterator queryEntities(Uri url, String selection, String[] selectionArgs,
             String sortOrder) throws RemoteException {
         throw new UnsupportedOperationException("unimplemented mock method");
@@ -114,10 +113,6 @@
         throw new UnsupportedOperationException("unimplemented mock method");
     }
 
-    public int updateEntity(Uri uri, Entity entity) throws RemoteException {
-        throw new UnsupportedOperationException("unimplemented mock method");
-    }
-
     public IBinder asBinder() {
         throw new UnsupportedOperationException("unimplemented mock method");
     }
diff --git a/tests/AndroidTests/src/com/android/unit_tests/HeapTest.java b/tests/AndroidTests/src/com/android/unit_tests/HeapTest.java
index d21e6a3..d51cc26 100644
--- a/tests/AndroidTests/src/com/android/unit_tests/HeapTest.java
+++ b/tests/AndroidTests/src/com/android/unit_tests/HeapTest.java
@@ -485,7 +485,8 @@
         }
     }
 
-    @MediumTest
+    // TODO: flaky test
+    //@MediumTest
     public void testOomeLarge() throws Exception {
         /* Just shy of the typical max heap size so that it will actually
          * try to allocate it instead of short-circuiting.
diff --git a/tests/FrameworkTest/tests/src/com/android/frameworktest/view/BigCacheTest.java b/tests/FrameworkTest/tests/src/com/android/frameworktest/view/BigCacheTest.java
index b5e7473..02d5283 100644
--- a/tests/FrameworkTest/tests/src/com/android/frameworktest/view/BigCacheTest.java
+++ b/tests/FrameworkTest/tests/src/com/android/frameworktest/view/BigCacheTest.java
@@ -55,14 +55,14 @@
 
     @MediumTest
     public void testDrawingCacheBelowMaximumSize() throws Exception {
-        final int max = ViewConfiguration.getMaximumDrawingCacheSize();
+        final int max = ViewConfiguration.get(getActivity()).getScaledMaximumDrawingCacheSize();
         assertTrue(mTiny.getWidth() * mTiny.getHeight() * 2 < max);
         assertNotNull(createCacheForView(mTiny));
     }
 
     @MediumTest
     public void testDrawingCacheAboveMaximumSize() throws Exception {
-        final int max = ViewConfiguration.getMaximumDrawingCacheSize();
+        final int max = ViewConfiguration.get(getActivity()).getScaledMaximumDrawingCacheSize();
         assertTrue(mLarge.getWidth() * mLarge.getHeight() * 2 > max);
         assertNull(createCacheForView(mLarge));
     }
diff --git a/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/AndroidGraphicsTests.java b/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/AndroidGraphicsTests.java
index ac144e7..6e14e82 100644
--- a/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/AndroidGraphicsTests.java
+++ b/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/AndroidGraphicsTests.java
@@ -24,7 +24,7 @@
 import junit.framework.TestCase;
 
 /**
- * 
+ *
  */
 public class AndroidGraphicsTests extends TestCase {
 
@@ -40,24 +40,24 @@
 
     public void testMatrix() {
         Matrix m1 = new Matrix();
-        
-        assertFalse(m1.isIdentity());
-        
+
+        assertTrue(m1.isIdentity());
+
         m1.setValues(new float[] { 1,0,0, 0,1,0, 0,0,1 });
         assertTrue(m1.isIdentity());
-        
+
         Matrix m2 = new Matrix(m1);
-        
+
         float[] v1 = new float[9];
         float[] v2 = new float[9];
         m1.getValues(v1);
         m2.getValues(v2);
-        
+
         for (int i = 0 ; i < 9; i++) {
             assertEquals(v1[i], v2[i]);
         }
     }
-    
+
     public void testPaint() {
         _Original_Paint o = new _Original_Paint();
         assertNotNull(o);
@@ -65,7 +65,7 @@
         Paint p = new Paint();
         assertNotNull(p);
     }
-    
+
     public void textTextPaint() {
         TextPaint p = new TextPaint();
         assertNotNull(p);
diff --git a/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/BridgeTest.java b/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/BridgeTest.java
deleted file mode 100644
index c66ae37..0000000
--- a/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/BridgeTest.java
+++ /dev/null
@@ -1,275 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.layoutlib.bridge;
-
-import com.android.layoutlib.api.ILayoutResult;
-import com.android.layoutlib.api.IResourceValue;
-import com.android.layoutlib.api.IStyleResourceValue;
-import com.android.layoutlib.api.IXmlPullParser;
-import com.android.layoutlib.api.ILayoutResult.ILayoutViewInfo;
-
-import org.kxml2.io.KXmlParser;
-import org.xmlpull.v1.XmlPullParser;
-
-import java.io.File;
-import java.io.FileReader;
-import java.net.URL;
-import java.util.HashMap;
-import java.util.Map;
-
-import junit.framework.TestCase;
-
-public class BridgeTest extends TestCase {
-
-    /** the class being tested */
-    private Bridge mBridge;
-    /** the path to the sample layout.xml file */
-    private String mLayoutXml1Path;
-    private String mTextOnlyXmlPath;
-
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-
-        mBridge = new Bridge();
-        
-        // FIXME: need some fonts somewhere.
-        mBridge.init(null /* fontOsLocation */, getAttributeValues());
-        
-        URL url = this.getClass().getClassLoader().getResource("data/layout1.xml");
-        mLayoutXml1Path = url.getFile();
-
-        url = this.getClass().getClassLoader().getResource("data/textonly.xml");
-        mTextOnlyXmlPath = url.getFile();
-    }
-    
-    @Override
-    protected void tearDown() throws Exception {
-        super.tearDown();
-    }
-
-    // ---------------
-
-    /**
-     * Test parser that implements {@link IXmlPullParser}.
-     */
-    private static class TestParser extends KXmlParser implements IXmlPullParser {
-        public Object getViewKey() {
-            return null;
-        }
-    }
-
-    /**
-     * Mock implementation of {@link IStyleResourceValue}.
-     */
-    private static class StyleResourceValueMock extends ResourceValue
-            implements IStyleResourceValue {
-
-        private String mParentStyle = null;
-        private HashMap<String, IResourceValue> mItems = new HashMap<String, IResourceValue>();
-
-        StyleResourceValueMock(String name) {
-            super(name);
-        }
-
-        StyleResourceValueMock(String name, String parentStyle) {
-            super(name);
-            mParentStyle = parentStyle;
-        }
-
-        public String getParentStyle() {
-            return mParentStyle;
-        }
-
-        public IResourceValue findItem(String name) {
-            return mItems.get(name);
-        }
-
-        public void addItem(IResourceValue value) {
-            mItems.put(value.getName(), value);
-        }
-
-        @Override
-        public void replaceWith(ResourceValue value) {
-            super.replaceWith(value);
-
-            if (value instanceof StyleResourceValueMock) {
-                mItems.clear();
-                mItems.putAll(((StyleResourceValueMock)value).mItems);
-            }
-        }
-    }
-
-
-    public void testComputeLayout() throws Exception {
-        
-        TestParser parser = new TestParser();
-        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
-        parser.setInput(new FileReader(new File(mLayoutXml1Path)));
-
-        Map<String, Map<String, IResourceValue>> projectResources = getProjectResources();
-
-        Map<String, Map<String, IResourceValue>> frameworkResources = getFrameworkResources();
-        
-        int screenWidth = 320;
-        int screenHeight = 480;
-        
-        // FIXME need a dummy font for the tests!
-        ILayoutResult result = mBridge.computeLayout(parser, new Integer(1) /* projectKey */, 
-                screenWidth, screenHeight, false /* full render */,
-                160, 160f, 160f,
-                "Theme", false /* is project theme */,
-                projectResources, frameworkResources, null, null);
-                
-        display(result.getRootView(), "");
-    }
-
-    private Map<String, Map<String, Integer>> getAttributeValues() {
-        Map<String, Map<String, Integer>> attributeValues =
-            new HashMap<String, Map<String,Integer>>();
-        
-        // lets create a map for the orientation attribute
-        Map<String, Integer> attributeMap = new HashMap<String, Integer>();
-        
-        attributeMap.put("horizontal", Integer.valueOf(0));
-        attributeMap.put("vertical", Integer.valueOf(1));
-        
-        attributeValues.put("orientation", attributeMap);
-        
-        return attributeValues;
-    }
-
-    private Map<String, Map<String, IResourceValue>> getFrameworkResources() {
-        Map<String, Map<String, IResourceValue>> frameworkResources =
-            new HashMap<String, Map<String, IResourceValue>>();
-        
-        // create the style map
-        Map<String, IResourceValue> styleMap = new HashMap<String, IResourceValue>();
-        frameworkResources.put("style", styleMap);
-        
-        // create a button style.
-        IStyleResourceValue style = createStyle("Widget.Button",
-                "background",        "@android:drawable/something",
-                "focusable",        "true",
-                "clickable",        "true",
-                "textAppearance",   "?android:attr/textAppearanceSmallInverse",
-                "textColor",        "?android:attr/textColorBrightInverseNoDisable",
-                "gravity",          "center_vertical|center_horizontal"
-                );
-        styleMap.put(style.getName(), style);
-
-        // create the parent style of button style
-        style = createStyle("Widget",
-                "textAppearance", "?textAppearance");
-        styleMap.put(style.getName(), style);
-
-        // link the buttonStyle info in the default theme.
-        style = createStyle("Theme",
-                BridgeConstants.RES_STYLE, "buttonStyle",                      "@android:style/Widget.Button",
-                BridgeConstants.RES_STYLE, "textAppearance",                   "@android:style/TextAppearance",
-                BridgeConstants.RES_STYLE, "textAppearanceSmallInverse",       "@android:style/TextAppearance.Small.Inverse",
-                BridgeConstants.RES_COLOR, "textColorBrightInverseNoDisable",  "@android:color/bright_text_light_nodisable"
-                );
-        styleMap.put(style.getName(), style);
-
-        // create a dummy drawable to go with it
-        Map<String, IResourceValue> drawableMap = new HashMap<String, IResourceValue>();
-        frameworkResources.put("drawable", drawableMap);
-        
-        // get the 9 patch test location
-        URL url = this.getClass().getClassLoader().getResource("data/button.9.png");
-
-        IResourceValue drawable = new ResourceValue(BridgeConstants.RES_DRAWABLE, "something",
-                url.getPath());
-        drawableMap.put(drawable.getName(), drawable);
-        return frameworkResources;
-    }
-    
-    private Map<String, Map<String, IResourceValue>> getProjectResources() {
-        Map<String, Map<String, IResourceValue>> projectResources =
-            new HashMap<String, Map<String, IResourceValue>>();
-
-        // create the style map (even empty there should be one)
-        Map<String, IResourceValue> styleMap = new HashMap<String, IResourceValue>();
-        projectResources.put("style", styleMap);
-
-        return projectResources;
-    }
-
-
-    private void display(ILayoutViewInfo result, String offset) {
-
-        String msg = String.format("%s%s L:%d T:%d R:%d B:%d",
-                offset,
-                result.getName(),
-                result.getLeft(), result.getTop(), result.getRight(), result.getBottom());
-
-        System.out.println(msg);
-        ILayoutViewInfo[] children = result.getChildren();
-        if (children != null) {
-            offset += "+-";
-            for (ILayoutViewInfo child : children) {
-                display(child, offset);
-            }
-        }
-    }
-    
-    /**
-     * Creates a {@link IStyleResourceValue} based on the given values.
-     * @param styleName the name of the style.
-     * @param items An array of Strings. Even indices contain a style item name, and odd indices
-     * a style item value. If the number of string in the array is not even, an exception is thrown.
-     */
-    private IStyleResourceValue createStyle(String styleName, String... items) {
-        StyleResourceValueMock value = new StyleResourceValueMock(styleName);
-        
-        if (items.length % 3 == 0) {
-            for (int i = 0 ; i < items.length;) {
-                value.addItem(new ResourceValue(items[i++], items[i++], items[i++]));
-            }
-        } else {
-            throw new IllegalArgumentException("Need a multiple of 3 for the number of strings");
-        }
-        
-        return value;
-    }
-
-    // ---------------
-
-    public void testTextLayout() throws Exception {
-        
-        TestParser parser = new TestParser();
-        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
-        parser.setInput(new FileReader(new File(mTextOnlyXmlPath)));
-
-        Map<String, Map<String, IResourceValue>> projectResources = getProjectResources();
-        Map<String, Map<String, IResourceValue>> frameworkResources = getFrameworkResources();
-        
-        int screenWidth = 320;
-        int screenHeight = 480;
-
-        // FIXME need a dummy font for the tests!
-        ILayoutResult result = mBridge.computeLayout(parser, new Integer(1) /* projectKey */,
-                screenWidth, screenHeight, false /* full render */,
-                160, 160f, 160f,
-                "Theme", false /* is project theme */,
-                projectResources, frameworkResources, null, null);
-                
-        display(result.getRootView(), "");
-    }
-
-}
diff --git a/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/BridgeXmlBlockParserTest.java b/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/BridgeXmlBlockParserTest.java
index ef7442c..9e2987a 100644
--- a/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/BridgeXmlBlockParserTest.java
+++ b/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/BridgeXmlBlockParserTest.java
@@ -17,33 +17,18 @@
 package com.android.layoutlib.bridge;
 
 import org.kxml2.io.KXmlParser;
-import org.w3c.dom.Document;
 import org.w3c.dom.Node;
-import org.xml.sax.SAXException;
 import org.xmlpull.v1.XmlPullParser;
 
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.net.URL;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
+import java.io.InputStream;
 
 import junit.framework.TestCase;
 
 public class BridgeXmlBlockParserTest extends TestCase {
 
-    private String mXmlPath;
-    private Document mDoc;
-
     @Override
     protected void setUp() throws Exception {
         super.setUp();
-        URL url = this.getClass().getClassLoader().getResource("layout1.xml");
-        mXmlPath = url.getFile();
-        mDoc = getXmlDocument(mXmlPath);
     }
 
     @Override
@@ -54,7 +39,10 @@
     public void testXmlBlockParser() throws Exception {
         XmlPullParser parser = new KXmlParser();
         parser = new BridgeXmlBlockParser(parser, null, false /* platformResourceFlag */);
-        parser.setInput(new FileReader(new File(mXmlPath)));
+
+        InputStream input = this.getClass().getClassLoader().getResourceAsStream(
+            "/com/android/layoutlib/testdata/layout1.xml");
+        parser.setInput(input, null /*encoding*/);
 
         assertEquals(XmlPullParser.START_DOCUMENT, parser.next());
 
@@ -85,24 +73,8 @@
         assertEquals(XmlPullParser.END_TAG, parser.next());
         assertEquals(XmlPullParser.END_DOCUMENT, parser.next());
     }
-    
-    //------------
-    
-    private Document getXmlDocument(String xmlFilePath)
-            throws ParserConfigurationException, SAXException, IOException {
-        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
-        
-        // keep comments
-        factory.setIgnoringComments(false);
-        // don't validate our bogus DTD
-        factory.setValidating(false);
-        // we want namespaces
-        factory.setNamespaceAware(true);
-        
-        DocumentBuilder builder = factory.newDocumentBuilder();
-        return builder.parse(new File(xmlFilePath));
-    }
 
+    //------------
 
     /**
      * Quick'n'dirty debug helper that dumps an XML structure to stdout.
@@ -126,7 +98,7 @@
                 "DOCUMENT_FRAGMENT_NODE",
                 "NOTATION_NODE"
         };
-        
+
         String s = String.format("%s<%s> %s %s",
                 prefix,
                 types[node.getNodeType()],
@@ -134,7 +106,7 @@
                 node.getNodeValue() == null ? "" : node.getNodeValue().trim());
 
         System.out.println(s);
-        
+
         n = node.getFirstChild();
         if (n != null) {
             dump(n, prefix + "- ");
diff --git a/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/NinePatchTest.java b/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/NinePatchTest.java
index e667472..5314976 100644
--- a/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/NinePatchTest.java
+++ b/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/NinePatchTest.java
@@ -7,20 +7,21 @@
 import junit.framework.TestCase;
 
 public class NinePatchTest extends TestCase {
-    
+
     private NinePatch mPatch;
 
     @Override
     protected void setUp() throws Exception {
-        URL url = this.getClass().getClassLoader().getResource("button.9.png");
+        URL url = this.getClass().getClassLoader().getResource(
+                "/com/android/layoutlib/testdata/button.9.png");
 
         mPatch = NinePatch.load(url, false /* convert */);
     }
-    
+
     public void test9PatchLoad() throws Exception {
         assertNotNull(mPatch);
     }
-    
+
     public void test9PatchMinSize() {
         int[] padding = new int[4];
         mPatch.getPadding(padding);
@@ -28,8 +29,8 @@
         assertEquals(3, padding[1]);
         assertEquals(13, padding[2]);
         assertEquals(4, padding[3]);
-        assertEquals(38, mPatch.getWidth());
-        assertEquals(27, mPatch.getHeight());
+        assertEquals(36, mPatch.getWidth());
+        assertEquals(25, mPatch.getHeight());
     }
 
 }
diff --git a/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/TestClassReplacement.java b/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/TestClassReplacement.java
new file mode 100644
index 0000000..e0dc55f
--- /dev/null
+++ b/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/TestClassReplacement.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.layoutlib.bridge;
+
+import java.lang.reflect.Method;
+
+import junit.framework.TestCase;
+
+public class TestClassReplacement extends TestCase {
+
+    public void testClassReplacements() {
+        // TODO: we want to test all the classes. For now only Paint passes the tests.
+//        final String[] classes = CreateInfo.RENAMED_CLASSES;
+        final String[] classes = new String[] {
+                "android.graphics.Paint",               "android.graphics._Original_Paint"
+        };
+        final int count = classes.length;
+        for (int i = 0 ; i < count ; i += 2) {
+            loadAndCompareClasses(classes[i], classes[i+1]);
+        }
+    }
+
+    private void loadAndCompareClasses(String newClassName, String oldClassName) {
+        // load the classes
+        try {
+            Class<?> newClass = TestClassReplacement.class.getClassLoader().loadClass(newClassName);
+            Class<?> oldClass = TestClassReplacement.class.getClassLoader().loadClass(oldClassName);
+
+            compare(newClass, oldClass);
+        } catch (ClassNotFoundException e) {
+            fail("Failed to load class: " + e.getMessage());
+        }
+    }
+
+    private void compare(Class<?> newClass, Class<?> oldClass) {
+        // first compare the methods.
+        Method[] newClassMethods = newClass.getDeclaredMethods();
+        Method[] oldClassMethods = oldClass.getDeclaredMethods();
+
+        for (Method oldMethod : oldClassMethods) {
+            // we ignore anything that starts with native
+            if (oldMethod.getName().startsWith("native")) {
+                continue;
+            }
+            boolean found = false;
+            for (Method newMethod : newClassMethods) {
+                if (compareMethods(newClass, newMethod, oldClass, oldMethod)) {
+                    found = true;
+                    break;
+                }
+            }
+
+            if (found == false) {
+                fail(String.format("Unable to find %1$s", oldMethod.toGenericString()));
+            }
+        }
+
+        // TODO: check (somehow?) that the methods that were removed from the original class
+        // have been put back in the new class!
+        // For this we need the original unmodified class (ie renamed, but w/o the methods removed)
+    }
+
+    private boolean compareMethods(Class<?> newClass, Method newMethod,
+            Class<?> oldClass, Method oldMethod) {
+        // first check the name of the method
+        if (newMethod.getName().equals(oldMethod.getName()) == false) {
+            return false;
+        }
+
+        // check the return value
+        Class<?> oldReturnType = oldMethod.getReturnType();
+        // if it's the old class, or if it's a inner class of the oldclass, we need to change this.
+        oldReturnType = adapt(oldReturnType, newClass, oldClass);
+
+        // compare the return types
+        Class<?> newReturnType = newMethod.getReturnType();
+        if (newReturnType.equals(oldReturnType) == false) {
+            return false;
+        }
+
+        // now check the parameters type.
+        Class<?>[] oldParameters = oldMethod.getParameterTypes();
+        Class<?>[] newParemeters = newMethod.getParameterTypes();
+        if (oldParameters.length != newParemeters.length) {
+            return false;
+        }
+
+        for (int i = 0 ; i < oldParameters.length ; i++) {
+            if (newParemeters[i].equals(adapt(oldParameters[i], newClass, oldClass)) == false) {
+                return false;
+            }
+        }
+
+        return true;
+    }
+
+    /**
+     * Adapts a class to deal with renamed classes.
+     * <p/>For instance if old class is <code>android.graphics._Original_Paint</code> and the
+     * new class is <code>android.graphics.Paint</code> and the class to adapt is
+     * <code>android.graphics._Original_Paint$Cap</code>, then the method will return a
+     * {@link Class} object representing <code>android.graphics.Paint$Cap</code>.
+     * <p/>
+     * This method will also ensure that all renamed classes contains all the proper inner classes
+     * that they should be declaring.
+     * @param theClass the class to adapt
+     * @param newClass the new class object
+     * @param oldClass the old class object
+     * @return the adapted class.
+     * @throws ClassNotFoundException
+     */
+    private Class<?> adapt(Class<?> theClass, Class<?> newClass, Class<?> oldClass) {
+        // only look for a new class if it's not primitive as Class.forName() would fail otherwise.
+        if (theClass.isPrimitive() == false) {
+            String n = theClass.getName().replace(oldClass.getName(), newClass.getName());
+            try {
+                return Class.forName(n);
+            } catch (ClassNotFoundException e) {
+                fail("Missing class: " + n);
+            }
+        }
+
+        return theClass;
+    }
+}
diff --git a/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/button.9.png b/tools/layoutlib/bridge/tests/com/android/layoutlib/testdata/button.9.png
similarity index 100%
rename from tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/button.9.png
rename to tools/layoutlib/bridge/tests/com/android/layoutlib/testdata/button.9.png
Binary files differ
diff --git a/tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/layout1.xml b/tools/layoutlib/bridge/tests/com/android/layoutlib/testdata/layout1.xml
similarity index 100%
rename from tools/layoutlib/bridge/tests/com/android/layoutlib/bridge/layout1.xml
rename to tools/layoutlib/bridge/tests/com/android/layoutlib/testdata/layout1.xml